text:
Q: All buttons generate same event, generate same output I've written a code that generates a simple rectangle in the frame and changes the color of an already existing circle on the frame.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class DrawRect extends JPanel{
     public void paintComponent(Graphics g){
          Graphics2D g2 = (Graphics2D)g;

         g2.draw(new Rectangle(200,200,200,200));
    }
}

class FillOval extends JPanel{
     public void paintComponent(Graphics g){
           Graphics2D g2 = (Graphics2D)g;

           int red = (int)(Math.random()*255);
           int green = (int)(Math.random()*255);
           int blue  = (int)(Math.random()*255);
           Color startColor = new Color(red,green,blue);

           red = (int)(Math.random()*255);
           green = (int)(Math.random()*255);
           blue = (int)(Math.random()*255);

          Color endColor = new Color(red,green , blue);
          GradientPaint gradient  = new GradientPaint(70,70,startColor,150,150,endColor);
          g2.setPaint(gradient);
          g2.fillOval(70,70,100,100);
    }
}

class MainGui {

     public static void main(String[] args){
             MainGui gui = new MainGui();
             gui.go();
    }
JFrame frame;
FillOval ov = new FillOval();
void go(){

  frame = new JFrame();
  JButton colorButton = new JButton("change color");
  JButton rectButton = new JButton("draw rectangle");

  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  colorButton.addActionListener(new colorListener());
  rectButton.addActionListener(new rectListener());

  frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
  frame.getContentPane().add(BorderLayout.WEST, rectButton);
  frame.getContentPane().add(BorderLayout.CENTER, ov);

  frame.setSize(500,500);
  frame.setVisible(true);
 }

 class colorListener implements ActionListener{
       public void actionPerformed(ActionEvent ev){
            frame.repaint();
   }
}

 class rectListener implements ActionListener{
      public void actionPerformed(ActionEvent ev){
           DrawRect rect = new DrawRect();
           frame.add(rect);
           frame.revalidate();
           frame.repaint();
       }
}
}

Now, the problem is that rectButton button is changing the color of the circle in the frame along with generating a rectangle in the frame.
It has nothing to do with the event of colorButton button. Why is it behaving in such a way? And how should I fix it?

A: Calling repaint triggers the call of paintComponent where the color will always be chosen randomly. You will need to define endColor as a member of a class, initialized with null. In your paintComponent method check it against null and if it is null, initialize it. You will need to initialize it at colorListener as well. And in paintComponent, use the endColor member. This way you will not redefine endColor whenever paintComponent is called. Since you need to initialize endColor at multiple places, it is a good idea to implement a method for it and call that method whenever the color needs to be initialized to avoid code duplication.


text:
Q: Use VBA to copy cells in a Range that contain specific characters I need to be able to copy cells from one column to another that contain specific characters. In this example they would be ^ and * the characters can be in any order in the cell.
Here is an example :

It looks like I might be able to use the InStr function in VBA to accomplish this if I am not mistaken.
Run a loop for each item in the list and check it with something like the following:
IF InStr(1,Range("A" & i), "^") <> 0 AND InStr(1, Range("A" & i), "*") <> 0 THEN

'copy cell to another place

End If

or might there be a more elegant solution?

A: I can't see your image form where I am, but Like is generally easier and faster than Instr(). You could try something like this:
If Range("A" & i) Like "*[*^]*[*^]*" Then

meaning you look for some text, then * or a ^, more text, then * or *, more text
For detailed syntax, look here.

A: Option for no loops - use Arrays and Filter
Option Explicit
Sub MatchCharacters()
    Dim src As Variant, tmp As Variant
    Dim Character As String, Character2 As String

    Character = "*"
    Character2 = "^"
    ' Replace with your sheetname
    With Sheet1
        src = Application.Transpose(Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1)))
        tmp = Filter(Filter(src, Character), Character2)

        .Range(.Cells(2, 3), .Cells(.Cells(1, 3).End(xlDown).Row, 3)).ClearContents
        If UBound(tmp) > -1 Then
            With .Cells(2, 3)
                Range(.Offset(0, 0), .Offset(UBound(tmp), 0)).Value2 = Application.Transpose(tmp)
            End With
        End If
    End With
End Sub

Or use as a function with unlimited character searching
Public Function MatchCharacters(arr As Variant, ParamArray Characters() As Variant) As Variant
    Dim i As Long
    For i = LBound(Characters) To UBound(Characters)
        arr = Filter(arr, Characters(i))
    Next i
    MatchCharacters = arr
End Function

Sub test()
    Dim tmp As Variant

    With Sheet1
        tmp = Application.Transpose(Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1)))

        tmp = MatchCharacters(tmp, "*", "^")

        If UBound(tmp) > -1 Then
            With .Cells(2, 3)
                Range(.Offset(0, 0), .Offset(UBound(tmp), 0)).Value2 = Application.Transpose(tmp)
            End With
        End If
    End With
End Sub

A: Edit
Looking at this again and being inspired by Tom's answer about filtering, it got be thinking... the AdvancedFilter can do exactly what you're looking to do. It's designed into the spreadsheet side of Excel, but you can use it from VBA.
If you only want to work out of VBA, or if your filter won't be changing often, then this probably is not your best choice... but if you want something that's more visible and flexible from the workbook side of things, this would be a good choice.
To manually run Advanced Filter...

Example code and dynamic filter scenario...
(Notice you can use equations with it)
Sub RunCopyFilter()
    Dim CriteriaCorner As Integer
    CriteriaCorner = Application.WorksheetFunction.Max( _
    Range("B11").End(xlUp).Row, _
    Range("C11").End(xlUp).Row, _
    Range("D11").End(xlUp).Row)
    [A4:A10].AdvancedFilter xlFilterCopy, Range("B4:D" & CriteriaCorner), [E4:E10], True
End Sub

Named Ranges
AdvancedFitler automatically creates NamedRanges for it's criteria and output. That can be handy because you can reference the NamedRange as Extract and it will dynamically update.

Original Post
Here's some code for a "tolerant" InStr() function from a similar post I made... it isn't tailored exactly to your example, but it gets at the basic point of character-by-character analysis.
Function InStrTolerant(InputString As String, MatchString As String, Optional CaseInsensitiveChoice = False, Optional Tolerance As Integer = 0) As Integer
'Similar to InStr, but allows for a tolerance in matching

Dim ApxStr As String 'Approximate String to Construct
Dim j As Integer 'Match string index
j = 1
Dim Strikes As Integer
Dim FoundIdx As Integer

For i = 1 To Len(InputString)

    'We can exit early if a match has been found
    If StringsMatch(ApxStr, MatchString, CaseInsensitiveChoice) Then
        InStrTolerant = FoundIdx
        Exit Function
    End If

    If StringsMatch(Mid(InputString, i, 1), Mid(MatchString, j, 1), CaseInsensitiveChoice) Then
        'This character matches, continue constructing
        ApxStr = ApxStr + Mid(InputString, i, 1)
        j = j + 1
        FoundIdx = i
    Else
        'This character doesn't match
        'Substitute with matching value and continue constructing
        ApxStr = ApxStr + Mid(MatchString, j, 1)
        j = j + 1
        'Since it didn't match, take a strike
        Strikes = Strikes + 1
    End If

    If Strikes > Tolerance Then
        'Strikes exceed tolerance, reset contruction
        ApxStr = ""
        j = 1
        Strikes = 0
        i = i - Tolerance
    End If
Next

If StringsMatch(ApxStr, MatchString, CaseInsensitiveChoice) Then
    InStrTolerant = FoundIdx
Else
    InStrTolerant = 0
End If

End Function

Also, I always feel obliged to mention Regex in these cases. Although it isn't the easiest to use, especially with VBA, it is designed exactly for powerful complex matching.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access file on docker using JavaScript/Node Is there a way to programatically access a file on a container (docker) during execution. I've tried using node-docker-api just to set things up in the first instance, and establish a connection:
const docker = new Docker({
    "host": "tcp://docker:port"
});

// List
docker.container.list()
// Inspect
    .then(containers => containers[0].status())
    .then(container => container.top())
    .then(processes => console.log(processes))
    .catch(error => console.log(error));

where "port" is the 4 digit port number. But I get this error message:
{ Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1081:14)
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80 }

UPDATE:
I have done something similar in Java with dockerjava using https://github.com/docker-java/docker-java/issues/253 and httphijack - https://gist.github.com/missedone/76517e618486db746056
ExecCreateCmdResponse execCreateResp = dck.execCreateCmd(cid).withCmd("bash")
        .withAttachStderr().withAttachStdout().withAttachStdin().withTty(false).exec();

HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");

HttpHijack ws = new HttpHijack(new URI("http://127.0.0.1:2376/v1.19/exec/" + execCreateResp.getId() + "/start"));
String payload = "{\"Detach\": false,\"Tty\": false}";
ws.post(headers, payload);

and then copying the file from the container using:
try (TarArchiveInputStream tarStream = new TarArchiveInputStream(
    docker.copyArchiveFromContainerCmd(containerId, "/home/seluser/Downloads/" + fileName).exec())) {
    unTar(tarStream, new File(filePath));
    return;
}catch(NotFoundException e){
    e.printStackTrace();
}

But I can't seem to find an approach to achieve the above using javascript/node

A: Given that the files inside the container are ephemeral you should be careful if your code somehow relies on that files.
The best practice is to use docker volumes to store data.
In your case, if you can store files in a docker volume, then you can run your code from another container and see that files from it. So, containers will share the same storage, which is not ephemeral and will survive container restarts.
If docker volumes are not your case, then the single idea in my mind is to play with Docker REST API and especially with an Exec method.
Using this method you can execute the Linux commands in a container.

UPDATE 1:
If your program runs on a host machine and you need to have access to data generated by docker volume, you can also bind host machine directory to the directory inside docker container.
An example: docker run -v /host/folder:/container/folder <your_image>
This way any change in docker folder will be reflected on folder in your host machine - so you can access them.
Read more

UPDATE 2:
You can use Docker REST API to execute commands inside docker container in the next way:

*

*Enable TCP access to the REST API:
Edit /lib/systemd/system/docker.service and change the next line:
ExecStart=/usr/bin/dockerd -g /data/docker -H fd:// to ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:2375
and save the file.
Then systemctl daemon-reload and service docker restart. Now you should be able to access the API on http://127.0.0.1:2375 - you should get { "message": "page not found" } as a response.

