问:
$ produces unexpected identifier in JS
I'm using ${} to call an API from .env
issue is,

my code:

```<code>const url = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric&appid=${process.env.API_KEY}'
</code>```

now, ${process.env.API_KEY} works as apart of string and not as a function or identifier. How can I resolve this?

P.s: I'm new to JS

答:
If you are using embedded expressions with ${...}-notation, you need to put them between backticks like: `${...}`

var process = { env: { API_KEY: 'my_app_id' } };

const url = `http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric&appid=${process.env.API_KEY}`;

console.log(url);```

Title: $ produces unexpected identifier in JS

Body:
I'm using ${} to call an API from .env
issue is,

my code:

const url = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric&appid=${process.env.API_KEY}'

now, ${process.env.API_KEY} works as apart of string and not as a function or identifier. How can I resolve this?

P.s: I'm new to JS


来源: stackexchange

问:
How to install virtualenv with pipx?
Using Python 3.8.3, pipx 0.15.4.0

I tried to install virtualenv using:

```<code>python -m pipx install virtualenv
python -m pipx ensurepath
</code>```

Then I checked to see if it was installed properly:

```<code>python -m virtualenv --help
C:\Users\...\AppData\Local\Programs\Python\Python38\python.exe: No module named virtualenv.__main__; 'virtualenv' is a package and cannot be directly executed
</code>```

I'd like to use pipx rather than pip to do this, any ideas?

答:
You could use venv.

```<code>python -m venv new_env
</code>```

Creates a new virtual environment called new_env.

ContentLicense: CC BY-SA 4.0

Title: How to install virtualenv with pipx?

Body:
Using Python 3.8.3, pipx 0.15.4.0

I tried to install virtualenv using:

python -m pipx install virtualenv
python -m pipx ensurepath

Then I checked to see if it was installed properly:

python -m virtualenv --help
C:\Users\...\AppData\Local\Programs\Python\Python38\python.exe: No module named virtualenv.__main__; 'virtualenv' is a package and cannot be directly executed

I'd like to use pipx rather than pip to do this, any ideas?

Body:
You could use venv.

python -m venv new_env

Creates a new virtual environment called new_env.


问:
Why does 3cx c# api makecall method makes more than one call per method use?
When I use

```<code>pbx.MakeCall(prefix + abone.telefon, ivr);
</code>```

method of 3cx api, it makes three calls per method use. Why this happens? How can I fix it?

There are two makecall methods:

```<code>// TCX.PBXAPI.PBXConnection
public unsafe void MakeCall(string dnNumber, Dictionary<string, string> parameters)

// TCX.PBXAPI.PBXConnection
public unsafe void MakeCall(string dn_from, string number_to)
</code>```

Does anyone know how to use the first method?

答:
You must be running on an old version of 3cX to have this experience.
Do upgrade to version 16.x and you'll find out that this method fires just once.
You can find the 3cX Call Control APIs on GitHub.

For the first method,

```<code>                     Dictionary<String, String> dict = new Dictionary<String, String>
                                    {
                                        { "destnum", customer }
                                    };
                      PhoneSystem.Root.MakeCall(Ext.DN.Number, dict);
</code>```

The issue many people have with this method is knowing the right keys to place in the dictionary.
I have a library of them and you can actually use this method more efficient than others.

Lastly, MakeCall has 3 methods in version 16.x.

```<code>        public void MakeCall(string dnNumber, Dictionary<string, string> parameters);
        public void MakeCall(string from_number, string number_to);
        public void MakeCall(RegistrarRecord from_device, string destination);
</code>```

The third one works quite well with the Windows Client but doesn't work with Web Client.

ContentLicense: CC BY-SA 3.0

Body:
When I use

pbx.MakeCall(prefix + abone.telefon, ivr);

method of 3cx api, it makes three calls per method use. Why this happens? How can I fix it?

There are two makecall methods:

// TCX.PBXAPI.PBXConnection
public unsafe void MakeCall(string dnNumber, Dictionary<string, string> parameters)

// TCX.PBXAPI.PBXConnection
public unsafe void MakeCall(string dn_from, string number_to)

Does anyone know how to use the first method?

Body:
You must be running on an old version of 3cX to have this experience.
Do upgrade to version 16.x and you'll find out that this method fires just once.
You can find the 3cX Call Control APIs on GitHub.

For the first method,

                     Dictionary<String, String> dict = new Dictionary<String, String>
                                    {
                                        { "destnum", customer }
                                    };
                      PhoneSystem.Root.MakeCall(Ext.DN.Number, dict);

The issue many people have with this method is knowing the right keys to place in the dictionary.
I have a library of them and you can actually use this method more efficient than others.

Lastly, MakeCall has 3 methods in version 16.x.

        public void MakeCall(string dnNumber, Dictionary<string, string> parameters);
        public void MakeCall(string from_number, string number_to);
        public void MakeCall(RegistrarRecord from_device, string destination);

The third one works quite well with the Windows Client but doesn't work with Web Client.


问:
Plotting charts with google app inventor
I'm trying to create an app with Google app inventor which can plot a graph from a database - for example: x,y values that the app will get.

Does anyone know how to do it?

During my search for some info I saw below image from this webpage, and if you look closely you'll see on the top (right corner) the options: "plot chart" and "output chart", but I don't actually find these options in the app inventor menu.

答: Yes, you can do it indirectly by creating an Image component, then setting its Picture property to a URL for a Google Chart.


问:
Error while using body.json() for parsing response from http.get()
Tried using body.json() to assign data to an array of object but as it returns a promise tried this. But browser throws error telling me json() is not a function.

getRecipes() {
  this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
    (response: Response) => {
      response.json().then(
        (data) => {
          this.recServ.setRecipes(data)
        }
      );
    }
  )
}
```

答:
You can actually replace it like this, Also, can assign response to an interface to strict-type it. </p>

```<code>getRecipes() {
  this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
    (response) => this.recServ.setRecipes(response)
  );
}
</code>```

Body:
You can actually replace it like this, Also, can assign response to an interface to strict-type it.

getRecipes() {
  this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
    (response) => this.recServ.setRecipes(response)
  );
}


问:
Loop through QSpinbox when reaches the end
Is there any way to create a QSpinbox that sets itself to the first value, when it reaches the end, and the step up button is pressed again?

I tried doing it in a custom QSpinBox but what happens is that when it reaches to the last value, y gets instantly reset, which leads to never seeing the last value.

```<code>from PyQt5.QtWidgets import QSpinBox
from music import TonoFactory

_tf = TonoFactory()

class StringBox(QSpinBox):
    def __init__(self, parent=None):
        super(StringBox, self).__init__(parent)
        strings = []
        for key in _tf.notas.keys():
            strings.append(key)
        self.setStrings(strings)
        self.editingFinished.connect(self.reset_spin)

    def strings(self):
        return self._strings

    def setStrings(self, strings):
        strings = list(strings)
        self._strings = tuple(strings)
        self._values = dict(zip(strings, range(len(strings))))
        self.setRange(0, len(strings) - 1)

    def textFromValue(self, value):
        return self._strings[value]

    def valueFromText(self, text):
        return self._values[text]

    def reset_spin(self):
        if self.value() == len(self.strings()) -1:
            self.setValue(0)
</code>```

答:
Use spinbox.setWrapping(True) method

It is a builtin method to repeat the values of spin box

Body:
Is there any way to create a QSpinbox that sets itself to the first value, when it reaches the end, and the step up button is pressed again?

I tried doing it in a custom QSpinBox but what happens is that when it reaches to the last value, y gets instantly reset, which leads to never seeing the last value.

from PyQt5.QtWidgets import QSpinBox
from music import TonoFactory

_tf = TonoFactory()

class StringBox(QSpinBox):
    def __init__(self, parent=None):
        super(StringBox, self).__init__(parent)
        strings = []
        for key in _tf.notas.keys():
            strings.append(key)
        self.setStrings(strings)
        self.editingFinished.connect(self.reset_spin)

    def strings(self):
        return self._strings

    def setStrings(self, strings):
        strings = list(strings)
        self._strings = tuple(strings)
        self._values = dict(zip(strings, range(len(strings))))
        self.setRange(0, len(strings) - 1)

    def textFromValue(self, value):
        return self._strings[value]

    def valueFromText(self, text):
        return self._values[text]

    def reset_spin(self):
        if self.value() == len(self.strings()) -1:
            self.setValue(0)


问:
Has anyone figured out how to program the STWBC-MC module by STM?
The documents say that we can flash custom firmware on this module but it doesn't say how. I am unable to locate any build tool chain either. I tried raising a customer support ticket with STM and they don't seem to have any answers. Has anyone used this module in any of their products?</p>

答: The User Manual for the STMWB-CM evaluation kit explains the programming process (see section 3.6).  You use an ST-LINK/V2 in-circuit debugger/programmer with single wire interface module (SWIM) and STVP software.</p>


问:
How to populate bootstrap grid dynamically using Vue.js
So far I have fetched a list of objects from my database (each contain a name and description) and would like to display these objects in a bootstrap grid so that each object has its own section with its name and description shown. So if for example there are 5 items in the list and I'd like 3 items per row, then it would look like this:

And the grid would be responsive to the screen size.
I'm not very familiar with Vue and can't see how to do this without hardcoding the grid.

This is what my code currently looks like:

```<code><template>
  <div class="app">
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'app2',
  data() {
    return {
      items: []
    }
  },
// Fetch items from database...
}
</code>```

答:
Use v-for and bootstrap styles:</p>

```<code><template>
  <div class="app">

    <div class="row">
      <div class="col-sm" v-for="item in items">
        {{ item.prop1 }}
      </div>
    </div>

  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'app2',
  data() {
    return {
      items: []
    }
  },
// Fetch items from database...
}
</code>```

Body:
So far I have fetched a list of objects from my database (each contain a name and description) and would like to display these objects in a bootstrap grid so that each object has its own section with its name and description shown. So if for example there are 5 items in the list and I'd like 3 items per row, then it would look like this:

And the grid would be responsive to the screen size.
I'm not very familiar with Vue and can't see how to do this without hardcoding the grid.

This is what my code currently looks like:

<template>

</template>

Body:
Use v-for and bootstrap styles:

<template>
  <div class="app">

    <div class="row">
      <div class="col-sm" v-for="item in items">
        {{ item.prop1 }}
      </div>
    </div>

  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'app2',
  data() {
    return {
      items: []
    }
  },
// Fetch items from database...
}


问:
How to correctly dismiss a DialogFragment?
The docs say this for the dismiss() method from the Dialog class:

Dismiss this dialog, removing it from the screen. This method can be invoked
      safely from any thread. Note that you should not override this method to do
      cleanup when the dialog is dismissed, instead implement that in onStop().

In my code, all I do is call getDialog().dismiss() to dismiss it. But I am not doing anything else or even using onStop(). So I am asking exactly how to correctly dismiss a DialogFragment to avoid any memory leaks, etc..

答:
Adding to the other answers, when having a DialogFragment that is full screen calling dismiss() won't pop the DialogFragment from the fragment backstack. A workaround is to call onBackPressed() on the parent activity.

Something like this:

CustomDialogFragment.kt

```<code>closeButton.onClick {
    requireActivity().onBackPressed()
}
</code>```

Body:
Adding to the other answers, when having a DialogFragment that is full screen calling dismiss() won't pop the DialogFragment from the fragment backstack. A workaround is to call onBackPressed() on the parent activity.

Something like this:

CustomDialogFragment.kt

closeButton.onClick {
    requireActivity().onBackPressed()
}


问:
The importance of design in a spring app
I've been taking a look into using the spring framework for my java apps.

It is such a different way of looking at programming in general, i'm talking about DI and AOP!

The level of breaking the fundamental parts up into reusable components to me seems like a lot of work up front(in the design process). Im questioning the part of when I'll know its ready to get coding(this might just be in experience)

Guess I am looking at some tips? Where should you begin? It seems it has to be perfectly designed from the get go to avoid this tightly coupling scenario that seems so common amongst other applications I have worked with(not necessarily made them myself) When will I know its time to shoot my load and code?

Please don't tag this is a subjective or something I just want some honest and decent advice from the community.

Thanks in advance!

答:
When I went with Spring DI, I realized that I stopped spending so much time figuring out whether to instantiate objects, or look them up from some service or do something else to them.

You probably shouldn't go overboard with DI either. A good guideline would be to split app into beans at the "seams" where you would want to do unit tests. Similar approach - at the "seams" between application layers: data access, vs. business logic services, vs. UI.


问:
Insert different record in table using FOR loop by PL/SQL
I want to insert data in the table in that way, so that whenever command runs, different data is entered.
like,

```<code>create table oppo
(
name varchar(10),
class varchar(10),
roll number (5)
);
declare
s number;
i number;
n char(10);
c char(10);
r number;
begin
s:=:no_of_records;
for i in 1..s LOOP
n:=:Enter_Name;
c:=:Enter_Class;
r:=:Enter_Roll;
insert into oppo (name,class,roll) values (n,c,r);
END LOOP;
End;
</code>```

when i run the program, and enter no_of_records (5 or any number), and entering name and other data. As a result the same data is displayed 5 times (or number of times record entered). I want to enter unique data every 5 times.

答:
PL/SQL procedures aren't interactive. If you want to insert different values, replace this anonymous PL/SQL block with a stored procedure and run it as many times as you want, providing new values every time.

For example:

```<code>SQL> create table test (name varchar2(20), class number);

Table created.

SQL> create or replace procedure p_test (par_name in varchar2, par_class in number) as
  2  begin
  3    insert into test (name, class) values (par_name, par_class);
  4  end;
  5  /

Procedure created.
</code>```

```<code>SQL> exec p_test('&name', &class);
Enter value for name: LF
Enter value for class: 1

PL/SQL procedure successfully completed.

SQL> exec p_test('&name', &class);
Enter value for name: Bigfoot
Enter value for class: 2

PL/SQL procedure successfully completed.

SQL> exec p_test('&name', &class);
Enter value for name: Scott
Enter value for class: 3

PL/SQL procedure successfully completed.

SQL> select * From test;

NAME                      CLASS
-------------------- ----------
LF                            1
Bigfoot                       2
Scott                         3

SQL>
</code>```

Body:
I want to insert data in the table in that way, so that whenever command runs, different data is entered.
like,

create table oppo
(
name varchar(10),
class varchar(10),
roll number (5)
);
declare
s number;
i number;
n char(10);
c char(10);
r number;
begin
s:=:no_of_records;
for i in 1..s LOOP
n:=:Enter_Name;
c:=:Enter_Class;
r:=:Enter_Roll;
insert into oppo (name,class,roll) values (n,c,r);
END LOOP;
End;

when i run the program, and enter no_of_records (5 or any number), and entering name and other data. As a result the same data is displayed 5 times (or number of times record entered). I want to enter unique data every 5 times.

Body:
PL/SQL procedures aren't interactive. If you want to insert different values, replace this anonymous PL/SQL block with a stored procedure and run it as many times as you want, providing new values every time.

For example:

SQL> create table test (name varchar2(20), class number);

Table created.

SQL> create or replace procedure p_test (par_name in varchar2, par_class in number) as
  2  begin
  3    insert into test (name, class) values (par_name, par_class);
  4  end;
  5  /

Procedure created.

SQL> exec p_test('&name', &class);
Enter value for name: LF
Enter value for class: 1

PL/SQL procedure successfully completed.

SQL> exec p_test('&name', &class);
Enter value for name: Bigfoot
Enter value for class: 2

PL/SQL procedure successfully completed.

SQL> exec p_test('&name', &class);
Enter value for name: Scott
Enter value for class: 3

PL/SQL procedure successfully completed.

SQL> select * From test;

NAME                      CLASS
-------------------- ----------
LF                            1
Bigfoot                       2
Scott                         3

SQL>


问:
MongoDB find query: return duplicate records but which has unique existing ids
I have a collection document say test:

```<code>{id: 123,
 lId: abc,
 cnum: [{num: 112, type:R}]
},
{id: 234,
 lId: abc,
 cnum:[{ num: 112, type: R}]
},
{id: 345,
 lId: cbd,
 cnum: [{num: 112, type: R}]
},
{id: 456,
 lId: efg,
 cnum: [{num: 121, type:R}]
}
</code>```

I want the query to return values with duplicate cnum's num value but unique lId. That is it should return

```<code>id: 123,lId: abc, cnum.num: 112, id: 345,lId: cbd, cnum.num: 112
</code>```

but currently it is returning

```<code>id: 123,lId: abc,cnum.num: 112, id: 234, lId: abc, cnum.num: 112, id: 345,lId: cbd, cnum.num: 112
</code>```

My current script is returning the duplicate lId too. Here is my script:

```<code>var groupCnum = db.getCollection('test').aggregate([
{ $match: {"cnum.0": {$exists: true}}},
{ $unwind: "$cnum" },
{ $match: { "cnum.type": "R" } },
{ $group: { "_id": "$cnum.num", "count": { $sum: 1 } } },
{ $match: {"count": {"$gt": 1} } }
], {allowDiskUse: true}).map(record => record._id);

var duplicatedCnum = db.getCollection('test').aggregate([
{ $match: {"lId": {$nin: groupCnum}}},
{ $match: { "cnum.num": {$in: groupCnum} } },
{ $unwind: "$cnum" },
{ $match: { "cnum.type": "R" } },
{ $sort: {cnum: 1} },
{ $limit: 100}
], {allowDiskUse: true});
var fieldNames = ["id", "lId", "cnum.num"];
print(fieldNames.join(","));
</code>```

Can anyone suggest what am I missing?

答:
I was able to get the desired result with the following query in case it helps someone:</p>

```<code>db.getCollection('test').aggregate([
 {$match: {"cnum.0": { $exists: true }} },
 {$unwind: "$cnum"},
 {$match: { "cnum.type": "R"}},
 {$group: {"_id": {"lId": "$lId", "cnum": "$cnum.num" } } },
 {$group: {"_id": "$_id.cnum", "count": {$sum: 1}}},
 {$match: {"count": {"$gt": 1}}
}])
</code>```

Body:
I have a collection document say test:

{id: 123,
 lId: abc,
 cnum: [{num: 112, type:R}]
},
{id: 234,
 lId: abc,
 cnum:[{ num: 112, type: R}]
},
{id: 345,
 lId: cbd,
 cnum: [{num: 112, type: R}]
},
{id: 456,
 lId: efg,
 cnum: [{num: 121, type:R}]
}

I want the query to return values with duplicate cnum's num value but unique lId. That is it should return

id: 123,lId: abc, cnum.num: 112, id: 345,lId: cbd, cnum.num: 112

but currently it is returning

id: 123,lId: abc,cnum.num: 112, id: 234, lId: abc, cnum.num: 112, id: 345,lId: cbd, cnum.num: 112

My current script is returning the duplicate lId too. Here is my script:

var groupCnum = db.getCollection('test').aggregate([
{ $match: {"cnum.0": {$exists: true}}},
{ $unwind: "$cnum" },
{ $match: { "cnum.type": "R" } },
{ $group: { "_id": "$cnum.num", "count": { $sum: 1 } } },
{ $match: {"count": {"$gt": 1} } }
], {allowDiskUse: true}).map(record => record._id);

var duplicatedCnum = db.getCollection('test').aggregate([
{ $match: {"lId": {$nin: groupCnum}}},
{ $match: { "cnum.num": {$in: groupCnum} } },
{ $unwind: "$cnum" },
{ $match: { "cnum.type": "R" } },
{ $sort: {cnum: 1} },
{ $limit: 100}
], {allowDiskUse: true});
var fieldNames = ["id", "lId", "cnum.num"];
print(fieldNames.join(","));

Can anyone suggest what am I missing?

Body:
I was able to get the desired result with the following query in case it helps someone:

db.getCollection('test').aggregate([
 {$match: {"cnum.0": { $exists: true }} },
 {$unwind: "$cnum"},
 {$match: { "cnum.type": "R"}},
 {$group: {"_id": {"lId": "$lId", "cnum": "$cnum.num" } } },
 {$group: {"_id": "$_id.cnum", "count": {$sum: 1}}},
 {$match: {"count": {"$gt": 1}}
}])


问:
could not get unknown property 'android' for project ':shared_preferences' of type org.gradle.api.project
i am trying to use shared preference in my app and before I even use it, just adding the dependency gives me this error. anyone with any idea? thanks in advance</p>

答: I fixed it by changing the gradle version in the shared preferences build.gradle file to match with the one in the android folder in the flutter app.</p>


问:
How to simplify my less file without repeating statement with different value?
There are five less statements, and they're all the same except the value for padding-right.
Instead of repeating the statement five times, is there a way to simplify it into one statement?

```<code>h1 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 100px;
    }
  }
}
h3 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 50px;
    }
  }
}
h4 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 50px;
    }
  }
}
h5 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 25px;
    }
  }
}
</code>```

答:
Use mixins to reuse and not repeat the line of code.

Mixins are a way of including ("mixing in") a bunch of properties from one rule-set into another rule-set.

Exemple:

```<code>item {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background:
        url(../../resources/icon/external-link-alt.svg)
        no-repeat
        right;
    }
  }
}
</code>```

And we want to use these properties inside other rule-sets. Well, we just have to drop in the name of the class where we want the properties, like so:

```<code>h1 {
  item();
  padding-right: 100px;
}

h3 {
  item();
  padding-right: 75px;
}

h4 {
  item();
  padding-right: 50px;
}

h5 {
  item();
  padding-right: 25px;
}

</code>```