*Create an Exec object using REST API, example:
curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"AttachStdout": true,"AttachStderr": true,"Cmd": ["date"]}' \
http://127.0.0.1:2375/v{dockerVersion}/containers/{containerId}/exec

Here:

*

*dockerVersion - the version of your docker engine, could be retrieved using docker version command (see version fo the server, in my case it's 1.38 - so in URL it will be like v1.38 don't forget v)

*containerId - id of your container in docker, could be retrieved by following command: curl http://127.0.0.1:2375/v{dockerVersion}/containers/json
In response to /containers/{containerId}/exec you should get something like: {"Id": "{objectId}"}

*Execute previously created command:
curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"Detach": false,"Tty": false}' \
http://127.0.0.1:2375/v{dockerVersion}/exec/{objectId}/start

Here:

*

*objectId - id returned from docker API in previous step (STEP 2)

As a response you should get a plain text - the output of your command.
NOTE: The Cmd in JSON body is an array, so you can specify multiple commands.

A: You can use the Docker API /getAchive method to extract files from a container, and then untar them
There is a NodeJS implementation of the docker API to use on the server side dockerode
 npm i dockerode

Then import it and run the container where the file is
var Docker = require('dockerode');
var docker = new Docker({socketPath: '/var/run/docker.sock'}); //or whatever path to your socket
let file="abs/path/in/container/somefile.file"
let tag="docekerImageTag"  //"repo/image" //"johndoe/docker_image"

runContainer(tag,"foo").then(container=>{
  getFile(container,file,ws)
})

function runContainer(containerName,param){
 return docker.run(
    containerName,
    ['Rscript', 'random.rscript','--test',`${param}`,],
    [process.stdout, process.stderr], {Tty:false}, //send only stdout if you don't want the split no tty needed
  ).then(function(data){
      var output=data[0]
      var container=data[1]
      return container
    },rej=>{
      console.log({rej})
      return rej
    }
  )
}
function getFile(container,file,ws){
  container.getArchive({path:file}).then(file=>{
    if(ws) ws.sendMsg(file) //send it somewhere I'm using a websocket. This will give you a stream with the tar file.
//With the websocket you might have to parse the BufferList and iteratively send the buffers and assemble it on the other end
//fs.write(file,path,"UTF8") is another option. Though I think you still have to iterate the bufferList for "fs"
  })
}

Don't forget to untar the file if you want to use it right away.
There is also a client side JavaScript package to untar the stream call js-untar that works well once you get it to the client side via websocket/other.


text:
Q: XAML WP8 - ScrollViewer doesnt take into account orientation Im working on an app for Win Phone 8 and need to make a settings screen.
I created a user control for this.
...omitted the beginning stuff...
<Grid x:Name="LayoutRoot" Opacity="0.995" VerticalAlignment="Top">
    <ScrollViewer
        Name="scrollViewer"
        Margin="0"
        VerticalAlignment="Top"
        VerticalScrollBarVisibility="Hidden" Background="#CC000000" Opacity="0.995" HorizontalScrollBarVisibility="Disabled">

        <StackPanel Orientation="Vertical" VerticalAlignment="Top" Margin="0">
            <RichTextBox x:Name="MenuLabel" Height="100" HorizontalAlignment="Left" VerticalAlignment="Center">
                <Paragraph>
                    <Run Text="[Menu]"/>
                </Paragraph>
            </RichTextBox>

I have all my setting options in the stack panel.
While im in portait orientation, everything works fine, listed correctly, scrolls correctly by swiping upward from the bottom of the phone to the top. However, when I rotate the phone to landscape orientation, the control shows correctly but the swiping remains the same. So instead on swiping up from one side to the other, I still need to swipe from the bottom of the phone to the top -- essentially swiping right to left to make the control scroll up.
Am I missing something? Did I forget a setting somewhere? Ive scoured the internet for any clues / advice and could not find anything relevant.
Any help or suggestions would be greatly appreciated.
Thanks,
-G

A: Remove the Opacity property on your ScrollViewer and your Grid, and it will work!
    <Grid x:Name="LayoutRoot"
      VerticalAlignment="Top">
    <ScrollViewer Name="scrollViewer"
                  Margin="0"
                  VerticalAlignment="Top"
                  VerticalScrollBarVisibility="Hidden"
                  Background="#CC000000"
                  HorizontalScrollBarVisibility="Disabled">
        <StackPanel Orientation="Vertical"
                    VerticalAlignment="Top"
                    Margin="0">
            <RichTextBox x:Name="MenuLabel"
                         Height="100"
                         HorizontalAlignment="Left"
                         VerticalAlignment="Center">
                <Paragraph>
                    <Run Text="[Menu]" />
                </Paragraph>
            </RichTextBox>


text:
Q: Unable to find ejabberd/src folder - Ubuntu I am a newbie in Ubuntu and I am installing Ejabberd in Ubuntu. As of now everything seems ok and I am able to make it up and running. Now I need to install the patch from the link
http://www.ejabberd.im/aclpopulatesr
I was able to get the patch from the link
http://www.ejabberd.im/files/contributions/mod_shared_roster.erl.diff
But when I try to copy to Ejabberd folder, I am not able to find the src folder. I believe I am missing it or it is somewhere hidden. Could anyone help me in installing this patch in Ubuntu. That will be very helpful. Thanks for your time

A: The package does not contain sources. You need to download them separately if you want to compile your own version.
apt-get source ejabberd
apt-get install build-essential # make, compiler, system libraries, deb toolchain
apt-get build-dep ejabberd # any packages required to build this particular package