This is very helpful if you want to change something in the future, as you only need to modify the mixins in one place .

Body:
There are five less statements, and they're all the same except the value for padding-right.
Instead of repeating the statement five times, is there a way to simplify it into one statement?

h1 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 100px;
    }
  }
}
h3 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 50px;
    }
  }
}
h4 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 50px;
    }
  }
}
h5 {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background: url(../../resources/icon/external-link-alt.svg) no-repeat
        right;
      padding-right: 25px;
    }
  }
}

Body:
Use mixins to reuse and not repeat the line of code.

Mixins are a way of including ("mixing in") a bunch of properties from one rule-set into another rule-set.

Exemple:

item {
  a[href^="http://"], a[href^="https://"] {
    &:hover {
      background:
        url(../../resources/icon/external-link-alt.svg)
        no-repeat
        right;
    }
  }
}

And we want to use these properties inside other rule-sets. Well, we just have to drop in the name of the class where we want the properties, like so:

h1 {
  item();
  padding-right: 100px;
}

h3 {
  item();
  padding-right: 75px;
}

h4 {
  item();
  padding-right: 50px;
}

h5 {
  item();
  padding-right: 25px;
}

This is very helpful if you want to change something in the future, as you only need to modify the mixins in one place .


问:
How can I get an updated $Revision$ in my code
I have a project into which I'd like to embed the revision number automagically.

In this case, it's a multi-file perl script. In the main file, I have a line that looks like this:

my $revision = '$Revision: 24 $';

When I make a release, I checkout the project to my release dir.

The revision number does change whenever I check-in a change to THAT FILE. The $Revision$ attribute is updated on check-in, but not check-out.

The thing is, the main file doesn't change that often, so even though the other files in the project are now at 27, the main still has 24.

Is there a way that I can get the main file to reflect the latest rev number? The one that svn prints out at the end of the checkout, ie "Checked out revision 27."

答:
It is similar to CVS, you can use $Revision$ you just have to set the keyword property for that file for SVN to know it is supposed to do a keyword replace.

From the manual:

"With no svn:keywords property set on that file, Subversion will do nothing special. Now,
let's enable substitution of the LastChangedDate keyword.
$ svn propset svn:keywords "Date Author" weather.txt
property 'svn:keywords' set on 'weather.txt'
$
"

http://svnbook.red-bean.com/en/1.5/svn-book.pdf

OwnerDisplayName: mmccoo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mmccoo

OwnerDisplayName: Evan


问:
How to create a Google Cloud Compute Instance from the an instance template
I want to create a VM from my custom image via the instance template mechanism. I can see that the instance template is available. Below is my config :

```<code>config = {
        'name': name,
        'machineType': machine_type,

        # Specify the boot disk and the image to use as a source.
        'disks': [
            {
                'boot': True,
                'autoDelete': True,
                'initializeParams': {
                    'sourceImage': source_disk_image,
                }
            }
        ],

        # Specify a network interface with NAT to access the public
        # internet.
        'networkInterfaces': [{
            'network': 'global/networks/default',
            'accessConfigs': [
                {'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'}
            ]
        }],

        # Allow the instance to access cloud storage and logging.
        'serviceAccounts': [{
            'email': 'default',
            'scopes': [
                'https://www.googleapis.com/auth/devstorage.read_write',
                'https://www.googleapis.com/auth/logging.write'
            ]
        }],

        # Metadata is readable from the instance and allows you to
        # pass configuration from deployment scripts to instances.
        'metadata': {
            'items': [{
                # Startup script is automatically executed by the
                # instance upon startup.
                'key': 'startup-script',
                'value': startup_script,
                'VIDEOPATH': videopath,
                'uuid': uuid
            }]
        }
    }
</code>```

How can I use the python api to create the VM instance via the instance template ?

```<code>compute.instances().insert(
        project=project,
        zone=zone,
        body=config).execute()
</code>```

答:
The below item to should be added to the json including device name and sourceImage, and the Google Compute Instance will be created from the particular image.</p>

```<code>    # Specify the boot disk and the image to use as a source.
    "disks": [
        {
            "kind": "compute#attachedDisk",
            "type": "PERSISTENT",
            "boot": True,
            "mode": "READ_WRITE",
            "autoDelete": True,
            "deviceName": "instance-template-1",
            "initializeParams": {
                "sourceImage": "projects/supereye/global/images/image-1",
                "diskType": "projects/supereye/zones/europe-west2-b/diskTypes/pd-standard",
                "diskSizeGb": "10"
            }, "diskEncryptionKey": {}
        }
    ],
</code>```

Body:
I want to create a VM from my custom image via the instance template mechanism. I can see that the instance template is available. Below is my config :

config = {
        'name': name,
        'machineType': machine_type,

        # Specify the boot disk and the image to use as a source.
        'disks': [
            {
                'boot': True,
                'autoDelete': True,
                'initializeParams': {
                    'sourceImage': source_disk_image,
                }
            }
        ],

        # Specify a network interface with NAT to access the public
        # internet.
        'networkInterfaces': [{
            'network': 'global/networks/default',
            'accessConfigs': [
                {'type': 'ONE_TO_ONE_NAT', 'name': 'External NAT'}
            ]
        }],

        # Allow the instance to access cloud storage and logging.
        'serviceAccounts': [{
            'email': 'default',
            'scopes': [
                'https://www.googleapis.com/auth/devstorage.read_write',
                'https://www.googleapis.com/auth/logging.write'
            ]
        }],

        # Metadata is readable from the instance and allows you to
        # pass configuration from deployment scripts to instances.
        'metadata': {
            'items': [{
                # Startup script is automatically executed by the
                # instance upon startup.
                'key': 'startup-script',
                'value': startup_script,
                'VIDEOPATH': videopath,
                'uuid': uuid
            }]
        }
    }

How can I use the python api to create the VM instance via the instance template ?

compute.instances().insert(
        project=project,
        zone=zone,
        body=config).execute()

Body:
The below item to should be added to the json including device name and sourceImage, and the Google Compute Instance will be created from the particular image.

    # Specify the boot disk and the image to use as a source.
    "disks": [
        {
            "kind": "compute#attachedDisk",
            "type": "PERSISTENT",
            "boot": True,
            "mode": "READ_WRITE",
            "autoDelete": True,
            "deviceName": "instance-template-1",
            "initializeParams": {
                "sourceImage": "projects/supereye/global/images/image-1",
                "diskType": "projects/supereye/zones/europe-west2-b/diskTypes/pd-standard",
                "diskSizeGb": "10"
            }, "diskEncryptionKey": {}
        }
    ],


问:
need assistance with css layout

  I am having css layout issues.  I am attempting to align the Required! message to the right of the input elements

Keeping the flow:

Species:

input element    error-message

Breed:

input element    error-message

I tried various nested divs with-out success.

Link:

http://jsfiddle.net/d0773d/BpqyT/

答:
Divs are block-level elements, so they will force a new line by default. To correct this, change:

```<code><div id="species_error">
</code>```

and

```<code><div id="breed_error">
</code>```

to:

```<code><div id="species_error" style="display:inline-block">
</code>```

and

```<code><div id="breed_error" style="display:inline-block">
</code>```

Title: need assistance with css layout

Body:
Divs are block-level elements, so they will force a new line by default. To correct this, change:

<div id="species_error">

and

<div id="breed_error">

to:

<div id="species_error" style="display:inline-block">

and

<div id="breed_error" style="display:inline-block">


问:
restart docker containers after reboot
I have been trying to make docker containers restart after reboot. I am using --restart unless-stopped
 option. Container starts after reboot but I have to be logged in to my remote machine. I am running docker on my remote machine.

```<code>docker run --restart unless-stopped -d -v /var/run/docker.sock:/var/run/docker.sock --net sp-example-net -p 8080:8080 sp
</code>```

答: Docker has restart policies such as --restart=always that will handle this. This is also available in the compose.yml config file as restart: always.</p>

Title: restart docker containers after reboot

Body:
I have been trying to make docker containers restart after reboot. I am using --restart unless-stopped
 option. Container starts after reboot but I have to be logged in to my remote machine. I am running docker on my remote machine.

docker run --restart unless-stopped -d -v /var/run/docker.sock:/var/run/docker.sock --net sp-example-net -p 8080:8080 sp


问:
reading character for scanf when it is suppose to be an int
I'm using scanf to read in an int, however, I to make create an error if someone puts something other than an int. I have noticed that if I input a character for scanf("%d",%number);, it saves it as 0. I would like 0 to be an option. How do i avoid this issues?

the test code would be
int number;
   scanf("%d",&number);
   printf("%d",number);

答:
Try this method to see if the entered input was a number %d:

```<code>#include <stdio.h>

int main(void) {
    int number;

    if (scanf("%d", &number))
        printf("A number!\n");
    else
        printf("Not a number!\n");

    return 0;
}
</code>```

Body:
Try this method to see if the entered input was a number %d:

#include <stdio.h>

int main(void) {
    int number;

    if (scanf("%d", &number))
        printf("A number!\n");
    else
        printf("Not a number!\n");

    return 0;
}


问:
How to open new controller for the UICollectionViewCell
I have follow https://www.freecodecamp.org/news/autolayout-programmatically-spotify-clone-in-swift/ to create a uicollectionview but the different is I use UIView to implement. However I don't know how to click to each cell of the Sub-UICollectionCell  and open a new UIController. Below is my code.

```<code>Class HomeView : UIView,UICollectionViewDataSource,UICollectionViewDelegate   ,UICollectionViewDelegateFlowLayout{
    lazy var collectionView : UICollectionView = {
      let layout = UICollectionViewFlowLayout()
      let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
      cv.translatesAutoresizingMaskIntoConstraints = false
      cv.delegate = self
      cv.dataSource = self
      cv.register(HomeCollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
      cv.backgroundColor = UIColor(hexString: "#F7F7F7")
      return cv
    }()
    override init(frame: CGRect) {
      super.init(frame: frame)
      addSubview(collectionView)

    }

   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      return sections.count
   }

   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)  -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! HomeCollectionViewCell
      cell.section = sections[indexPath.item]

      return cell
    }
</code>```

}

where I have HomeCollectionCell as

```<code>class HomeCollectionViewCell : UICollectionViewCell , UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,UICollectionViewDataSource{
   override init(frame: CGRect) {
      super.init(frame: frame)
      addSubview(titleLabel)
      collectionView.dataSource = self
      collectionView.delegate = self
      collectionView.register(SubHomeViewCell.self, forCellWithReuseIdentifier: cellId)
      setupSubCells()
    }

  fileprivate  func setupSubCells(){
       // add collectionView to the view
       addSubview(collectionView)

       collectionView.dataSource = self
       collectionView.delegate = self

   }

   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return  self.subCategorys.count
   }
   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SubHomeViewCell
       cell.subCategory = subCategorys[indexPath.item]
       return cell
   }

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

       let width = frame.height
       let height = frame.height

       return CGSize(width: width, height: height)

  }
</code>```

}

For my SubHomeView I just add the addSubview of image and title
I need to click each cell to open a controller page to show each menu detail.

答:
Pass in a weak var reference to your controller in HomeView.Then, use didSelectItemAt method of UICollectionView inside your HomeView, here is an example:

weak var homeViewController: HomeViewController?

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let newViewController = UIViewController()
    newViewController.view.backgroundColor = .purple
    homeViewController?.navigationController?.pushViewController(newViewController, animated: true)
}
```

Body:
I have follow https://www.freecodecamp.org/news/autolayout-programmatically-spotify-clone-in-swift/ to create a uicollectionview but the different is I use UIView to implement. However I don't know how to click to each cell of the Sub-UICollectionCell  and open a new UIController. Below is my code.

Class HomeView : UIView,UICollectionViewDataSource,UICollectionViewDelegate   ,UICollectionViewDelegateFlowLayout{
    lazy var collectionView : UICollectionView = {
      let layout = UICollectionViewFlowLayout()
      let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
      cv.translatesAutoresizingMaskIntoConstraints = false
      cv.delegate = self
      cv.dataSource = self
      cv.register(HomeCollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
      cv.backgroundColor = UIColor(hexString: "#F7F7F7")
      return cv
    }()
    override init(frame: CGRect) {
      super.init(frame: frame)
      addSubview(collectionView)

    }

   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      return sections.count
   }

   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)  -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! HomeCollectionViewCell
      cell.section = sections[indexPath.item]

      return cell
    }

}

where I have HomeCollectionCell as

class HomeCollectionViewCell : UICollectionViewCell , UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,UICollectionViewDataSource{
   override init(frame: CGRect) {
      super.init(frame: frame)
      addSubview(titleLabel)
      collectionView.dataSource = self
      collectionView.delegate = self
      collectionView.register(SubHomeViewCell.self, forCellWithReuseIdentifier: cellId)
      setupSubCells()
    }

  fileprivate  func setupSubCells(){
       // add collectionView to the view
       addSubview(collectionView)

       collectionView.dataSource = self
       collectionView.delegate = self

   }

   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return  self.subCategorys.count
   }
   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SubHomeViewCell
       cell.subCategory = subCategorys[indexPath.item]
       return cell
   }

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

       let width = frame.height
       let height = frame.height

       return CGSize(width: width, height: height)

  }

}

For my SubHomeView I just add the addSubview of image and title
I need to click each cell to open a controller page to show each menu detail.


问:
GUı programming in tkinter, when ı create a windows and input labe ı cant assign
ı am new in tkinter. I want to multpily two inputs box. my codes are below. The problem is when i run it runs as x2*x2 but i want to x2*x1  how can ı fix this code it runs only one box</p>

```<code>import tkinter as tk
from functools import partial
from tkinter import *

root=tk.Tk()
root.geometry("900x900+100+200")

root.title("Converter")
root.configure(background="grey")
root.resizable(width=False,height=False)
def call_result15(rL,inputn):
  x1=inputn.get()
  x2=inputn.get()
  h=float(float(x1)*float(x2))
  rL.config(text="% f " % h)

  return
numberInput=tk.StringVar()
var=tk.StringVar()
input_label=tk.Label(root,text="x1",background="white",foreground="black")
input_entry=tk.Entry(root,textvariable=numberInput)
input_label.grid()
input_entry.grid()
numberInput2=tk.StringVar()
var2=tk.StringVar()
input_label=tk.Label(root,text="x2",background="white",foreground="black")
input_entry=tk.Entry(root,textvariable=numberInput2)
input_label.grid()
input_entry.grid()

 rlabel=tk.Label(root,text="h1",background="white",foreground="black")
 rlabel.grid()

call_result15=partial(call_result15,rlabel,numberInput2)

result_button.grid()

 root.mainloop()
</code>```

答:
```<code>def call_result15(rL,inputn):
  x1=inputn.get()
  x2=inputn.get()
</code>```

x1 and x2 are both read from the same supplied inputn parameter...

```<code>call_result15=partial(call_result15,rlabel,numberInput2)
</code>```

which is bound here. So of course we multiply the value from numberInput2 by itself.

You need to write the callback so it accepts (and uses) both inputs, and bind both of them in the partial.

Body:
ı am new in tkinter. I want to multpily two inputs box. my codes are below. The problem is when i run it runs as x2*x2 but i want to x2*x1  how can ı fix this code it runs only one box

import tkinter as tk
from functools import partial
from tkinter import *

root=tk.Tk()
root.geometry("900x900+100+200")

root.title("Converter")
root.configure(background="grey")
root.resizable(width=False,height=False)
def call_result15(rL,inputn):
  x1=inputn.get()
  x2=inputn.get()
  h=float(float(x1)*float(x2))
  rL.config(text="% f " % h)

  return
numberInput=tk.StringVar()
var=tk.StringVar()
input_label=tk.Label(root,text="x1",background="white",foreground="black")
input_entry=tk.Entry(root,textvariable=numberInput)
input_label.grid()
input_entry.grid()
numberInput2=tk.StringVar()
var2=tk.StringVar()
input_label=tk.Label(root,text="x2",background="white",foreground="black")
input_entry=tk.Entry(root,textvariable=numberInput2)
input_label.grid()
input_entry.grid()

 rlabel=tk.Label(root,text="h1",background="white",foreground="black")
 rlabel.grid()

call_result15=partial(call_result15,rlabel,numberInput2)

result_button.grid()

 root.mainloop()

Body:
def call_result15(rL,inputn):
  x1=inputn.get()
  x2=inputn.get()

x1 and x2 are both read from the same supplied inputn parameter...

call_result15=partial(call_result15,rlabel,numberInput2)

which is bound here. So of course we multiply the value from numberInput2 by itself.

You need to write the callback so it accepts (and uses) both inputs, and bind both of them in the partial.


答:
You can use 'text-align: right;' to make the message snap to the right of its available area.  But when you do that, it becomes evident that the parent containers don't line up vertically.  You'll need to re-work your markup and CSS.  Try one of these:

Two div columns, "right" and "left" which contain either right or left halves of the content

Getting rid of the container divs, and just using float and width to line everything up.

Title: need assistance with css layout

Body:
  I am having css layout issues.  I am attempting to align the Required! message to the right of the input elements

Keeping the flow:

Species:

input element    error-message

Breed:

input element    error-message

I tried various nested divs with-out success.

Link:

http://jsfiddle.net/d0773d/BpqyT/


问:
How to resolve the NZEC error on Codechef?
This is the code, which is working fine on my machine. But while submitting it in Codechef there is a problem named NZEC error, from which I am not familiar with and don't know how to debug that. Where I am wrong?

Question: https://www.codechef.com/problems/SNELECT

```<code>    import java.io.*;
    import java.util.*;
    class A
     {
public static void main(String args[]) throws IOException
{

    int t,i;
    Scanner sc= new Scanner(System.in);
    t=sc.nextInt();
    while(t>0)                                //testcases
    {
        int eaten=0,m=0,s=0;
    String a=new String();
    a=sc.next();
    int n= a.length();
    for( i=0;i<n;i++)
    {
        if(a.charAt(i)=='m')                //counting_m&s
            m++;
        else if(a.charAt(i)=='s')
            s++;
    }
    if(a.charAt(0) == 'm' && a.charAt(1)=='s')
    {
        eaten++;                   //mongoos eaten atmost 1 snake
        a=a.substring(0,1)+'x'+a.substring(2);  //removing eaten snake from string
    }
    if(a.charAt(n-1) == 'm' && a.charAt(n-2)=='s')
    {
        eaten++;
        a=a.substring(0,n-2)+'x'+a.substring(n-1);
    }
    for( i=1;i<n-1;i++)
    {
        if(a.charAt(i) == 'm' && a.charAt(i-1)=='s')
        {
        eaten++;
        a=a.substring(0,i-1)+'x'+a.substring(i);
        }
        else if(a.charAt(i) == 'm' && a.charAt(i+1)=='s')
        {
        eaten++;
        a=a.substring(0,i+1)+'x'+a.substring(i+2);
        }
    }
    if(s-eaten < m)
        System.out.println("mongooses");    //checking the winner
    else if(s- eaten > m)
        System.out.println("snakes");
    else
        System.out.println("tie");
t--;
        }
   }
      }
</code>```

答:
NZEC is a runtime error.
It mostly occurs when negative array index is accessed or the program which we have written takes up more space than the allocated memory for our program to run.Try:

```<code>try{
    // code which you think might throw exception
}catch(java.lang.Throwable t){
    // code to catch that exception or simply don't give any code leave it blank
}
</code>```

Throwable class is super class of all error and exception classes in Java.

Body:
This is the code, which is working fine on my machine. But while submitting it in Codechef there is a problem named NZEC error, from which I am not familiar with and don't know how to debug that. Where I am wrong?

Question: https://www.codechef.com/problems/SNELECT

    import java.io.*;
    import java.util.*;
    class A
     {
public static void main(String args[]) throws IOException
{

    int t,i;
    Scanner sc= new Scanner(System.in);
    t=sc.nextInt();
    while(t>0)                                //testcases
    {
        int eaten=0,m=0,s=0;
    String a=new String();
    a=sc.next();
    int n= a.length();
    for( i=0;i<n;i++)
    {
        if(a.charAt(i)=='m')                //counting_m&s
            m++;
        else if(a.charAt(i)=='s')
            s++;
    }
    if(a.charAt(0) == 'm' && a.charAt(1)=='s')
    {
        eaten++;                   //mongoos eaten atmost 1 snake
        a=a.substring(0,1)+'x'+a.substring(2);  //removing eaten snake from string
    }
    if(a.charAt(n-1) == 'm' && a.charAt(n-2)=='s')
    {
        eaten++;
        a=a.substring(0,n-2)+'x'+a.substring(n-1);
    }
    for( i=1;i<n-1;i++)
    {
        if(a.charAt(i) == 'm' && a.charAt(i-1)=='s')
        {
        eaten++;
        a=a.substring(0,i-1)+'x'+a.substring(i);
        }
        else if(a.charAt(i) == 'm' && a.charAt(i+1)=='s')
        {
        eaten++;
        a=a.substring(0,i+1)+'x'+a.substring(i+2);
        }
    }
    if(s-eaten < m)
        System.out.println("mongooses");    //checking the winner
    else if(s- eaten > m)
        System.out.println("snakes");
    else
        System.out.println("tie");
t--;
        }
   }
      }

Body:
NZEC is a runtime error.
It mostly occurs when negative array index is accessed or the program which we have written takes up more space than the allocated memory for our program to run.Try:

try{
    // code which you think might throw exception
}catch(java.lang.Throwable t){
    // code to catch that exception or simply don't give any code leave it blank
}

Throwable class is super class of all error and exception classes in Java.


问:
How to convert rows to columns with commasepart using huge data in SQL Server
I have a question about SQL Server: how to convert rows to columns with comma-separated data using bulk data?

```<code>CREATE TABLE [dbo].[Emp]
(
    [eid] [int] NULL,
    [name] [varchar](50) NULL,
    [sal] [money] NULL,
    [doj] [date] NULL,
    [deptno] [int] NULL
)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (1, N'a', 100.0000, CAST(N'2010-10-01' AS Date), 10)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (2, N'bb', 200.0000, CAST(N'2010-02-03' AS Date), 20)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (3, N'c', 300.0000, CAST(N'2017-02-03' AS Date), 30)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (4, N'd', 301.0000, CAST(N'2010-03-04' AS Date), 10)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (5, N'teee', 250.0000, CAST(N'2010-06-04' AS Date), 20)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (7, N'tte', 800.0000, CAST(N'2010-08-09' AS Date), 70)
</code>```

I want output like below :

```<code>userlist
1,2,3,4,5,7
</code>```

I tried this code:

```<code>select distinct
    stuff((select ',' + cast(u.eid as varchar)
           from emp u
           where 1 = 1
           for xml path('')), 1, 1, '') as userlist