Now patch, build, install.
This is obviously just a quick whirlwind intro. You probably want to google a few examples to get a fuller picture. There are several for ejabberd alone.
In particular, you need to understand how to give your local package a version number which is higher than the current official package, but lower than any future official upgrade.
Alternatively, find someone who has already done this and published the resulting package in a PPA. (Obviously, trust them to not trojanize the binary, or don't install it.)


text:
Q: Помогите разобраться с учебным заданием в си Есть учебное задание на бросание костей (бросание 6000 раз и вывод "таблицы") в принципе элементарное. Понимаю как всё работает, но не получается ответ.
вот код:
#include <stdio.h>
#include <stdlib.h>

main()
{
  int face, roll, frequency1 = 0, frequency2 = 0, frequency3 = 0, frequency4 = 0, frequency5 = 0, frequency6 = 0;

  for (roll = 1; roll <= 6000; roll++) // прокручивание 6000 раз
    face = 1 + rand() % 6; // Добавление смещения и использование функции rand cо сдвигом масштабирования на 6

  switch (face)
  {
    case 1:
      ++frequency1;  // добавление в переменную 1
      break;         // конец цикла
    case 2:
      ++frequency2;
      break;
    case 3:
      ++frequency3;
      break;
    case 4:
      ++frequency4;
      break;
    case 5:
      ++frequency5;
      break;
    case 6:
      ++frequency6;
      break;
  }

  printf("%s%13s\n", "Face", "Frequency");
  printf("1%13d\n", frequency1);
  printf("1%13d\n", frequency2);
  printf("1%13d\n", frequency3);
  printf("1%13d\n", frequency4);
  printf("1%13d\n", frequency5);
  printf("1%13d\n", frequency6);

  return 0;
}

Получаю при выходе:
Face    Frequency
1            0
1            0
1            0
1            0
1            1
1            0

Можете указать на мою ошибку?
A: Swith-case в блок фора фозьми. У тебя без тела только face = 1 + rand() % 6; 6000 раз выполняется.


text:
Q: use ReactJS to .map through response of Express API I have an Express API that responds with data from MongoDB when requested upon mounting of a reactJS component.
app.get('/api/characters', function(req, res) {
  var db = req.db;
  var collection = db.get('usercollection');
  collection.find({},{},function(e,docs){
    res.send({
      data: docs
    });
  });
});

Code for Characters component :
export default class Characters extends React.Component {

    constructor(props) {
    super(props);
    this.state = CharactersStore.getState();
    this.onChange = this.onChange.bind(this);
    }
    componentDidMount() {
        CharactersStore.listen(this.onChange);
        CharactersActions.getCharacters('http://localhost:3000/api/characters');
    }
    componentWillUnmount() {
      CharactersStore.unlisten(this.onChange);
    }
    onChange(state) {
    this.setState(state);
  }
    render() {
        return (

{this.props.route.header}

                <CharacterList data={this.state.characters}/>

        )
    }
}

Code for Characters component  Action
class CharactersActions {
  constructor() {
    this.generateActions(
      'getCharactersSuccess',
      'getCharactersFail'
    );
  }
  getCharacters(query) {
    requestPromise(query)
      .then((res) => {
        this.actions.getCharactersSuccess(res)
      }).catch((err) => {
        console.log('error:', err);
        this.actions.getCharactersFail(err)
      })
  }
}

export default alt.createActions(CharactersActions);

Code for Characters component  Store
class CharactersStore {
  constructor() {
    this.bindActions(CharactersActions);
    this.characters = [''];
    this.isLoading = true;
  }
  getCharactersSuccess(res) {
    this.characters = res;
    this.isLoading = false;
  }
  getCharactersFail(err) {
    toastr.error(err.responseJSON && err.responseJSON.message || err.responseText || err.statusText);
  }
}

export default alt.createStore(CharactersStore);

The Characters component above requests the API upon mounting and sends the response data along to the store to be saved into State.
I then pass the Characters state into the child component CharacterList as props (named data)
Characters List Component
export default class CharacterList extends React.Component {

    constructor(props) {
    super(props);
    }

    render() {

        return (

        {console.log(this.props.data)}

        // THIS IS WHERE I AM TRYING TO .MAP THROUGH THE RESULTS

        )
    }
}

I am trying to use .map to loop through the returned data but am a little unsure on how to proceed, any advice would be appreciated. Data is being returned as follows:
{
  "data": [
    {
      "_id": "58d5044b0898f816066227f1",
      "character": "Luke Skywalker"
    },
    {
      "_id": "58d504c60898f816066227f2",
      "character": "Obi Wan Kenobi"
    },
    {
      "_id": "58d504c60898f816066227f3",
      "character": "Han Solo"
    }
  ]
}

A: You want to set res.data as your characters store.
getCharactersSuccess(res) {
  this.characters = res.data; // <--
  this.isLoading = false;
}

Then you can map over the data array, and not the full response:

const data = [
  {
    _id: '58d5044b0898f816066227f1',
    character: 'Luke Skywalker'
  },
  {
    _id: '58d504c60898f816066227f2',
    character: 'Obi Wan Kenobi'
  },
  {
    _id: '58d504c60898f816066227f3',
    character: 'Han Solo'
  }
];

const Character = ({ data }) =>
{data.character}
;

class CharacterList extends React.Component {
  render() {
    return (

        {this.props.data.map((character, i) => (
          <Character key={i} data={character} />
        ))}

    );
  }
}

ReactDOM.render(<CharacterList data={data} />, document.getElementById('root'));

A: It is simple.I dont know where you confused. try this

{
    Array.isArray(this.props.data)&& this.props.data.map((val,index)=>{
          return val
        })
}


text:
Q: Understanding $PROP$ set in the book Logic and Structure (Van Dalen). Working on the book: Dirk van Dalen. "Logic and Structure (Universitext)" (p. 18)

Definition 1.1.2 The set PROP of propositions is the smallest set X with the properties

$
\begin{array}{rl}
\rm(i)&p_i\in X(i\in N),\bot\in X,\\
\rm(ii)&\varphi,\psi\in X\Rightarrow(\varphi\wedge\psi),(\varphi\vee\psi),(\varphi\to\psi),(\varphi\leftrightarrow\psi)\in X,\\
\rm(iii)&\varphi\in X\Rightarrow(\neg\varphi)\in X.\\
\end{array}
$

I would like to know:

$p_i\in X(i\in N),\bot\in X$

*

*How can I instantiate this statement when verifiyng a string of symbols belongs to PROP ?

*Is the comma an and connective ?

*What is $N$?

*Why is bottom symbol there ?

$((p \land q) \to p)$

*

*How can I show this statement belongs to PROP ?

P.S.: I am already aware of similar questions but they do not address my questions, I think.

A:
$p_i\in X(i\in N),\bot\in X$

*

*How can I instantiate this statement when verifiyng a string of symbols belongs to PROP ?

You can instantiate any propositional symbol or $\bot$: $p_1$ is $\in PROP$ according to this clause, $p_{354}$ is $\in PROP$ according to this clause, $\bot$ is $\in PROP$ according to this clause.

*

*Is the comma an and connective ?

Yes.

*

*What is $N$?

It should be $\mathbb{N}$. The $(i \in N)$ just indicates that the $i$'s are running indices to number the propositional symbols.

*

*Why is bottom symbol there ?

Because it is an atomic formula. Unlike the other connectives, it does not take any other formulas to form a new formula, and thus belongs in the base case together with the propositional symbols.

$((p \land q) \to p)$

*

*How can I show this statement belongs to PROP ?

Strictly speaking you can't, because according to the definition introduced up to this point, there exist only indexed propositional symbols starting iwth $p$. But it is customary to use $p, q, r$ in practice; if we incoporate these into clause (i), one can prove by induction on the structure of the formula:

*

*$p \in PROP$ (by (i), with $p_i = p$).

*$q \in PROP$ (by (i), with $p_i = q$).

*Since $p \in PROP$ and $q$ in $PROP$, $(p \land q) \in PROP$ (by (ii), with $\phi = p$ and $\psi = q$).

*Since $(p \land q) \in PROP$ and $p \in PROP$, $((p \land q) \to p) \in PROP$ (by (ii), with  $\phi$ = $(p \land q)$ and $\psi = p$).


text:
Q: pgRouting gives fragmented results when trying to calculate route I have a road network and I used pgr_createTopology and pgr_nodeNetwork to convert it for use in pgRouting library. However the results are fragmented and there is no continuous path. Furthermore I have to give source and target values instead of ID in the below query. here 747 and 311 are source and target values from table rather than IDs.

pgr_dijkstra('
    SELECT id, source::int, target::int, length::double precision AS cost FROM guru_noded',
    747, 311, false, false);

I am new to this.

A: Probabaly your "snapping tolerance" parameter did not match with the unit of your data, when you ran pgr_createTopology.
The dimension of the tolerance parameter depends on your data projection. Usually it's either "degrees" or "meters".

A: have you tried another solution?
If you just want to calculate the faster or shorter path, just use the network analysis tool from QGIS
http://docs.qgis.org/2.2/pt_PT/docs/training_manual/vector_analysis/network_analysis.html


text:
Q: How do I restore Windows 7 from a System Image to a Boot Camp partition without formatting? I had a 70GB Boot Camp partition on my iMac that I wanted to increase the size of, so after creating a system image (.vhd) on an external FW drive of the Boot Camp partition using Windows Backup and Restore, I removed the Boot Camp partition from within OS X and re-created one that is now 140GB.
When I go to restore the system image using the Windows 7 installation disc or the repair disc, it says that when restoring the image, the entire [physical?] disk is going to be erased and formatted so that the image can be restored to it. (I don't see any options to choose just a partition!)
I've considered that there may be a command line utility on the Windows 7 install disc to restore the VHD to the partition, but can't find any documentation for such. Is there a cost-free way to just restore the system image backup to the new partition while preserving the OSX partition?

EDIT:
Basically what I am saying is that when installing Windows 7, there is an option to install to a specific partition on the physical disk, but when restoring, I do not see that option...

UPDATE: (bounty)
I am still looking for a way to restore a VHD image to an NTFS formatted partition on a hard drive. Specifically a boot camp partition on a Mac.
I really don't understand why Windows won't allow this, although it allows installing to a partition...

A: I would suggest to first install Windows 7 on the new partition as a new installation.
Then, within Windows 7, Restore your computer from a system image backup using Control Panel -> Recovery -> Advanced recovery methods -> Use a system image you created earlier to recover your computer, and then follow the steps.
If worse comes to worst, you can always mount the .vhd in Disk Management to retrieve your data.
EDIT
I have found new info from this article using Acronis True Image Home 2011 (trial version available):
Restoring Windows 7 VHD Backup Files with Acronis True Image Home 2010.
The article says:

Windows 7 has a special System
  Reserved Partition, which is hidden
  and contains boot files. This
  partition can be viewed in Windows
  Disk Management (Start-Run ->
  diskmgmnt.msc).
When making an image of your Windows
  system using the Windows 7 Backup
  tool, it will create a separate .vhd
  file for each partition that is in the
  system, including the System Reserved
  Partition.
If you choose to restore your system
  partition from the created Windows 7
  Backup .vhd files, you will need to
  restore the whole disk where this
  system partition is.
Solution

*

*Boot from Acronis Bootable Media and select Acronis True Image Home
  (Full version)

*Click Recovery, browse to your Windows 7 Backup .vhd files and select
  any of the files

*Once selected, right-click on the .vhd file and select Recover

*Select Recover whole disks and partitions and click Next

*Check the partition to recover

This approach has failed if you are warned that all data on the
destination disk will be erased:

A: Your Mac OS X system should be intact.
Windows 7 "see" just bootcamp partition as HDD. Is there size of hard drive? to help you figure out?
usually bootcamp partition looks like last with BOOTCAMP name on it.
If your restore will be unsuccessful,
Install fresh copy of windows 7 to partition what you created.
try to use virtualbox (virtualbox.org) or this method to access your files:
http://www.gilsmethod.com/how-to-mount-vhd-files-without-virtual-pc
Next time use winclone free software to change win bootcamp partition
Or Paragon (trial or buy)

A: This is not the most direct approach, and would be inconvenient, but would probably be the safest.
I would recommend that you restore the VHD to a different computer hard drive - either an external drive, a spare one you may have lying around, a different computer if you have one you don't care about — anywhere you can. Then, use a different imaging suite (with the capability to restore to a particular partition) to create an image of that, then using that, restore to your original machine.

A: A simple solution would be to convert the vhd disk to a raw disk file, (which would take up 70gb) then 'dd' it to the given partition. qemu-img, which is part of QEMU, can handle the conversion. (You would obviously have to install qemu on the osx side)
qemu-img convert -f vhd -O raw YourW7Disk.vhd OutputDiskImage.raw

This would, as it is a raw disk image, require 70gb of space. You would then, after creating the raw disk file:
dd if=OutputDiskImage.raw of=/dev/disk0s2

Replacing disk0s2 with the path to the partition device node. You can find the partition device node name in Disk Utility.
Obviously, these commands would have to be run on the OSX side.
This is all assuming that the VHD disk is an image of just the W7 partition, and has the bootsector/etc intact.
This, of the solutions I have seen, is the easiest. It can be done in the already installed system, with minimal effort and time. The only thing you would have to install is qemu (which provides qemu-image iirc), which you can get through macports/brew/fink.

A: Here is how I think one can restore the vhd to a physical partition, into a partition of 140 GB. I assume that the vhd is on an external disk drive. You will need a partition manager tool with a bootable CD. A free one is MiniTool Partition Wizard Bootable CD.

*

*Re-partition the 140 GB partition into 2 partitions of 70 GB and format them as NTFS. You can either format as FAT32 by using OS X "Disk Utility" in /Applications/Utilties to format as "MS-DOS File System". Or (preferred) you can use the MiniTool bootable CD to do both the partitioning and format directly in NTFS. Be careful not to destroy any other Mac partition and ensure that the first partition is exactly the same size as when it was backed-up to the vhd.
The two partitions should now be visible to the Windows 7 boot installation DVD.

*Install Windows 7 into the first partition. If possible, create the partition in NTFS format. Else, Convert a FAT or FAT32 Volume to NTFS in Windows 7 after the installation.

*Try to use the backup utility to restore the vhd. If successful, use the Windows Disk Manager to erase the second 70 GB partition and resize the first (system) partition to include the second. If restoring the vhd has failed, continue to the next step.

*If required, in Windows 7 format the second drive as NTFS if it is not already in NTFS and assign it a drive letter.

*In Disk Management, Mount a VHD Within Windows 7 as a virtual disk.

*Use Control Panel / Folder Options / View tab, set "Show hidden files and folders" and unset "Hide protected operating system files" and press OK.

*Copy all files from the vhd virtual disk to the second partition.

*Use MiniTool to erase the first partition and move the second one in its place.

*Try to boot into Windows. If unsuccessful, try to Do a Repair Install to Fix Windows 7.

*If successful, use the Windows Disk Manager to resize the system partition to include the unused space left when you moved the second partition.

There is of course no way that I can test if my above advice will really work, but let me know if you have any difficulties.

A: You could try to convert the VHD to a WIM file and use ImageX to apply the WIM to the new partition.  I haven't tried this but it is an option to explore.
This will require the The Windows® Automated Installation Kit (AIK) for Windows® 7
Mount the VHD (as read only) in your host system:
- diskmgmt.msc
- Action > Attach VHD
- check Read-Only
- select the VHD. Let us assume that it has the letter D: assigned.
Then use imagex to create the WIM:
imagex /compress fast /flags "Ultimate" /check /capture D: C:\image.wim "Windows 7 Ultimate"

Afterwards boot from a Windows PE disk and apply the image with the following command:
imagex /apply d:\image.wim 1 c:\ /verify

Microsoft ImageX reference

A: I happened to have an old Mac that didn't have anything on it, so losing Mac OS wasn't an issue for me with that particular machine. For that reason, I tried restoring from an image directly from the Windows 7 Ultimate CD, and not only did the restore succeed, but the warning was inaccurate, I didn't lose anything! If you are reading this, go ahead and try it... the worst that can happen is that you do lose Mac OS, but that is what Time Machine is for, right?
EDIT: I did this process again on my primary Mac. Oddly enough, the Macintosh HD partition was reformatted to FAT32, but the installation remained. Both Windows 7 and Lion worked independently, and I could view Mac from Windows, but not Windows from Mac. The Bootcamp partition wouldn't mount in Disk Utility, either.
The problem, however, is that since Macintosh HD became FAT32, the boot camp assistant gave an error saying that the startup disk is not supported. Fortunately, I made backups of both Mac and Windows, but I will have to restore everything and lose the last week of changes to my Windows installation. Not terrible (for me), but I would like to advise against trying my solution.

A: Step 2 Point 7 from here:
http://www.sevenforums.com/tutorials/675-system-image-recovery.html
Format and repartition disks box:
NOTE: Special thanks to MJF for this addition.
1) Grayed out and selected
You are forced to have the whole disk formatted and repartitioned to match the partition structure of the disk the image was made from. This can occur when restoring an image to a new disk or the original disk with a modified partition structure. Data on other partitions on the disk you are restoring to will be lost.
2) Grayed out and unselected
You are not given the option to format and repartition the disk. This will occur if you are restoring Windows from a partition on the same disk.
3) Not grayed out and unselected
Here you have the option to select format the whole disk and repartition or not. In this case the disk the image was taken from has a matching partition structure to the disk you are restoring the image to. By not selecting the format and repartition option your image will be restored and other partitions untouched such as valuable data partitions.
in short, you (and me) are screwed =/