from emp
</code>```

Suppose if data has 100 thousand entries, then this query is not returning 100 thousand comma-separated

Could you please tell me how to write query to achieve this task in SQL Server?

答: I think the query is working as expected.  But the result is too large to be displayed in management studio. </p>

Body:
I have a question about SQL Server: how to convert rows to columns with comma-separated data using bulk data?

CREATE TABLE [dbo].[Emp]
(
    [eid] [int] NULL,
    [name] [varchar](50) NULL,
    [sal] [money] NULL,
    [doj] [date] NULL,
    [deptno] [int] NULL
)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (1, N'a', 100.0000, CAST(N'2010-10-01' AS Date), 10)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (2, N'bb', 200.0000, CAST(N'2010-02-03' AS Date), 20)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (3, N'c', 300.0000, CAST(N'2017-02-03' AS Date), 30)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (4, N'd', 301.0000, CAST(N'2010-03-04' AS Date), 10)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (5, N'teee', 250.0000, CAST(N'2010-06-04' AS Date), 20)

INSERT [dbo].[Emp] ([eid], [name], [sal], [doj], [deptno])
VALUES (7, N'tte', 800.0000, CAST(N'2010-08-09' AS Date), 70)

I want output like below :

userlist
1,2,3,4,5,7

I tried this code:

select distinct
    stuff((select ',' + cast(u.eid as varchar)
           from emp u
           where 1 = 1
           for xml path('')), 1, 1, '') as userlist
from emp

Suppose if data has 100 thousand entries, then this query is not returning 100 thousand comma-separated

Could you please tell me how to write query to achieve this task in SQL Server?


问:
Remove an ID if a input value is = some defined code
I want to remove an input id when another input id having value in defined values

my codes

```<code>setInterval(function() {
  var MaterialGod = [
    "FPPUTHP1100000",
    "FPPUTHP1100000",
    "FPPUTHP1110000",
    "FPPUTHP1500000",
    "FPPUTHP1680000",
    "FPPUTHP1690000",
    "FPPUTHP1590000"
  ];

  $.each(MaterialGod, function(index) {
    if ($("label:contains('Meterial Code')").parent().next().find('input').val() == index) {
      $('#__item5-__box2-0').remove();
    }
  })
}, 100);
</code>```

Pls give your advise what i m doing wrong

答:
You're comparing the array index, not the array element, with the value.

There's also no reason to put the selector in the loop, since you're selecting the same input every time.

Just get the input value, and use .includes() to see if it's in the array.

setInterval(function() {
  var MaterialGod = [
    "FPPUTHP1100000",
    "FPPUTHP1100000",
    "FPPUTHP1110000",
    "FPPUTHP1500000",
    "FPPUTHP1680000",
    "FPPUTHP1690000",
    "FPPUTHP1590000"
  ];
  if MaterialGod.includes($("label:contains('Meterial Code')").parent().next().find('input').val()) {
    $('#__item5-__box2-0').remove();
  }
}, 100);```

Body:
I want to remove an input id when another input id having value in defined values

my codes

setInterval(function() {
  var MaterialGod = [
    "FPPUTHP1100000",
    "FPPUTHP1100000",
    "FPPUTHP1110000",
    "FPPUTHP1500000",
    "FPPUTHP1680000",
    "FPPUTHP1690000",
    "FPPUTHP1590000"
  ];

  $.each(MaterialGod, function(index) {
    if ($("label:contains('Meterial Code')").parent().next().find('input').val() == index) {
      $('#__item5-__box2-0').remove();
    }
  })
}, 100);

Pls give your advise what i m doing wrong


问:
declaring an array of pointers in a C header file and assigning value?
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in a C header file?

```<code>char *i[2];
i[0] = "abc";
</code>```

the following does not work.

```<code>char *x = "def"; // this will, of course.
</code>```

How am I supposed to declare and assign values for an array of pointers?

答:
Is this what you're looking for?

```<code>char *i[2] = {"abc", "def"};
</code>```

Though it'll give you a warning unless you make them const char *

```<code>const char *i[2] = {"abc", "def"};
</code>```

Body:
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in a C header file?

char *i[2];
i[0] = "abc";

the following does not work.

char *x = "def"; // this will, of course.

How am I supposed to declare and assign values for an array of pointers?

Body:
Is this what you're looking for?

char *i[2] = {"abc", "def"};

Though it'll give you a warning unless you make them const char *

const char *i[2] = {"abc", "def"};


问:
Tensorflow 2: apply one hot encoding on masks for semantic segmentation
I'm trying to process my ground truth images to create one hot encoded tensors:

```<code>def one_hot(img, nclasses):
  result = np.zeros((img.shape[0], img.shape[1], nclasses))
  img_unique = img.reshape(512*512, img.shape[2])
  unique = np.unique(img_unique, axis=0)
  for i in range(img.shape[0]):
    for j in range(img.shape[1]):
      for k, unique_val in enumerate(unique):
        if (np.array_equal(img[i,j], unique_val)):
          result[i,j,k] = 1
          break

  return result
</code>```

This is creating WxHxN tensor from WxHx3 image. I really don't like such approach because of its performance. Could you advice more efficient way?

I tried to use tf.one_hot but it converts the image into WxHx3xN tensor.

答:
For your specific scenario where the 3 classes are known this should work faster</p>

```<code>def one_hot2(img):
    class1 = [255,0,0]
    class2 = [0,0,255]
    class3 = [255,255,255]
    label = np.zeros_like(img)
    label[np.sum(img==np.array([[class2]]), 2)==3] = 1
    label[np.sum(img==np.array([[class3]]), 2)==3] = 2
    onehot = np.eye(3)[label]
    return onehot
</code>```

Body:
I'm trying to process my ground truth images to create one hot encoded tensors:

def one_hot(img, nclasses):
  result = np.zeros((img.shape[0], img.shape[1], nclasses))
  img_unique = img.reshape(512*512, img.shape[2])
  unique = np.unique(img_unique, axis=0)
  for i in range(img.shape[0]):
    for j in range(img.shape[1]):
      for k, unique_val in enumerate(unique):
        if (np.array_equal(img[i,j], unique_val)):
          result[i,j,k] = 1
          break

  return result

This is creating WxHxN tensor from WxHx3 image. I really don't like such approach because of its performance. Could you advice more efficient way?

I tried to use tf.one_hot but it converts the image into WxHx3xN tensor.

Body:
For your specific scenario where the 3 classes are known this should work faster

def one_hot2(img):
    class1 = [255,0,0]
    class2 = [0,0,255]
    class3 = [255,255,255]
    label = np.zeros_like(img)
    label[np.sum(img==np.array([[class2]]), 2)==3] = 1
    label[np.sum(img==np.array([[class3]]), 2)==3] = 2
    onehot = np.eye(3)[label]
    return onehot


问:
How can I use a class that use conditional export in Angular's app.module?
This question is the beggining of the story if you want to understand it deeper.

I'm trying to use this class in app.module:

```<code>import { Injectable } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { environment } from '../../../environments/environment';

@Injectable({ providedIn: 'root' })
export class MockKeycloakService {

    init(ign: any) {
        console.log('[KEYCLOAK] Mocked Keycloak call');
        return Promise.resolve(true);
    }

    getKeycloakInstance() {
        return {
            loadUserInfo: () => {
                let callback;
                Promise.resolve().then(() => {
                    callback({
                    username: '111111111-11',
                    name: 'Whatever Something de Paula',
                    email: 'whatever@gmail.com',
                  });
                });
                return { success: (fn) => callback = fn };
            }
        } as any;
    }
    login() {}
    logout() {}
}

const exportKeycloak =
    environment.production ? KeycloakService : MockKeycloakService;
export default exportKeycloak;
</code>```

This conditional export fakes keycloak call to use in local development and returns the real class in production.

This is the app.module I used:

```<code><...>
import { KeycloakAngularModule } from 'keycloak-angular';
import KeycloakService from './shared/services/keycloak-mock.service';
import { initializer } from './app-init';
<...>

    imports: [
        KeycloakAngularModule,
         <...>
    ],
    providers: [
        <...>,
        {
            provide: APP_INITIALIZER,
            useFactory: initializer,
            multi: true,
            deps: [KeycloakService, <...>]
        },
        <...>
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

related app-init:

```<code>import KeycloakService from './shared/services/keycloak.mock.service';
import { KeycloakUser } from './shared/models/keycloakUser';

import { environment } from '../environments/environment';
<...>