A: I just did a downgrade from Lion to Snow Leopard with a Bootcamp installation, and restored the bootcamp partition with the default Windows 8 system image backup tool (It's the same as Windows 7)
When restoring from the VHD image, yes it will say that the entire disk will be formatted but in reality it will only write to the bootcamp partition and leave the mac osx partition untouched (and for me the partition still stayed as Mac OSX Extended)
Just make sure to setup a Bootcamp partition within Mac OSX before restoring


text:
Q: User login error message is not displaying django Hi I would like to display userlogin error message when a user enters either wrong username or password on the login page.
What might i be missing or not doing?
Here is my views.py
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from django.template import RequestContext,loader,Context
from django.views.generic import ListView
from django.core.context_processors import csrf
from django.contrib.auth import authenticate,login as auth_login,logout
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse

from OMRS.models import JobStatus,Jobs,Authentication,Server,Shredder,Document
from OMRS.forms import UserProfileForm,UserForm,serverParams,DocumentForm
import OMRS.omrsfunctions as OF

#when using modelforms
from OMRS.forms import serverForm

# Create your views here.

def post_server_details(request):
    context = RequestContext(request)
    if request.method == 'GET':
        form = serverForm()
    else:
        # A POST request: Handle Form Upload
        # Bind data from request.POST into a PostForm
        form = serverForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/upload')
    c = {'serverDetails':form}
    return render_to_response('setup.html',c,context)

def index(request):
    context = RequestContext(request)
    context_dict = {'boldmessage':"I am bold"}
    return render_to_response('index.html',context_dict,context)

def restricted(request):
    context = RequestContext(request)
    context_dict = {'boldmessage':"I am bold"}
    return render_to_response('index.html',context_dict,context)

def server(request):
    latest_server_list = Server.objects.all()
    t = loader.get_template('server.html')
    c = Context({
        'latest_server_list' : latest_server_list
    })
    return HttpResponse(t.render(c))

def userProfile(request):
    context = RequestContext(request)
    return render_to_response('userprofile.html',{
        'jobStatus_list' :  JobStatus.objects.all(),
    },context)

class jobs(ListView):
    model = Jobs
    template_name = 'jobs.html'

def userJobSettings(request):
    context = RequestContext(request)
    return render_to_response('serverparams.html',{
        'userjobsettings_list': Server.objects.all(),
    },context)

def setup(request):
     context = RequestContext(request)

     if request.method == 'POST':
         setup_form = serverParams(data=request.POST)
         if setup_form.is_valid():
             new_obj = setup_form.save(commit=False)
             new_obj.save()
             #setup_form.save()
             return HttpResponseRedirect('/jobserversettings')
         else:
             print setup_form.errors

     return render_to_response('/setup', {}, context_instance=RequestContext(request))

def serverDetails(request):
    context = RequestContext(request)

    if request.method == 'POST':
        server_form = serverParams(data = request.POST)  #whats is declared int he forms data
        if server_form.is_valid():
            location_list = OF.searchLocations(server_form.serverAddress,server_form.serverUsername,server_form.serverPassword)
            print location_list
    return render_to_response('serverdetails.html',{
        'userjobsettings_list': Server.objects.all(),
    })

def register(request):
    context = RequestContext(request)
    registered = False
    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            #if 'picture' in request.FILES:
                #profile.picture = request.FILES['picture']

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful.
            registered = True

            #on successful registration move to the login page
            return HttpResponseRedirect('/login')

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            print user_form.errors, profile_form.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    # Render the template depending on the context.
    return render_to_response(
            'register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
            context)

def user_login(request):
    # Like before, obtain the context for the user's request.
    context = RequestContext(request)
    c = {}
    c.update(csrf(request))

    # If the request is a HTTP POST, try to pull out the relevant information.
    if request.method == 'POST':
        # Gather the username and password provided by the user.
        # This information is obtained from the login form.
        username = request.POST['username']
        password = request.POST['password']

        # Use Django's machinery to attempt to see if the username/password
        # combination is valid - a User object is returned if it is.
        user = authenticate(username=username, password=password)

        # If we have a User object, the details are correct.
        # If None (Python's way of representing the absence of a value), no user
        # with matching credentials was found.
        if user is not None:
            # Is the account active? It could have been disabled.
            if user.is_active:
                # If the account is valid and active, we can log the user in.
                # We'll send the user back to the homepage.
                auth_login(request, user)
                return HttpResponseRedirect('/userprofile')
            else:
                # An inactive account was used - no logging in!
                return HttpResponse("Your Kenya Data Works account is disabled.")
        else:
            # Bad login details were provided. So we can't log the user in.
            print "Invalid login details: {0}, {1}".format(username, password)
            return HttpResponseRedirect('/')
            #return HttpResponse("Invalid login details supplied.")

    # The request is not a HTTP POST, so display the login form.
    # This scenario would most likely be a HTTP GET.
    else:
        # No context variables to pass to the template system, hence the
        # blank dictionary object...
        return render_to_response('login.html', {}, context)

# Use the login_required() decorator to ensure only those logged in can access the view.
@login_required
def user_logout(request):
    # Since we know the user is logged in, we can now just log them out.
    logout(request)
    # Take the user back to the homepage.
    return HttpResponseRedirect('/OMRS')

#view to support file upload

def upload(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            #return HttpResponseRedirect(reverse(''))  userprofile
            return HttpResponseRedirect('/userprofile')
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'upload.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

'''
class servers(ListView):
    model = Server
    template_name = 'server.html'

def requires_login(view):
    def new_view(request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseRedirect('/accounts/login/')
        return view(request, *args, **kwargs)
    return new_view

 OMRS Server: {{ serverAddress }}

 OMRS Username: {{ serverUsername }}

 Date Added: {{ dateAdded }}

'''

'''

from django.conf.urls.defaults import *
from mysite.views import requires_login, my_view1, my_view2, my_view3

urlpatterns = patterns('',
    (r'^view1/$', requires_login(my_view1)),
    (r'^view2/$', requires_login(my_view2)),
    (r'^view3/$', requires_login(my_view3)),
)
'''

Here is my login.html
{% extends "index.html" %}

{% block title %} User Login {% endblock %}

{% block body_block %}
   {% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

        <form id="login_form" method="post" action="/login/">
            {% csrf_token %}

            Username: <input type="text" name="username" value="" size="50" />

            Password: <input type="password" name="password" value="" size="50" />

            <input type="submit" value="Submit" />
            <input type="submit" value="Cancel" />
        </form>

        {% if errors %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

        {% endif %}

{% endblock %}

Any help to fix this?

A: You pass the form object into the context with name serverDetails
c = {'serverDetails':form}
return render_to_response('setup.html',c,context)

so the your form object will be accessible by name serverDetails
{% if serverDetails.errors %}

Your username and password didn't match. Please try again.

{% endif %}


text:
Q: Unable to set array index at 0th position in JavaScript Here is a simple js code :

let day = 10;

let arrayMinutes = Array(day);
const d = new Date();
d.setHours(0);
d.setMinutes(1);
d.setSeconds(0);
arrayMinutes[0] = d;
console.log("arrayMinutes[0]", d, arrayMinutes[0], arrayMinutes);

const d2 = new Date();
d2.setHours(0);
d2.setMinutes(day);
d2.setSeconds(0);
arrayMinutes[day - 1] = d2;
console.log("arrayMinutes[day]", arrayMinutes[0], arrayMinutes[day - 1], arrayMinutes);

And the console logs :

Why arrayMinutes[0] evaluates to 0?
According to me it should be equal to d.

A: Beware using the Array constructor. My guess is that your day variable at the beginning of the code is a number. When you do Array(number), it creates an array with no entries in it and a length matching that number:

const a = Array(10);
console.log(a.length); // 10
console.log(a[0]);     // undefined
console.log(0 in a);   // false

In fact, doing that is almost the only time the Array constructor is useful. Any other time, use an array literal:

const a = [10];
console.log(a.length); // 1
console.log(a[0]);     // 10
console.log(0 in a);   // true

The reason I say "beware" is that Array behaves differently based on what you give it:

*

*If you give it a single number argument, as above, it creates an empty array with length set to that number.

*If you give it a single non-number argument, it creates an array containing that value (with length = 1).

*If you give it more than one argument, it creates an array containing those values (even if the first one is a number).
This...changing...behavior is why you should avoid the Array constructor entirely unless you're intentionally creating an empty array of a specified length (usually just prior to filling it).

A: The Array() constructor can be used in two ways:

*

*Array(el0, el1, el2, ...)
Creates an array containing el0, el1, el2, .... This is equivalent to [el0, el1, el2, ...]

*

*Array(count)
Creates an array with count elements, but the elements are uninitialized
If there's a single argument and it's an integer, it's taken to be the second form. So if day is an integer, you're creating an uninitialized array containing day elements.
Don't use Array(day), use [day] to create an array just containing the value day.

A: Maybe try with push
arrayMinutes.push(d);


text:
Q: mysql Insert query datatype I have table product_type with columns: ID_TYPE, PRODUCT_NAME, DESCRIPTION, QUANTITY.
INSERT QUERY should be:
Insert into product_type(PRODUCT_NAME, DESCRIPTION, QUANTITY)
values
('Muffin','blahblahblah','1 piece'),
('Cookies','blahblahblah','1 kg');

QUANTITY column has datatype DECIMAL. And I have problem with inserting product quantity. I'we got error:

3 row(s) affected, 3 warning(s): 1265 Data truncated for column
  'QUANTITY' at row 1 1265 Data truncated for column 'QUANTITY' at row
  2: 2 Duplicates: 0 Warnings: 2

Do you have any solution? Maybe I should write just 1 instead of '1 piece' or '1 kg'.

A: as you said if the data type of quantity is decimal then you cant store srting in it. for storing the units i would suggest you to make another column Unit of char type to store the units like Kg or Ltr or g etc.
ID_TYPE, PRODUCT_NAME, DESCRIPTION, QUANTITY.
INSERT QUERY should be:
Insert into product_type(PRODUCT_NAME, DESCRIPTION, QUANTITY, UNIT)
values
('Muffin','blahblahblah',1, 'piece'),
('Cookies','blahblahblah',1 ,'kg');

A: Check the datatype of QUANTITY column, I think it is INT or DECIMAL and you are trying to insert a string value 1 piece in it. In that case the integer past i.e. 1 is inserted with the message

Data truncated for column 'QUANTITY' at row 1

So insert the appropriate value as per the datatype


text:
Q: RegExp to validate the string "900 - 09 999" What would be the correct Javascript RegExp to validate the following string "900 - 09 999"
The string should only allow digits from 0 to 9, an hyphen and a space.
Thanks in advance

A: Always be precise when you explain what you want your regex to validate. Are the spaces and hyphens optional or not? This stuff matters. Anyway, this validates the strict format:
"\d{3} \- \d{2} \d{3}"

And this a less strict one:
"\d{3} ?\-? ?\d{2} ?\d{3}"

A: If you use this:
inputField.value = inputField.value.replace(/\s*(\d\d\d)\s*-?\s*(\d\d)\s*(\d\d\d)\s*/, "$1 - $2 $3")

...it should both loosely validate AND reformat the value if it does not match perfectly.
broken down, the expression does the following:
\s*          # match any amount of whitespace
(\d\d\d)     # capture three digits
\s*          # match any amount of whitespace
-?           # match an optional hyphen
\s*          # match any amount of whitespace
(\d\d)       # capture two digits
\s*          # match any amount of whitespace
(\d\d\d)     # capture three digits
\s*          # match any amount of whitespace

*

*match means to find a set of characters that matches the expression

*capture means to find a match, but store the match for later use

*whitespace can be spaces, tabs or carriage return characters

*any amount can mean zero or more


text:
Q: Cannot get line to draw on log scale y-axis, but can on linear I am trying to draw a simple line chart in D3.  I am able to draw the data line with a linear scale on the Y-axis (ignore the fact that there are no ticks):

Here is the code and a relevant JSFiddle for this:
var margin = { top: 10, right: 245, bottom: 30, left: 100 },
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// Set the X and Y scale (e.g., linear vs. log) and the domains
var x = d3.scale.linear().domain([-95,-74]).range([0, width]);

// ******* CHANGE linear() to log() *************************** //
var y = d3.scale.linear().domain([0.000010,1]).range([height, 0]);

// Set the locations of the axis (e.g., bottom and left)
var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left").ticks(0, ".1");;

// Set up some lines and related colors
var color = d3.scale.category10();
var line = d3.svg.line().x(function (d) { return x(d.power); }).y(function (d) { return y(d.ber); });

// Set the graph to be drawn in the respective div (grapharea), and set dimensions
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// Append the X and Y axis to the actual SVG graph
svg.append("g").attr("class", "y axis").call(yAxis);
svg.append("g").attr("class", "x axis").attr("transform", "translate(0," + height + ")").call(xAxis);

// Parse the JSON data response
var jsonString = '[{"power":-91.0,"ber":0.0},{"power":-92.0,"ber":0.0},{"power":-93.0,"ber":1E-07},{"power":-94.0,"ber":6.5E-06},{"power":-95.0,"ber":0.000147}]';
var jsonData = JSON.parse(jsonString);

jsonData.forEach(function (d) {
    d.ber = d.ber;
    d.power = d.power;
});

// Set the data properly
x.domain(d3.extent(jsonData, function(d) { return d.power; }));
y.domain(d3.extent(jsonData, function(d) { return d.ber; }));

svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("BER");

svg.append("path")
.datum(jsonData)
.attr("class", "line")
.attr("d", line);

If all I change is linear() to log() on the variable y, then I get a resulting log scale graph but my data line no longer shows up (relevant JSFiddle):

Does anyone know what I am doing wrong for the data line to not show up on the log scale graph?

A: You have zeros in your data. The log of zero is not defined. You'll need to use a different type of scale.


text:
Q: H.264 in Firefox As I understand it Firefox does not support H.264 encoded video using the  tag. I've been told that Flash will quite happily handle such content however I have no experience with Flash nor do I have access to Adobe Creative Suite. I'm developing primarily for Firefox users and recoding our video content to OGG would not be practical. What are my options?

A: You can develop a very simple app with Adobe Flex using their free SDK.  Flex is much easier for programmers than Flash IDE anyways.  No need for CS.
http://www.adobe.com/products/flex/
There are free IDE's too, for example FlashDevelop:
http://www.flashdevelop.org

A: You're probably best off using a component made for the purpose. JWPlayer is very popular, though I don't personally have experience with it. You just embed the player in your page and pass in the videos you want played with JavaScript, so no Flash development tools or skills are needed.

A: i would recommend http://flowplayer.org

A: flash really plays h.264 vids in FF
so you can develop your own player (it will take about one page of code if you need just a player) or use OSMF (opensource media framework), the compiler is free at opensource.adobe.com and above-mentioned FlashDevelop is a really cool actionscript editor imho.
flowplayer.org/ is google top result for 'free web video player' btw
'


text:
Q: Spacing of awesome-cv subsection I'm using the awesome-cv document class and noticed a problem with the \cvsubsection command:
\documentclass[11pt, a4paper]{awesome-cv}
\geometry{left=1.4cm, top=.8cm, right=1.4cm, bottom=1.8cm, footskip=.5cm}
\begin{document}

\cvsubsection{Sub A}
\begin{cventries}
    \cventry
    {Degree} % Degree
    {Institution} % Institution
    {Location} % Location
    {99/9999} % Date(s)
    {
        \begin{cvitems} % Description(s) bullet points
            \item{foobar}
            \item{barfoo}
        \end{cvitems}
    }
    \cventry
    {Degree} % Degree
    {Institution} % Institution
    {Location} % Location
    {99/9999} % Date(s)
    {
        \begin{cvitems} % Description(s) bullet points
            \item{foobar}
            \item{barfoo}
        \end{cvitems}
    }

\end{cventries}

\cvsubsection{SubB}
\begin{cventries}
    \cventry
    {Degree} % Degree
    {Institution} % Institution
    {Location} % Location
    {99/9999} % Date(s)
    {
        \begin{cvitems} % Description(s) bullet points
            \item{foobar}
            \item{barfoo}
        \end{cvitems}
    }
\end{cventries}
\cvsubsection{SubC}
\begin{cventries}
    \cventry
    {Degree} % Degree
    {Institution} % Institution
    {Location} % Location
    {99/9999} % Date(s)
    {
        \begin{cvitems} % Description(s) bullet points
            \item{foobar}
            \item{barfoo}
        \end{cvitems}
    }
    \cventry
    {Degree} % Degree
    {Institution} % Institution
    {Location} % Location
    {99/9999} % Date(s)
    {
        \begin{cvitems} % Description(s) bullet points
            \item{foobar}
            \item{barfoo}
        \end{cvitems}
    }
\end{cventries}
\cvsubsection{SubD}
\begin{cventries}
    \cventry
    {Degree} % Degree
    {Institution} % Institution
    {Location} % Location
    {99/9999} % Date(s)
    {
        \begin{cvitems} % Description(s) bullet points
            \item{foobar}
            \item{barfoo}
        \end{cvitems}
    }
\end{cventries}
\end{document}

As you can see, when there are two or more \cventrys, the spacing before the \cvsubsection becomes too small.
The document clas can be downloaded here, but here is a shortened version, just enough for my example above.
I found out that omitting the package fontawesome in the document class leads to equal vertical spacing before all subsections. How could I fix the problem when using fontawesome?
%% Start of file `awesome-cv.cls'.
% Awesome CV Class File
%
% This class has been downloaded from:
% https://github.com/posquit0/Awesome-CV
%
% Author:
% Claud D. Park <posquit0.bj@gmail.com>
% http://www.posquit0.com
%
% Notes:
% 1) This class file defines the structure and layout of the template file (cv.tex, resume.tex).
% 2) It has been written in such a way that under most circumstances you
% should not need to edit it.
%
% Class license:
% LPPL v1.3c (http://www.latex-project.org/lppl)
%

%-------------------------------------------------------------------------------
%                Identification
%-------------------------------------------------------------------------------
\ProvidesClass{awesome-cv}[2016/01/30 v1.5 Awesome Curriculum Vitae Class]
\NeedsTeXFormat{LaTeX2e}

%-------------------------------------------------------------------------------
%                Class options
%
% (need to be done before the external package loading, for example because
% we need \paperwidth, \paperheight and \@ptsize to be defined before loading
% geometry and fancyhdr)
%-------------------------------------------------------------------------------
% Inherit options of article
\DeclareOption*{%
  \PassOptionsToClass{\CurrentOption}{article}
}
\ProcessOptions\relax
\LoadClass{article}

%-------------------------------------------------------------------------------
%                3rd party packages
%-------------------------------------------------------------------------------
% Needed to make fixed length table
\RequirePackage{array}
% Needed to handle list environment
\RequirePackage{enumitem}
% Needed to handle text alignment
\RequirePackage{ragged2e}
% Needed to configure page layout
\RequirePackage{geometry}
% Needed to make header & footer effeciently
\RequirePackage{fancyhdr}
% Needed to manage colors
\RequirePackage{xcolor}
% Needed to use \ifxetex-\else-\fi statement
\RequirePackage{ifxetex}
% Needed to use \if-\then-\else statement
\RequirePackage{xifthen}
% Needed to use a toolbox of programming tools
\RequirePackage{etoolbox}
% Needed to change line spacing in specific environment
\RequirePackage{setspace}
% Needed to use icons from font-awesome
% (https://github.com/posquit0/latex-fontawesome)
\RequirePackage{fontawesome}
% Needed to deal a paragraphs
\RequirePackage{parskip}
% Needed to deal hyperlink
\RequirePackage[hidelinks,unicode]{hyperref}

%-------------------------------------------------------------------------------
%                Configuration for layout
%-------------------------------------------------------------------------------
%% Page Layout
% Configure page margins with geometry
\geometry{left=2.0cm, top=1.5cm, right=2.0cm, bottom=2.0cm, footskip=.5cm}

%-------------------------------------------------------------------------------
%                Configuration for colors
%-------------------------------------------------------------------------------
% Gray-scale colors
\definecolor{darkgray}{HTML}{333333}
\definecolor{gray}{HTML}{5D5D5D}
\definecolor{lightgray}{HTML}{999999}
% Text colors
\definecolor{darktext}{HTML}{414141}
\colorlet{text}{darkgray}
\colorlet{graytext}{gray}
\colorlet{lighttext}{lightgray}
% Awesome colors
\definecolor{awesome-red}{HTML}{DC3522}
\colorlet{awesome}{awesome-red}

%-------------------------------------------------------------------------------
%                Configuration for styles
%-------------------------------------------------------------------------------
% Configure styles for each CV elements
% For fundamental structures
\newcommand*{\subsectionstyle}[1]{{\fontsize{12pt}{1em}\scshape\textcolor{text}{#1}}}

% For elements of entry
\newcommand*{\entrytitlestyle}[1]{{\fontsize{10pt}{1em}\bfseries\color{darktext} #1}}
\newcommand*{\entrypositionstyle}[1]{{\fontsize{8pt}{1em}\scshape\color{graytext} #1}}
\newcommand*{\entrydatestyle}[1]{{\fontsize{8pt}{1em}\slshape\color{graytext} #1}}
\newcommand*{\entrylocationstyle}[1]{{\fontsize{9pt}{1em}\slshape\color{awesome} #1}}
\newcommand*{\descriptionstyle}[1]{{\fontsize{9pt}{1em}\upshape\color{text} #1}}

%-------------------------------------------------------------------------------
%                Commands for extra
%-------------------------------------------------------------------------------
%% Define helper macros a user can change easily

% Others
\newcommand{\acvSectionTopSkip}{3mm}
\newcommand{\acvSectionContentTopSkip}{2.5mm}

%-------------------------------------------------------------------------------
%                Commands for utilities
%-------------------------------------------------------------------------------
% Use to align an element of tabular table
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}

% Use to execute conditional statements by checking empty string
\newcommand*{\ifempty}[3]{\ifthenelse{\isempty{#1}}{#2}{#3}}

%-------------------------------------------------------------------------------
%                Commands for elements of CV structure
%-------------------------------------------------------------------------------

% Define a subsection for CV
% Usage: \cvsubsection{<subsection-title>}
\newcommand{\cvsubsection}[1]{%
  \vspace{\acvSectionContentTopSkip}
  \vspace{-3mm}
  \subsectionstyle{#1}
  \phantomsection
}
% Define an environment for cventry
\newenvironment{cventries}{%
  \vspace{\acvSectionContentTopSkip}
  \begin{center}
}{%
  \end{center}
}
% Define an entry of cv information
% Usage: \cventry{<position>}{<title>}{<location>}{<date>}{<description>}
\newcommand*{\cventry}[5]{%
  \vspace{-2.0mm}
  \setlength\tabcolsep{0pt}
  \setlength{\extrarowheight}{0pt}
  \begin{tabular*}{\textwidth}{@{\extracolsep{\fill}} L{\textwidth - 4.5cm} R{4.5cm}}
    \ifempty{#2#3}
      {\entrypositionstyle{#1} & \entrydatestyle{#4} \\}
      {\entrytitlestyle{#2} & \entrylocationstyle{#3} \\
      \entrypositionstyle{#1} & \entrydatestyle{#4} \\}
    \multicolumn{2}{L{\textwidth}}{\descriptionstyle{#5}}
  \end{tabular*}%
}
% Define an environment for cvitems(for cventry)
\newenvironment{cvitems}{%
  \vspace{-4.0mm}
  \begin{justify}
  \begin{itemize}[leftmargin=2ex, nosep, noitemsep]
    \setlength{\parskip}{0pt}
    \renewcommand{\labelitemi}{\bullet}
}{%
  \end{itemize}
  \end{justify}
  \vspace{-4.0mm}
}


text:
Q: ASP.NET MVC Validation add class to containing div I'm using bootstrap CSS form styles, When a textbox gets a validation error message, I need to put the class "error" on the containg . How can I do this?
Problem is, all the validations fire on ajax before submitting the form, except for my custom validators which only fire on post. So need to make sure it happens 4 both scenarios.
http://twitter.github.com/bootstrap/base-css.html#forms

A: Inside the onError function in jquery.validate.unobtrusive, just add the .addClass("error") line like this:
function onError(error, inputElement) {  // 'this' is the form element
  var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
      replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;

  container.removeClass("field-validation-valid").addClass("field-validation-error");
  error.data("unobtrusiveContainer", container);
  container.parents(".field-encapsulator:first").addClass("error");

  if (replace) {
    container.empty();
    error.removeClass("input-validation-error").appendTo(container);
  }
  else {
    error.hide();
  }
}

A: ASP.NET MVC adds the field-validation-error class to the error message element, and input-validation-error to form controls, both on the server-side and client-side via javascript. There's no containing element, depending on your code the form control and its label may or may not be under the same containing element. And, even if they do, MVC will set the mentioned classes to the form control and error message element and not the containing element.
Also, when you autogenerate a form using Html.EditorForModel() the generated markup is like this:

Foo

<input name="foo"/>

There's no containing element that could map to the control-group class on Twitter Bootstrap. You could change this template by adding an EditorTemplates/Object.cshtml template.
I'd suggest you adapt Twitter Bootstrap to ASP.NET MVC and not the other way around.

A: As described in some of the answers at How to add a 'submitHandler' function when using jQuery Unobtrusive Validation?, the settings can be accessed by $("form").data("validator").settings.
And you can then set any valid/invalid class you like:
var settings = $("form").data("validator").settings;
settings.errorClass += " is-invalid";
settings.validClass += " is-valid";


text:
Q: IMAP authenticate vs login IMAP servers may, according to RFC 3501, supports these (and other) commands:

*

*LOGIN

*AUTHENTICATE "PLAIN"
Questions

*

*Is there a reason to use one above the other?

*Is there a reason to support other AUTHENTICATION mechanisms when TLS is used?

A: Almost all servers support LOGIN, which is the basic baseline version to authenticate.
AUTHENTICATE is an extensible generic command, which could support any SASL* authentication mechanism, or custom methods.
I would use login where available because it's a simpler command (no base64 or continuation responses).
Reasons to use AUTHENTICATE: supporting SSO or OAUTH scenarios, which have different requirements then just a username or password.
For example, to integrate well with GMail, OAUTH2 is the preferred mechanism, which has a custom AUTHENTICATE method.
*SASL is the Simple Authentication and Security Layer, which is a metaprotocol for authentication, described currently in RFC 4422.


text:
Q: Outlook 2007 Multiple Meeting Request with multiple times I know this can't be a unique issue.  In my company, we have 75+ employees that all need to attend a meeting.  It is impossible to get all 75+ employees together at one time so I would like to create a meeting request with the multiple times the meeting is going to be held.  Ideally, the employee would click a link to accept the meeting request at that time.
The 2nd Quarter meeting is next Friday.
Select a time to attend and it will automatically be added to your calendar

         *10am
         *12pm
         *2pm

Is there anything out there that can do this?

A: You can do this by scheduling the multiple meetings as meetings (not appointments) with yourself. Then, save each as a file (use a descriptive name) and attach them to an email that you send to people. The accept/reject options will be available for people to use, and people can just accept (and thus add to their calendar) the one they'll be attending.
We do this all the time at my company for social events, so as to not automatically put it on people's calendars but still get RSVPs :-).

A: Does the describe what you are trying to do?
http://www.techtalkz.com/microsoft-outlook/434618-outlook-2007-meeting-request-multiple-time-options.html

A: Had the same problem - - but figured out a work around.
(1) set up your mtgs (as others have said, in the title, use the date and time)
(2) Then, while in calendar view, right click on the mtg and select "forward" (but don't forward it - just leave that email message open)
(3) do that for EACH mtg - - leaving each "forward" email open.
(4) Create your main email.
(5) Now, for EACH "forward" email, the mtg should show as an ATTACHMENT.  Click and HOLD on the attachment and DRAG it into the BODY (not attachment line) of your NEW email message.
...you should be able to drag all of the attachments into the new email.
(6) tell the attendees to open the attachment that is the date/time that works for them, then they need to select "add to calendar" - - this will then provide them with the option to: (a) accept the mtg, (b) tentatively accept, or (c) just copy the mtg.
It is allowing me to track those who accepted or tentatively accepted.  I'm also receiving the email responses.


text:
Q: Serialized connection using Socket Programming I am trying to make a loop of communicating nodes passing very low level messages and I was wondering whether socket programming would be a good fit for my purpose. I will explain what I intend to do below:
Consider three nodes A, B, C.

*

*Node A generates some data and sends it to B.

*Node B receives this data, does some computation and sends it to C.

*Node C receives this data, does some computation and sends it back to A.

To make it work, I was thinking of having all nodes as both client and servers.
Client A ----> Server B [After Computation] Client B ---> Server C [After Computation] Client C---> Server A
My question is that would this work? Or is there a major flaw in my thought process?
Thank you all :)

A: I'm affraid stackoverflow is not a good place for such question, this is "direct question -> direct answer" site. But here are some my thoughts:
It is weird architecture i must say. It could work this way, but how do you want to run client and server at the same node? No matter if they are 2 threads or 2 processes or even 2 applications, you will have to deal with communication between them.
You can also try to do peer-to-peer communication through UDP, but that's not going to be easier.
Consider alternative having server at node B offering service "some computation 1",
server at node C offering "some computation 2" and then client at node A, which will first query server B with the initial data, and after receiving response query server C with the returned data.


text:
Q: How to use filter in "*ngFor" loop based on list of data It was done in angular 1.5 as follows with the following data

getdetailAttrList= [
    { getName: "Id", getNumber: "1335626187264778", getString: '10000450439458'},
    { getName: "Pat_Id", getNumber: "1335626196206806", getString: '00350242060011'},
    { getName: "Prov_Id", getNumber: "1335626218309875", getString: '3228610'},
    { getName: "Pat_Name", getNumber: "1335626212804143", getString: '200131'},

];

= 0"
ng-repeat="info in getdetailAttrList
| unique:'getName' | filter: { getName: '!UID' }
| filter: { getName: '!PROVIDERID' }">
   {{info.getName}}
   {{info.getString}}

How to achieve the same functionality in angular 6?

A: In angular 6 you can loop your data by this way

= 0" *ngFor="let info of getdetailAttrList">
 {{info.getName}}
 {{info.getString}}


text:
Q: How to upload phonegap build app in google playstore? Whenever I am trying to upload app which has formed by phonegap build method (Which have only config.xml and index.html file) getting an error

You uploaded a debuggable APK. For security reasons you need to disable debugging before it can be published in Google Play. Learn more about debuggable APKs.
You uploaded an APK that was signed in debug mode. You need to sign your APK in release mode. Learn more about signing.

My search found the solution that to make debuggable="false" in androidmanifest.xml. But the thing is that there is no such file in the case of phonegap build method. How can I fix this?

A: No. The solution you found is wrong. This is how you do it.
In the future, read the official documentation.
If you are confused, ask question at the official Phonegap Build forum or the Nitobi forum.
The instructions you need for signing are at this link: Android Signing for Google Play
The final step is, which is not documented very well, is here:
Builing a release version for build.phonegap.com


text:
Q: joining two tables with differnt join column names I have two tables A -> B with many-to-one mapping/associations.
Table B's primary key is foreign key in table A.
The problem is column names in both tables are different. let's say B has primary  key column "typeNumId" which is foreign key in table A as "type". How can I join both tables on this column? how can I specify mapping to indicate that tables have to join on "typeNumId" and "type" which is essentially same.
especially is this possible through hibernate config ( hbm files) ?
something like
<many-to-one name="Type" class="com.domain.ProcedureType" update="false" insert="false" fetch="join" lazy="false">
    <column name="? <this is in questions? >" not-null="true" />
</many-to-one>

A: The ON clause:
select * from A join B on A.type = B.typeNumId

A: You declare the name of the foreign key using the column attribute of the many-to-one element or the equivalnent nested column element. From the documentation:

5.1.12. Many-to-one
An ordinary association to another
  persistent class is declared using a
  many-to-one element. The relational
  model is a many-to-one association; a
  foreign key in one table is
  referencing the primary key column(s)
  of the target table.
<many-to-one
        name="propertyName"                                          (1)
        column="column_name"                                         (2)
        class="ClassName"                                            (3)
        cascade="cascade_style"                                      (4)
        fetch="join|select"                                          (5)
        update="true|false"                                          (6)
        insert="true|false"                                          (6)
        property-ref="propertyNameFromAssociatedClass"               (7)
        access="field|property|ClassName"                            (8)
        unique="true|false"                                          (9)
        not-null="true|false"                                        (10)
        optimistic-lock="true|false"                                 (11)
        lazy="proxy|no-proxy|false"                                  (12)
        not-found="ignore|exception"                                 (13)
        entity-name="EntityName"                                     (14)
        formula="arbitrary SQL expression"                           (15)
        node="element-name|@attribute-name|element/@attribute|."
        embed-xml="true|false"
        index="index_name"
        unique_key="unique_key_id"
        foreign-key="foreign_key_name"
/>

*

*name: the name of the property.

*column (optional): the name of the foreign key column. This can also be
  specified by nested
  element(s).

*class (optional - defaults to the property type determined by
  reflection): the name of the
  associated class.

*cascade (optional): specifies which operations should be cascaded from the
  parent object to the associated
  object.

*fetch (optional - defaults to select): chooses between outer-join
  fetching or sequential select
  fetching.

*update, insert (optional - defaults to true): specifies that the mapped
  columns should be included in SQL
  UPDATE and/or INSERT statements.
  Setting both to false allows a pure
  "derived" association whose value is
  initialized from another property that
  maps to the same column(s), or by a
  trigger or other application.

*property-ref (optional): the name of a property of the associated class
  that is joined to this foreign key. If
  not specified, the primary key of the
  associated class is used.

*access (optional - defaults to property): the strategy Hibernate uses
  for accessing the property value.

*unique (optional): enables the DDL generation of a unique constraint for
  the foreign-key column. By allowing
  this to be the target of a
  property-ref, you can make the
  association multiplicity one-to-one.

*not-null (optional): enables the DDL generation of a nullability
  constraint for the foreign key
  columns.

*optimistic-lock (optional - defaults to true): specifies that
  updates to this property do or do not
  require acquisition of the optimistic
  lock. In other words, it determines if
  a version increment should occur when
  this property is dirty.

*lazy (optional - defaults to proxy): by default, single point
  associations are proxied.
  lazy="no-proxy" specifies that the
  property should be fetched lazily when
  the instance variable is first
  accessed. This requires build-time
  bytecode instrumentation. lazy="false"
  specifies that the association will
  always be eagerly fetched.

*not-found (optional - defaults to exception): specifies how foreign keys
  that reference missing rows will be
  handled. ignore will treat a missing
  row as a null association.

*entity-name (optional): the entity name of the associated class.

*formula (optional): an SQL expression that defines the value for
  a computed foreign key.

So something like this should do it:
<many-to-one name="Type" class="com.domain.ProcedureType" update="false" insert="false" fetch="join" lazy="false">
    <column name="type" not-null="true" />
</many-to-one>

Reference

*

*Hibernate Core documenation

*

*5.1.12. Many-to-one

A: Something like this?
LEFT JOIN B on A.field1 = B.field2

Choose type of JOIN on your taste


text:
Q: What's the difference between ng-model and ng-bind I'm currently learning AngularJS and am having difficulty understanding the difference between ng-bind and ng-model.
Can anyone tell me how they differ and when one should be used over the other?

A: ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }}
which displays the scope value $scope.val inserted into html where val is a variable name.
ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <input ng-model="val"/>.

A: ng-model
ng-model  directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.
ng-bind
ng-bind works much different than ng-model. ng-bind is one way data binding used for displaying the value inside html component as inner HTML. This directive can not be used for binding with the variable but only with the HTML elements content. Infact this can be used along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.
This example would help you to understand.

A:

angular.module('testApp',[]).controller('testCTRL',function($scope)

{

$scope.testingModel = "This is ModelData.If you change textbox data it will reflected here..because model is two way binding reflected in both.";
$scope.testingBind = "This is BindData.You can't change this beacause it is binded with html..In above textBox i tried to use bind, but it is not working because it is one way binding.";
});
div input{
width:600px;
}

Diff b/w model and bind

        Model-Data : <input type="text" data-ng-model="testingModel">

{{testingModel}}

          <input type="text" data-ng-bind="testingBind">

A: ngModel
The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.
This directive executes at priority level 1.
Example Plunker
JAVASCRIPT
angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.val = '1';
}]);

CSS
.my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
}
.my-input.ng-invalid {
    color:white;
    background: red;
}

HTML

   Update input to see transitions when valid/invalid.
   Integer is a valid value.

<form name="testForm" ng-controller="ExampleController">
    <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
</form>

ngModel is responsible for:

*

*Binding the view into the model, which other directives such as
input, textarea or select require.

*Providing validation behavior (i.e. required, number, email, url).

*Keeping the state of the control (valid/invalid, dirty/pristine,
touched/untouched, validation errors).

*Setting related css classes on the element (ng-valid, ng-invalid,
ng-dirty, ng-pristine, ng-touched, ng-untouched) including
animations.

*Registering the control with its parent form.

ngBind
The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
This directive executes at priority level 0.
Example Plunker
JAVASCRIPT
angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
    $scope.name = 'Whirled';
}]);

HTML

  Enter name: <input type="text" ng-model="name">

  Hello !

ngBind is responsible for:

*

*Replacing the text content of the specified HTML element with the
value of a given expression.

A: ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.

A: tosh's answer gets to the heart of the question nicely. Here's some additional information....
Filters & Formatters
ng-bind and ng-model both have the concept of transforming data before outputting it for the user. To that end, ng-bind uses filters, while ng-model uses formatters.
filter (ng-bind)
With ng-bind, you can use a filter to transform your data. For example,

,
or more simply:

{{mystring | uppercase}}

Note that uppercase is a built-in angular filter, although you can also build your own filter.
formatter (ng-model)
To create an ng-model formatter, you create a directive that does require: 'ngModel', which allows that directive to gain access to ngModel's controller. For example:
app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$formatters.push(function(value) {
        return value.toUpperCase();
      });
    }
  }
}

Then in your partial:
<input ngModel="mystring" my-model-formatter />

This is essentially the ng-model equivalent of what the uppercase filter is doing in the ng-bind example above.

Parsers
Now, what if you plan to allow the user to change the value of mystring? ng-bind only has one way binding, from model-->view. However, ng-model can bind from view-->model which means that you may allow the user to change the model's data, and using a parser you can format the user's data in a streamlined manner. Here's what that looks like:
app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
}

Play with a live plunker of the ng-model formatter/parser examples

What Else?
ng-model also has built-in validation. Simply modify your $parsers or $formatters function to call ngModel's controller.$setValidity(validationErrorKey, isValid) function.
Angular 1.3 has a new $validators array which you can use for validation instead of $parsers or $formatters.
Angular 1.3 also has getter/setter support for ngModel

A: If you are hesitating between using ng-bind or ng-model, try to answer these questions:

Do you only need to display data?

*

*Yes: ng-bind (one-way binding)

*No: ng-model (two-way binding)

Do you need to bind text content (and not value)?

*

*Yes: ng-bind

*No: ng-model (you should not use ng-bind where value is required)

Is your tag a HTML <input>?

*

*Yes: ng-model (you cannot use ng-bind with <input> tag)

*No: ng-bind

A: We can use ng-bind with
 to display, we can use shortcut for ng-bind {{model}}, we cannot use ng-bind with html input controls, but we can use shortcut for ng-bind {{model}} with html input controls.
<input type="text" ng-model="name" placeholder="Enter Something"/>
<input type="text" value="{{name}}" placeholder="Enter Something"/>
  Hello {{name}}
<p ng-bind="name"


text:
Q: The problem of the joint arrangement of two TextViews with a large volume of text There is a horizontal LinearLayout in which 2 TextViews are located. The problem is as follows: if there is a large amount of text in the first TextView, then it completely overlaps the second TextView, as if pushing it into an invisible area, despite the fact that the latter also has text. I need part of the text in the first TextView to be hidden (I used the maxLines and ellipsize attributes) when the text is too large, but at the same time I need the text of the second TextView to be visible too.
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:ellipsize="end"
        tools:text="@tools:sample/lorem/random"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        tools:text="random text"/>
</LinearLayout>

I tried the android:maxWidth attribute. But it seems to me that this is not quite right.

A: According to Tenfour04's comment.

Give both TextViews layout_weight=1 and layout_width=0. –

Solution is:
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:ellipsize="end"
        android:layout_weight="1"
        tools:text="@tools:sample/lorem/random"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:ellipsize="end"
        android:layout_weight="1"
        tools:text="random text"/>
</LinearLayout>

Hope this helps!

A: The solution looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:ellipsize="end"
        android:layout_weight="1"
        tools:text="@tools:sample/lorem/random"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:layout_weight="0"
        tools:text="random text"/>
</LinearLayout>


text:
Q: How to add JObjects to a JArray when serializing a DataTable to JSON using custom formatting rules? When attempting to serialize a DataTable to JSON using a custom format,  I have some trouble adding JObjects (representing a row) to my JArray (representing the table).
So what I hope to make the table look like is something like this:
[
    "Orderline" : {"Item": "Table", "Quantity": "5", "Amount": "50$"},
    "Orderline" : {"Item": "Chair", "Quantity": "20", "Amount": "30$"},
    "Orderline" : {"Item": "Couch", "Quantity": "2", "Amount": "500$"}
]

I have tried using the Add method to the JArray but I cannot seem to get it to work properly.
At the beginning I have set the JArray to new JArray, so that it is in memory and then I will go along and add the JObjects to it one at a time.
I can see that the add method takes two arguments (Item as JToken and content as object) which makes me a little confused because I do not see anyone else addressing both arguments in other code snippets I have seen online.
JArray is a instance of class Newtonsoft.Json.Linq.JArray.
Desired JObject output:
{
  "Orderlines": {
    "Item": "Table",
    "Quantity": "5",
    "Amount": "50"
  }
}

Draft code:
Dim JsonObejct as JObject
Dim MyArray as Jarray
Dim Table as datatable

Set MyArray = new JArray

for each row in table

JsonObject = Jobject.FromObject(
    New With {
    Key.Orderlines = New With{
        key.Item = row("Item").Tostring,
        key.Quantity = row("Quantity").tostring,
        key.Amount = row("Amount").tostring
    }
    }
    )
Myarray.add(JsonObject)
Next row

I work in UiPath Studio and do not have the code in the same place its separated in multiple activities, so please don't get caught in wrongly defined details in the code, everything works until the add to jarray part.
I use Vb .net in UiPath Studio so I would appreciate a solution on how to add the JObects to my JArray in vb .net.

A: If you simply need to fix your compilation, the following compiles successfully and generates the required JSON structure:
Public Module DataTableJsonExtensions
    Public Function ToSpecificOrderlines(ByVal table As DataTable) As JArray
        Dim MyArray as JArray = New JArray
        For Each row As DataRow In table.Rows
            ' Possibly you need to use CultureInfo.InvariantCulture in your ToString calls
            Dim JsonObject As JObject = JObject.FromObject(
                New With {
                    Key.Orderlines = New With{
                        key.Item = row("Item").ToString,
                        key.Quantity = row("Quantity").ToString,
                        key.Amount = row("Amount").ToString
                        }
                    }
                )
            MyArray.add(JsonObject)
        Next row
        Return MyArray
    End Function
End Module

And then do
Dim myArray as JArray = DataTableJsonExtensions.ToSpecificOrderlines(table)

Demo fiddle #1 here.
However, it seems preferable to generalize the code to serialize any set of DataTable columns by name, with an optional specified format:
Public Module DataTableJsonExtensions
    ' Serialize all the columns of the table to an Orderlines array
    Public Function ToOrderlines(ByVal table As DataTable) As JArray
        Return ToOrderlines(table, table.Columns.Cast(Of DataColumn).Select(Function(c) c.ColumnName).ToArray())
    End Function

    ' Serialize the selected columns of the table to an Orderlines array with the specified culture and formats (if any)
    Public Function ToOrderlines(ByVal table As DataTable, ByVal columns() As String, Optional ByVal culture As CultureInfo = Nothing, Optional ByVal formats As IDictionary(Of String, String) = Nothing) As JArray
        culture = If (IsNothing(culture), CultureInfo.InvariantCulture, culture)
        Dim array as JArray = New JArray
        For Each row As DataRow In table.Rows
            Dim obj As JObject = new JObject (
                new JProperty("Orderlines",
                    New JObject(columns.Select(Function(c) New JProperty(c, String.Format(culture, If(Not IsNothing(formats) AndAlso formats.ContainsKey(c), formats(c), "{0}"), row(c)))))
                )
            )
            array.add(obj)
        Next row
        Return array
    End Function
End Module

Then, to get the JSON shown at the top of your question, with the $ appended to the "Amount" property's value, do:
Dim formats = New Dictionary(Of String, String) From {{"Amount", "{0}$"}}
Dim myArray as JArray = DataTableJsonExtensions.ToOrderlines(table, {"Item", "Quantity", "Amount"}, Nothing, formats)

If you don't need the formatting after all, you call it as follows:
Dim myArray as JArray = DataTableJsonExtensions.ToOrderlines(table, {"Item", "Quantity", "Amount"})

Notes:

*

*You can use DataTableJsonExtensions.ToOrderlines(table) to serialize all columns of the table to an Orderlines array.

*In general serialization should always be performed using the invariant culture so that JSON serialized in one locale (say, the United States) can be deserialized in another locale (say, Europe) which uses a different decimal separator or DateTime format.  ToString(), however, formats its values using the current culture.  Thus I provided the option for you to specify a formatting culture in case you really want to serialize in CultureInfo.CurrentCulture.  Passing Nothing for the culture results in using the invariant culture.

*In the JSON shown in the top of your question you append a $ to the Amount column, so I provided an optional dictionary of formats in case you need to add that when serializing.
Demo fiddle #2 here.


text:
Q: Using DynamoDBMarshaller - how marshall can return int I am trying to get for dynamoDB table and i am getting error:
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException:
Expected S in value {N: 0,} when invoking public void
com.genieo.installer.data.MacClient.setGuardActivityCounter(int)"]}

I understood that I need to use DynamoDBMarshaller implementation.
I tried it like this:
public static class GuardActivityCounterDynamoDBMarshaller implements DynamoDBMarshaller<Integer>
{

    @Override
    public int marshall(Integer getterReturnResult) {
        return 0;
    }

    @Override
    public Integer unmarshall(Class<Integer> clazz, String obj) {
        return 0;
    }

}

but unfortunately the  marshall function can not return int.
I would love if someone could  help me please.
Thanks in advance
Gal

A: If I understood your question correctly, you have stored an attribute on DynamoDB with String data type. However, when you return the value from mapper, you would like to return it as integer (i.e. Java primitive int type).
Here is the example.
Please note that the attribute is defined as int on model.
private int postCounter;

@DynamoDBTyped(DynamoDBAttributeType.S)
@DynamoDBAttribute(attributeName = "postCounter")
public int getPostCounter() {
    return postCounter;
}

postCounter attribute is stored as String in DynamoDB table:-
See the screenshot below.
However, the mapper treats the attribute as Integer. The annotation @DynamoDBTyped is used to indicate the DynamoDB data type rather than interpreting automatically based on Java data type.