export function initializer(
    keycloak: any,
    <...>
): () => Promise<any> {
    return (): Promise<any> => {
        return new Promise(async (res, rej) => {
            <...>
            await keycloak.init({
                 <...>
            }).then((authenticated: boolean) => {
                if (!authenticated) return;
                keycloak
                    .getKeycloakInstance()
                    .loadUserInfo()
                    .success(async (user: KeycloakUser) => {
                        <...>
                    })
            }).catch((err: any) => rej(err));
            res();
        });
    };
</code>```

All works fine in the development mode. I can use the mocked call, and if I enable production in environment.config it makes the real call.
But when I try to build it to publish in production server I get the following error:

```<code>ERROR in Can't resolve all parameters for ɵ1 in /vagrant/frontend/src/app/app.module.ts: (?, [object Object], [object Object]).
</code>```

My guess is that the builder task can't understand the conditional export in the mocked class to use in app.module.

So this forced me to use both classes in the app-init and other class I use it and check for the environment mode in every one. I think it would be a much better solution if I could use only one class to treat this and just import it in all places I need.

this is my build command:

```<code>ng build --prod=true --configuration=production --delete-output-path --output-path=dist/
</code>```

How can I overcome this error in the build ? Also... why on earth all works well in dev mode and the build behaves differently ?

答:
I guess you're using Angular 8 or less.

AOT compiler in those versions doesn't support resolving reference to default export.

So you should be more specific:

keycloak-mock.service.ts

```<code>const KeycloakServiceImpl =
  environment.production ? KeycloakService : MockKeycloakService;
export { KeycloakServiceImpl };
</code>```

app.module.ts

```<code>import { KeycloakServiceImpl } from './keycloak-mock.service';

...
deps: [KeycloakServiceImpl]
</code>```

Tip:

ng build --prod is an equivalent of ng build --prod=true --configuration=production

Body:
This question is the beggining of the story if you want to understand it deeper.

I'm trying to use this class in app.module:

import { Injectable } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { environment } from '../../../environments/environment';

@Injectable({ providedIn: 'root' })
export class MockKeycloakService {

    init(ign: any) {
        console.log('[KEYCLOAK] Mocked Keycloak call');
        return Promise.resolve(true);
    }

    getKeycloakInstance() {
        return {
            loadUserInfo: () => {
                let callback;
                Promise.resolve().then(() => {
                    callback({
                    username: '111111111-11',
                    name: 'Whatever Something de Paula',
                    email: 'whatever@gmail.com',
                  });
                });
                return { success: (fn) => callback = fn };
            }
        } as any;
    }
    login() {}
    logout() {}
}

const exportKeycloak =
    environment.production ? KeycloakService : MockKeycloakService;
export default exportKeycloak;

This conditional export fakes keycloak call to use in local development and returns the real class in production.

This is the app.module I used:

<...>
import { KeycloakAngularModule } from 'keycloak-angular';
import KeycloakService from './shared/services/keycloak-mock.service';
import { initializer } from './app-init';
<...>

    imports: [
        KeycloakAngularModule,
         <...>
    ],
    providers: [
        <...>,
        {
            provide: APP_INITIALIZER,
            useFactory: initializer,
            multi: true,
            deps: [KeycloakService, <...>]
        },
        <...>
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

related app-init:

import KeycloakService from './shared/services/keycloak.mock.service';
import { KeycloakUser } from './shared/models/keycloakUser';

import { environment } from '../environments/environment';
<...>

export function initializer(
    keycloak: any,
    <...>
): () => Promise<any> {
    return (): Promise<any> => {
        return new Promise(async (res, rej) => {
            <...>
            await keycloak.init({
                 <...>
            }).then((authenticated: boolean) => {
                if (!authenticated) return;
                keycloak
                    .getKeycloakInstance()
                    .loadUserInfo()
                    .success(async (user: KeycloakUser) => {
                        <...>
                    })
            }).catch((err: any) => rej(err));
            res();
        });
    };

All works fine in the development mode. I can use the mocked call, and if I enable production in environment.config it makes the real call.
But when I try to build it to publish in production server I get the following error:

ERROR in Can't resolve all parameters for ɵ1 in /vagrant/frontend/src/app/app.module.ts: (?, [object Object], [object Object]).

My guess is that the builder task can't understand the conditional export in the mocked class to use in app.module.

So this forced me to use both classes in the app-init and other class I use it and check for the environment mode in every one. I think it would be a much better solution if I could use only one class to treat this and just import it in all places I need.

this is my build command:

ng build --prod=true --configuration=production --delete-output-path --output-path=dist/

How can I overcome this error in the build ? Also... why on earth all works well in dev mode and the build behaves differently ?

Body:
I guess you're using Angular 8 or less.

AOT compiler in those versions doesn't support resolving reference to default export.

So you should be more specific:

keycloak-mock.service.ts

const KeycloakServiceImpl =
  environment.production ? KeycloakService : MockKeycloakService;
export { KeycloakServiceImpl };

app.module.ts

import { KeycloakServiceImpl } from './keycloak-mock.service';

...
deps: [KeycloakServiceImpl]

Tip:

ng build --prod is an equivalent of ng build --prod=true --configuration=production


问:
Localized currency symbol from NumberFormatter
how to set NumberFormatter to return currency symbol not the iso one but local which is visible in iOS locale settings pane. Like for Polish currency I need to have “zł” symbol not the “PLN”.

I cannot find any way to get it from system as this cannot be hardcoded. IAP localized price also uses “zł” not “PLN”

I tried this way:

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = Locale.current.currencySymbol
formatter.maximumFractionDigits = 2

let price = formatter.string(from: (offeringPrice / 12) as NSNumber) ?? ""
```

but whatever I try to use as currency symbol I always get in return "PLN"

答:
If you set formatter.locale to pl_PL it works:

```<code>let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
formatter.currencyCode = "PLN"

let polandLocale = Locale(identifier: "pl_PL")
let usLocale = Locale(identifier: "en_US")

let offeringPrice = 50.0
let price = (offeringPrice / 12) as NSNumber

formatter.locale = usLocale
formatter.string(from: price) // "PLN 4.17"

formatter.locale = polandLocale
formatter.string(from: price) // "4,17 zł"
</code>```

Body:
how to set NumberFormatter to return currency symbol not the iso one but local which is visible in iOS locale settings pane. Like for Polish currency I need to have “zł” symbol not the “PLN”.

I cannot find any way to get it from system as this cannot be hardcoded. IAP localized price also uses “zł” not “PLN”

I tried this way:

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = Locale.current.currencySymbol
formatter.maximumFractionDigits = 2

let price = formatter.string(from: (offeringPrice / 12) as NSNumber) ?? ""

but whatever I try to use as currency symbol I always get in return "PLN"

Body:
If you set formatter.locale to pl_PL it works:

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
formatter.currencyCode = "PLN"

let polandLocale = Locale(identifier: "pl_PL")
let usLocale = Locale(identifier: "en_US")

let offeringPrice = 50.0
let price = (offeringPrice / 12) as NSNumber

formatter.locale = usLocale
formatter.string(from: price) // "PLN 4.17"

formatter.locale = polandLocale
formatter.string(from: price) // "4,17 zł"


问:
Get specific data from JSON file to listview
Trying to get second user data only

which have id :2 (whole his data)

Problem is when I get data, it show all users, not only second.

I heard about I can get it using Arraylist, but cant figure out how to make it.

```<code>mListView.get(position).get(Mykey);
</code>```

is there anyway to get specific user data, not show all users data, I'm new in android

users.json

```<code>[
{
"id": "1",
"name": "tester1",
"username": "user1",
"verify": "1",
"about": "tesst",
"description": "description....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
},
{
"id": "2",
"name": "tester2",
"username": "user2",
"verify": "0",
"about": "tesst",
"description": "description ....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
},
{
"id": "3",
"name": "tester3",
"username": "user3",
"verify": "0",
"about": "tesst",
"description": "description ....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
}
]
</code>```

ActivityMain

```<code>class Spacecraft {
    /*
    INSTANCE FIELDS
     */
    @SerializedName("id")
    private String id;

    @SerializedName("name")
    private String name;

    @SerializedName("username")
    private String username;

    @SerializedName("password")
    private String password;

    @SerializedName("about")
    private String about;

    @SerializedName("description")
    private String description;

    @SerializedName("mobile")
    private String mobile;

    @SerializedName("lvl")
    private String lvl;

    @SerializedName("imageurl")
    private String imageURL;

    @SerializedName("technologyexists")
    private int technologyexists;

    @SerializedName("verify")
    private String verify;
    ////////

    public Spacecraft(String id, String name, String username,String password, String about, String description,  String mobile, String lvl, String imageURL, int technologyexists, String verify) {

        this.id = id;
        this.name = name;

        this.username = username;
        this.password = password;

        this.about = about;
        this.description = description;

        this.mobile = mobile;
        this.lvl = lvl;

        this.imageURL = imageURL;
        this.technologyexists = technologyexists;

        this.verify = verify;

    }

    /*
     *GETTERS AND SETTERS
     */
    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getusername() {
        return username;
    }

    public String getpassword() {
        return password;
    }

    public String getAbout() {
        return about;
    }

    public String getImageURL() {
        return imageURL;
    }

    public String getMobile() {
        return mobile;
    }

    public String getlvl() {
        return lvl;
    }

    public String getDescription() {
        return description;
    }

    public String getVerify() {
        return verify;
    }

    public int getTechnologyExists() {
        return technologyexists;
    }

    /*
    TOSTRING
     */
    @Override
    public String toString() {
        return name;
    }
}

 interface MyAPIService {

    @GET("/users.json")
    Call<List<Spacecraft>> getSpacecrafts();
}

    static class RetrofitClientInstance {

    private static Retrofit retrofit;
    private static final String BASE_URL = "http://Server_ip_to_get_json_file:80/";

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

    class ListViewAdapter extends BaseAdapter{

    private List<Spacecraft> spacecrafts;
    private Context context;

    public ListViewAdapter(Context context,List<Spacecraft> spacecrafts){
        this.context = context;
        this.spacecrafts = spacecrafts;
    }

    @Override
    public int getCount() {
        return spacecrafts.size();
    }

    @Override
    public Object getItem(int pos) {
        return spacecrafts.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view=LayoutInflater.from(context).inflate(R.layout.model,viewGroup,false);
        }

        TextView nameTxt = view.findViewById(R.id.nameTextView);
        TextView txtPropellant = view.findViewById(R.id.propellantTextView);
        CheckBox chkTechExists = view.findViewById(R.id.myCheckBox);
        ImageView spacecraftImageView = view.findViewById(R.id.spacecraftImageView);

        final Spacecraft thisSpacecraft= spacecrafts.get(position);

        nameTxt.setText(thisSpacecraft.getName());
        //  txtPropellant.setText("Lvl : "+thisSpacecraft.getPropellant());
        txtPropellant.setText("Lvl : "+thisSpacecraft.getlvl());
        chkTechExists.setChecked( thisSpacecraft.getTechnologyExists()==1);
        chkTechExists.setEnabled(false);

        if(thisSpacecraft.getImageURL() != null && thisSpacecraft.getImageURL().length()>0)
        {
            Picasso.get().load(thisSpacecraft.getImageURL()).placeholder(R.drawable.pic).into(spacecraftImageView);
        }else {
            Toast.makeText(context, "Empty Image URL", Toast.LENGTH_LONG).show();
            Picasso.get().load(R.drawable.pic).into(spacecraftImageView);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //  Toast.makeText(context, "This : " + thisSpacecraft.getName(), Toast.LENGTH_SHORT).show();

                //  Toast.makeText(context, "This : " + thisSpacecraft.getImageURL(), Toast.LENGTH_SHORT).show();

                Intent myIntent = new Intent(Main3Activity.this, Main4Activity.class);

                myIntent.putExtra("Name", thisSpacecraft.getName());
                myIntent.putExtra("Uri", thisSpacecraft.getImageURL());

                myIntent.putExtra("Mobile", thisSpacecraft.getMobile());
                myIntent.putExtra("Lvl", thisSpacecraft.getlvl());

                myIntent.putExtra("Description", thisSpacecraft.getDescription());

                myIntent.putExtra("About", thisSpacecraft.getAbout());

                myIntent.putExtra("Verify", thisSpacecraft.getVerify());

                myIntent.putExtra("User_ID", thisSpacecraft.getId());

                myIntent.putExtra("Username", thisSpacecraft.getusername());

                myIntent.putExtra("Password", thisSpacecraft.getpassword());

                myIntent.putExtra("Username_me", Username_me);

                startActivity(myIntent);

                update();
            }
        });

        return view;
    }
}

  private ListViewAdapter adapter;
private ListView mListView;
ProgressBar myProgressBar;
private int mImageResource;

private void populateListView(List<Spacecraft> spacecraftList) {
    mListView = findViewById(R.id.mListView);

    adapter = new ListViewAdapter(this,spacecraftList);
    mListView.setAdapter(adapter);
}

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

           final ProgressBar myProgressBar= findViewById(R.id.myProgressBar);
    myProgressBar.setIndeterminate(true);
    myProgressBar.setVisibility(View.VISIBLE);

    /*Create handle for the RetrofitInstance interface*/
    MyAPIService myAPIService = RetrofitClientInstance.getRetrofitInstance().create(MyAPIService.class);

    Call<List<Spacecraft>> call = myAPIService.getSpacecrafts();
    call.enqueue(new Callback<List<Spacecraft>>() {

           @Override
        public void onResponse(Call<List<Spacecraft>> call, Response<List<Spacecraft>> response) {
            myProgressBar.setVisibility(View.GONE);
            populateListView(response.body());
        }
        @Override
        public void onFailure(Call<List<Spacecraft>> call, Throwable throwable) {
            myProgressBar.setVisibility(View.GONE);
            //  Toast.makeText(Main3Activity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
            Toast.makeText(Main3Activity.this, "Check Your Internet Connection", Toast.LENGTH_LONG).show();
        }
    });
}

}
</code>```

答:
```<code>if(thisSpacecraft.getId().equals("2")){

}
</code>```

or

```<code>List<Spacecrafts> list = new ArrayList<>();
    if(list.get(position).getId().equals(2)) //check if the list contains the element
         {
          list.get(list.indexOf(position)); //get the element by passing the index of the element
         }
</code>```

Body:
Trying to get second user data only

which have id :2 (whole his data)

Problem is when I get data, it show all users, not only second.

I heard about I can get it using Arraylist, but cant figure out how to make it.

mListView.get(position).get(Mykey);

is there anyway to get specific user data, not show all users data, I'm new in android

users.json

[
{
"id": "1",
"name": "tester1",
"username": "user1",
"verify": "1",
"about": "tesst",
"description": "description....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
},
{
"id": "2",
"name": "tester2",
"username": "user2",
"verify": "0",
"about": "tesst",
"description": "description ....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
},
{
"id": "3",
"name": "tester3",
"username": "user3",
"verify": "0",
"about": "tesst",
"description": "description ....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
}
]

ActivityMain

class Spacecraft {
    /*
    INSTANCE FIELDS
     */
    @SerializedName("id")
    private String id;

    @SerializedName("name")
    private String name;

    @SerializedName("username")
    private String username;

    @SerializedName("password")
    private String password;

    @SerializedName("about")
    private String about;

    @SerializedName("description")
    private String description;

    @SerializedName("mobile")
    private String mobile;

    @SerializedName("lvl")
    private String lvl;

    @SerializedName("imageurl")
    private String imageURL;

    @SerializedName("technologyexists")
    private int technologyexists;

    @SerializedName("verify")
    private String verify;
    ////////

    public Spacecraft(String id, String name, String username,String password, String about, String description,  String mobile, String lvl, String imageURL, int technologyexists, String verify) {

        this.id = id;
        this.name = name;

        this.username = username;
        this.password = password;

        this.about = about;
        this.description = description;

        this.mobile = mobile;
        this.lvl = lvl;

        this.imageURL = imageURL;
        this.technologyexists = technologyexists;

        this.verify = verify;

    }

    /*
     *GETTERS AND SETTERS
     */
    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getusername() {
        return username;
    }

    public String getpassword() {
        return password;
    }

    public String getAbout() {
        return about;
    }

    public String getImageURL() {
        return imageURL;
    }

    public String getMobile() {
        return mobile;
    }

    public String getlvl() {
        return lvl;
    }

    public String getDescription() {
        return description;
    }

    public String getVerify() {
        return verify;
    }

    public int getTechnologyExists() {
        return technologyexists;
    }

    /*
    TOSTRING
     */
    @Override
    public String toString() {
        return name;
    }
}

 interface MyAPIService {

    @GET("/users.json")
    Call<List<Spacecraft>> getSpacecrafts();
}

    static class RetrofitClientInstance {

    private static Retrofit retrofit;
    private static final String BASE_URL = "http://Server_ip_to_get_json_file:80/";

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

    class ListViewAdapter extends BaseAdapter{

    private List<Spacecraft> spacecrafts;
    private Context context;

    public ListViewAdapter(Context context,List<Spacecraft> spacecrafts){
        this.context = context;
        this.spacecrafts = spacecrafts;
    }

    @Override
    public int getCount() {
        return spacecrafts.size();
    }

    @Override
    public Object getItem(int pos) {
        return spacecrafts.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view=LayoutInflater.from(context).inflate(R.layout.model,viewGroup,false);
        }

        TextView nameTxt = view.findViewById(R.id.nameTextView);
        TextView txtPropellant = view.findViewById(R.id.propellantTextView);
        CheckBox chkTechExists = view.findViewById(R.id.myCheckBox);
        ImageView spacecraftImageView = view.findViewById(R.id.spacecraftImageView);

        final Spacecraft thisSpacecraft= spacecrafts.get(position);

        nameTxt.setText(thisSpacecraft.getName());
        //  txtPropellant.setText("Lvl : "+thisSpacecraft.getPropellant());
        txtPropellant.setText("Lvl : "+thisSpacecraft.getlvl());
        chkTechExists.setChecked( thisSpacecraft.getTechnologyExists()==1);
        chkTechExists.setEnabled(false);

        if(thisSpacecraft.getImageURL() != null && thisSpacecraft.getImageURL().length()>0)
        {
            Picasso.get().load(thisSpacecraft.getImageURL()).placeholder(R.drawable.pic).into(spacecraftImageView);
        }else {
            Toast.makeText(context, "Empty Image URL", Toast.LENGTH_LONG).show();
            Picasso.get().load(R.drawable.pic).into(spacecraftImageView);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //  Toast.makeText(context, "This : " + thisSpacecraft.getName(), Toast.LENGTH_SHORT).show();

                //  Toast.makeText(context, "This : " + thisSpacecraft.getImageURL(), Toast.LENGTH_SHORT).show();

                Intent myIntent = new Intent(Main3Activity.this, Main4Activity.class);

                myIntent.putExtra("Name", thisSpacecraft.getName());
                myIntent.putExtra("Uri", thisSpacecraft.getImageURL());

                myIntent.putExtra("Mobile", thisSpacecraft.getMobile());
                myIntent.putExtra("Lvl", thisSpacecraft.getlvl());

                myIntent.putExtra("Description", thisSpacecraft.getDescription());

                myIntent.putExtra("About", thisSpacecraft.getAbout());

                myIntent.putExtra("Verify", thisSpacecraft.getVerify());

                myIntent.putExtra("User_ID", thisSpacecraft.getId());

                myIntent.putExtra("Username", thisSpacecraft.getusername());

                myIntent.putExtra("Password", thisSpacecraft.getpassword());

                myIntent.putExtra("Username_me", Username_me);

                startActivity(myIntent);

                update();
            }
        });

        return view;
    }
}

  private ListViewAdapter adapter;
private ListView mListView;
ProgressBar myProgressBar;
private int mImageResource;

private void populateListView(List<Spacecraft> spacecraftList) {
    mListView = findViewById(R.id.mListView);

    adapter = new ListViewAdapter(this,spacecraftList);
    mListView.setAdapter(adapter);
}

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

           final ProgressBar myProgressBar= findViewById(R.id.myProgressBar);
    myProgressBar.setIndeterminate(true);
    myProgressBar.setVisibility(View.VISIBLE);

    /*Create handle for the RetrofitInstance interface*/
    MyAPIService myAPIService = RetrofitClientInstance.getRetrofitInstance().create(MyAPIService.class);

    Call<List<Spacecraft>> call = myAPIService.getSpacecrafts();
    call.enqueue(new Callback<List<Spacecraft>>() {

           @Override
        public void onResponse(Call<List<Spacecraft>> call, Response<List<Spacecraft>> response) {
            myProgressBar.setVisibility(View.GONE);
            populateListView(response.body());
        }
        @Override
        public void onFailure(Call<List<Spacecraft>> call, Throwable throwable) {
            myProgressBar.setVisibility(View.GONE);
            //  Toast.makeText(Main3Activity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
            Toast.makeText(Main3Activity.this, "Check Your Internet Connection", Toast.LENGTH_LONG).show();
        }
    });
}

}

Body:
if(thisSpacecraft.getId().equals("2")){

}

or

List<Spacecrafts> list = new ArrayList<>();
    if(list.get(position).getId().equals(2)) //check if the list contains the element
         {
          list.get(list.indexOf(position)); //get the element by passing the index of the element
         }


问:
Butterfly pattern appears in random walk using srand(), why?
About 3 years ago I coded a 2D random walk togheter with a coleague in C++, first it seemed to work properly as we obtained a diferent pattern each time. But whenever we decided to increase the number of steps above some threshold an apparent butterfly pattern appeared, we noticed that with each run of the code the pattern would repeat but starting on a different place of the butterfly. We concluded and reported then that it was due to the pseudorandom generator associated with srand() function, but today I found again this report and there are still some things that I would like to understand. I would like to understand better how the pseudorandom generator works in order to obtain this sort of symmetry and ciclic pattern. The pattern I'm talking about is this (The steps are color coded in a rainbow sequence to apreciate the progression of the walk):

EDIT:

I'm adding the code used to obtain this figure:

```<code>#include<iostream>
#include<cmath>
#include<stdlib.h>
#include<time.h>
#include <fstream>
#include <string.h>
#include <string>
#include <iomanip>

using namespace std;

int main ()
{
srand(time(NULL));
int num1,n=250000;

ofstream rnd_coordinates("Random2D.txt");
float x=0,y=0,sumx_f=0,sumy_f=0,sum_d=0,d_m,X,t,d;
float x_m,y_m;

x=0;
y=0;

for(int i=0;i<n;i++){

    t=i;
    num1= rand()%4;

    if(num1==0){
        x++;
    }
    if(num1==1){
        x--;
    }
    if(num1==2){
        y++;
    }
    if(num1==3){
        y--;
    }

    rnd_coordinates<<x<<','<<y<<','<<t<<endl;

}

rnd_coordinates.close();

return 0;
}
</code>```

答:
The code below constitutes a complete compileable example.

Your issue is with dropping bits from the random generator. Lets's see how one could write a source of random bit pairs that doesn't drop bits. It requires that RAND_MAX is of the form 2^n−1, but the idea could be extended to support any RAND_MAX >= 3.

```<code>#include <cassert>
#include <cstdint>
#include <cstdlib>

class RandomBitSource {
    int64_t bits = rand();
    int64_t bitMask = RAND_MAX;
    static_assert((int64_t(RAND_MAX + 1) & RAND_MAX) == 0, "No support for RAND_MAX != 2^(n-1)");
public:
    auto get2Bits() {
        if (!bitMask) // got 0 bits
            bits = rand(), bitMask = RAND_MAX;
        else if (bitMask == 1) // got 1 bit
            bits = (bits * (RAND_MAX+1)) | rand(), bitMask = (RAND_MAX+1) | RAND_MAX;

        assert(bitMask & 3);
        bitMask >>= 2;
        int result = bits & 3;
        bits >>= 2;
        return result;
    }
};
</code>```

Then, the random walk implementation could be as follows. Note that the ' digit separator is a C++14 feature - quite handy.

```<code>#include <vector>

using num_t = int;
struct Coord { num_t x, y; };

struct Walk {
    std::vector<Coord> points;
    num_t min_x = {}, max_x = {}, min_y = {}, max_y = {};
    Walk(size_t n) : points(n) {}
};

auto makeWalk(size_t n = 250'000)
{
    Walk walk { n };
    RandomBitSource src;
    num_t x = 0, y = 0;

    for (auto& point : walk.points)
    {
        const int bits = src.get2Bits(), b0 = bits & 1, b1 = bits >> 1;
        x = x + (((~b0 & ~b1) & 1) - ((b0 & ~b1) & 1));
        y = y + (((~b0 & b1) & 1) - ((b0 & b1) & 1));

        if (x < walk.min_x)
            walk.min_x = x;
        else if (x > walk.max_x)
            walk.max_x = x;
        if (y < walk.min_y)
            walk.min_y = y;
        else if (y > walk.max_y)
            walk.max_y = y;

        point = { x, y };
    }
    return walk;
}
</code>```

With a bit more effort, we can make this into an interactive Qt application. Pressing Return generates a new image.

The image is viewed at the native resolution of the screen it's displayed on, i.e. it maps to physical device pixels. The image is not scaled. Instead, it is rotated when needed to better fit into the screen's orientation (portrait vs landscape). That's for portrait monitor aficionados :)

```<code>#include <QtWidgets>

QImage renderWalk(const Walk& walk, Qt::ScreenOrientation orient)
{
    using std::swap;
    auto width = walk.max_x - walk.min_x + 3;
    auto height = walk.max_y - walk.min_y + 3;
    bool const rotated = (width < height) == (orient == Qt::LandscapeOrientation);
    if (rotated) swap(width, height);
    QImage image(width, height, QPixmap(1, 1).toImage().format());
    image.fill(Qt::black);

    QPainter p(&image);
    if (rotated) {
        p.translate(width, 0);
        p.rotate(90);
    }
    p.translate(-walk.min_x, -walk.min_y);

    auto constexpr hueStep = 1.0/720.0;
    qreal hue = 0;
    int const huePeriod = walk.points.size() * hueStep;
    int i = 0;
    for (auto& point : walk.points) {
        if (!i--) {
            p.setPen(QColor::fromHsvF(hue, 1.0, 1.0, 0.5));
            hue += hueStep;
            i = huePeriod;
        }
        p.drawPoint(point.x, point.y);
    }
    return image;
}

#include <ctime>

int main(int argc, char* argv[])
{
    srand(time(NULL));
    QApplication a(argc, argv);
    QLabel view;
    view.setAlignment(Qt::AlignCenter);
    view.setStyleSheet("QLabel {background-color: black;}");
    view.show();

    auto const refresh = [&view] {
        auto *screen = view.screen();
        auto orientation = screen->orientation();
        auto pixmap = QPixmap::fromImage(renderWalk(makeWalk(), orientation));
        pixmap.setDevicePixelRatio(screen->devicePixelRatio());
        view.setPixmap(pixmap);
        view.resize(view.size().expandedTo(pixmap.size()));
    };
    refresh();
    QShortcut enter(Qt::Key_Return, &view);
    enter.setContext(Qt::ApplicationShortcut);
    QObject::connect(&enter, &QShortcut::activated, &view, refresh);
    return a.exec();
}
</code>```

Body:
About 3 years ago I coded a 2D random walk togheter with a coleague in C++, first it seemed to work properly as we obtained a diferent pattern each time. But whenever we decided to increase the number of steps above some threshold an apparent butterfly pattern appeared, we noticed that with each run of the code the pattern would repeat but starting on a different place of the butterfly. We concluded and reported then that it was due to the pseudorandom generator associated with srand() function, but today I found again this report and there are still some things that I would like to understand. I would like to understand better how the pseudorandom generator works in order to obtain this sort of symmetry and ciclic pattern. The pattern I'm talking about is this (The steps are color coded in a rainbow sequence to apreciate the progression of the walk):

EDIT:

I'm adding the code used to obtain this figure:

#include<iostream>
#include<cmath>
#include<stdlib.h>
#include<time.h>
#include <fstream>
#include <string.h>
#include <string>
#include <iomanip>

using namespace std;

int main ()
{
srand(time(NULL));
int num1,n=250000;

ofstream rnd_coordinates("Random2D.txt");
float x=0,y=0,sumx_f=0,sumy_f=0,sum_d=0,d_m,X,t,d;
float x_m,y_m;

x=0;
y=0;

for(int i=0;i<n;i++){

    t=i;
    num1= rand()%4;

    if(num1==0){
        x++;
    }
    if(num1==1){
        x--;
    }
    if(num1==2){
        y++;
    }
    if(num1==3){
        y--;
    }

    rnd_coordinates<<x<<','<<y<<','<<t<<endl;

}

rnd_coordinates.close();

return 0;
}

Body:
The code below constitutes a complete compileable example.

Your issue is with dropping bits from the random generator. Lets's see how one could write a source of random bit pairs that doesn't drop bits. It requires that RAND_MAX is of the form 2^n−1, but the idea could be extended to support any RAND_MAX >= 3.

#include <cassert>
#include <cstdint>
#include <cstdlib>

class RandomBitSource {
    int64_t bits = rand();
    int64_t bitMask = RAND_MAX;
    static_assert((int64_t(RAND_MAX + 1) & RAND_MAX) == 0, "No support for RAND_MAX != 2^(n-1)");
public:
    auto get2Bits() {
        if (!bitMask) // got 0 bits
            bits = rand(), bitMask = RAND_MAX;
        else if (bitMask == 1) // got 1 bit
            bits = (bits * (RAND_MAX+1)) | rand(), bitMask = (RAND_MAX+1) | RAND_MAX;

        assert(bitMask & 3);
        bitMask >>= 2;
        int result = bits & 3;
        bits >>= 2;
        return result;
    }
};

Then, the random walk implementation could be as follows. Note that the ' digit separator is a C++14 feature - quite handy.

#include <vector>

using num_t = int;
struct Coord { num_t x, y; };

struct Walk {
    std::vector<Coord> points;
    num_t min_x = {}, max_x = {}, min_y = {}, max_y = {};
    Walk(size_t n) : points(n) {}
};

auto makeWalk(size_t n = 250'000)
{
    Walk walk { n };
    RandomBitSource src;
    num_t x = 0, y = 0;

    for (auto& point : walk.points)
    {
        const int bits = src.get2Bits(), b0 = bits & 1, b1 = bits >> 1;
        x = x + (((~b0 & ~b1) & 1) - ((b0 & ~b1) & 1));
        y = y + (((~b0 & b1) & 1) - ((b0 & b1) & 1));

        if (x < walk.min_x)
            walk.min_x = x;
        else if (x > walk.max_x)
            walk.max_x = x;
        if (y < walk.min_y)
            walk.min_y = y;
        else if (y > walk.max_y)
            walk.max_y = y;

        point = { x, y };
    }
    return walk;
}

With a bit more effort, we can make this into an interactive Qt application. Pressing Return generates a new image.

The image is viewed at the native resolution of the screen it's displayed on, i.e. it maps to physical device pixels. The image is not scaled. Instead, it is rotated when needed to better fit into the screen's orientation (portrait vs landscape). That's for portrait monitor aficionados :)

#include <QtWidgets>

QImage renderWalk(const Walk& walk, Qt::ScreenOrientation orient)
{
    using std::swap;
    auto width = walk.max_x - walk.min_x + 3;
    auto height = walk.max_y - walk.min_y + 3;
    bool const rotated = (width < height) == (orient == Qt::LandscapeOrientation);
    if (rotated) swap(width, height);
    QImage image(width, height, QPixmap(1, 1).toImage().format());
    image.fill(Qt::black);

    QPainter p(&image);
    if (rotated) {
        p.translate(width, 0);
        p.rotate(90);
    }
    p.translate(-walk.min_x, -walk.min_y);

    auto constexpr hueStep = 1.0/720.0;
    qreal hue = 0;
    int const huePeriod = walk.points.size() * hueStep;
    int i = 0;
    for (auto& point : walk.points) {
        if (!i--) {
            p.setPen(QColor::fromHsvF(hue, 1.0, 1.0, 0.5));
            hue += hueStep;
            i = huePeriod;
        }
        p.drawPoint(point.x, point.y);
    }
    return image;
}

#include <ctime>

int main(int argc, char* argv[])
{
    srand(time(NULL));
    QApplication a(argc, argv);
    QLabel view;
    view.setAlignment(Qt::AlignCenter);
    view.setStyleSheet("QLabel {background-color: black;}");
    view.show();

    auto const refresh = [&view] {
        auto *screen = view.screen();
        auto orientation = screen->orientation();
        auto pixmap = QPixmap::fromImage(renderWalk(makeWalk(), orientation));
        pixmap.setDevicePixelRatio(screen->devicePixelRatio());
        view.setPixmap(pixmap);
        view.resize(view.size().expandedTo(pixmap.size()));
    };
    refresh();
    QShortcut enter(Qt::Key_Return, &view);
    enter.setContext(Qt::ApplicationShortcut);
    QObject::connect(&enter, &QShortcut::activated, &view, refresh);
    return a.exec();
}