问:
How can I select * WHERE & receive other results connected to the found primary keys?
So I've got the following tables setup:

thread:

id

created_at

thread_users:

id

thread_id -> FK thread

user_id -> FK users (the user who is in the thread)

joined_at

users:

id

name

etc...other relevant details for user

Current functionality: When a user clicks on another user (e.g there FRIEND in the app), it will open the message thread between the 2 users (it should grab the msgs between the 2 users). To determine WHICH thread to use (we need to find the thread_id between the 2 users), we must query the thread_users table using the HTTP_REQUEST_USER (user who sent the GET request) & and the user_id PARAM passed in the http GET request.

Once I do this: select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID

It will return a bunch of threads that the users are in, I then group the returned results using the lodash groupBy method: (which basically MOVES all the results into there corresponding thread objects - E.g 6: [ { user1 }, { user2 } ] - This represents the thread_id 6)

```<code>const groupedThreads = _.groupBy(foundThreadUsers, 'thread_id');
</code>```

From here I loop through each of the found threads (groupedThreads will contain objects THAT contain the arrays of user in each of the threads)

```<code>Object.keys(groupedThreads).forEach((key) => {
      const thr = groupedThreads[key].filter(tu => tu.user_id === currentUserId || tu.user_id === userId);
      console.log(thr, 'FOUND THREAD inside loop after filter');
      /**
       * @TODO add something here which will take into account pluralbot
       */
      if (thr.length === 2) {
        foundThread = thr[0];
      }
    });
</code>```

However, this bit of logic doesn't work:

```<code>if (thr.length === 2) {
   foundThread = thr[0];
}
</code>```

Because the select * from ... (query listed above ^^), only returns the thread_users that match the user ids passed into the where user_id = x OR user_id = y.

I want to be able to select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID BUT also return the other users WHO match the found thread_users.thread_id. Is this possible? Or is there another way I could find the thread between the 2 users?

答:
This will get you the answer you're looking for:</p>

```<code>SELECT DISTINCT  -- Use DISTINCT to avoid getting duplicates for inverse pairing
  T.id
FROM thread T
  INNER JOIN thread_users U1
    ON T.id = U1.thread_id
  INNER JOIN thread_users U2
    ON T.id = U2.thread_id
WHERE U1.user_id = @FirstUserID
  AND U2.user_id = @SecondUserID
</code>```

Body:
So I've got the following tables setup:

thread:

id

created_at

thread_users:

id

thread_id -> FK thread

user_id -> FK users (the user who is in the thread)

joined_at

users:

id

name

etc...other relevant details for user

Current functionality: When a user clicks on another user (e.g there FRIEND in the app), it will open the message thread between the 2 users (it should grab the msgs between the 2 users). To determine WHICH thread to use (we need to find the thread_id between the 2 users), we must query the thread_users table using the HTTP_REQUEST_USER (user who sent the GET request) & and the user_id PARAM passed in the http GET request.

Once I do this: select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID

It will return a bunch of threads that the users are in, I then group the returned results using the lodash groupBy method: (which basically MOVES all the results into there corresponding thread objects - E.g 6: [ { user1 }, { user2 } ] - This represents the thread_id 6)

const groupedThreads = _.groupBy(foundThreadUsers, 'thread_id');

From here I loop through each of the found threads (groupedThreads will contain objects THAT contain the arrays of user in each of the threads)

Object.keys(groupedThreads).forEach((key) => {
      const thr = groupedThreads[key].filter(tu => tu.user_id === currentUserId || tu.user_id === userId);
      console.log(thr, 'FOUND THREAD inside loop after filter');
      /**
       * @TODO add something here which will take into account pluralbot
       */
      if (thr.length === 2) {
        foundThread = thr[0];
      }
    });

However, this bit of logic doesn't work:

if (thr.length === 2) {
   foundThread = thr[0];
}

Because the select * from ... (query listed above ^^), only returns the thread_users that match the user ids passed into the where user_id = x OR user_id = y.

I want to be able to select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID BUT also return the other users WHO match the found thread_users.thread_id. Is this possible? Or is there another way I could find the thread between the 2 users?

Body:
This will get you the answer you're looking for:

SELECT DISTINCT  -- Use DISTINCT to avoid getting duplicates for inverse pairing
  T.id
FROM thread T
  INNER JOIN thread_users U1
    ON T.id = U1.thread_id
  INNER JOIN thread_users U2
    ON T.id = U2.thread_id
WHERE U1.user_id = @FirstUserID
  AND U2.user_id = @SecondUserID


来源: stackexchange

问:
Value of vuex getter not updating when switching between routed components
I have a vuex getter that takes the value of an array from my state.

```<code>import Vue from 'vue'
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        tableRow: [
            {
                "name": 1,
                "numSongs": 2,
                "Year": 3
            }
        ]
    },
    getters:{
        tRow : state => {
            return state.tableRow
        }
    }
});
</code>```

I have a function that takes the values from a table row and sets the value of it to my computed property for the getter.

```<code>       $("#table1 tr").click(function () {
            var list = [];

            var $row = $(this).closest("tr"),
                $tds = $row.find("td");

            list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() });
            // self.$store.state.tableRow = list;
            this.tabRow = list;
            console.log(this.tabRow);
             self.passData();
        });
    });
},

computed: {
    tabRow(){
     return this.$store.getters.tRow;
    }
},
</code>```

Then in another one of my routed components i set the same computed property and then try to call it in the template but the value it outputs is the default values i gave it.

```<code>mounted: function () {
    var self = this;
    console.log(this.tabRow)
    // self.passedRow = self.$store.state.tableRow;
    self.passedRow = this.tabRow;
    this.startDoughnut(this.$refs.canvas, 'Doughnut');
},
    computed: {
    tabRow(){
     return this.$store.getters.tRow;
    }
</code>```

I am not properly efficient with vuex yet so i am not sure why this won't work any help would be appreciated.

答:
What you are trying to do here is not possible in vue compute property and also in Vuex. Computed properties and vuex getters areread only.

```<code> this.tabRow = list;
======================
 computed: {
    tabRow(){
     return this.$store.getters.tRow;
    }
</code>```

Do this

```<code>computed: {
  tabRow(){
    get: function () {
      return this.$store.getters.tRow;
    },
    set: function (newValue) {
      commit('SET_TABLEROW', newValue)
    });
    }
   }
</code>```

In store add a mutation

```<code> mutations:{
        SET_TABLEROW: (state,list) => {
            state.tableRow=list
        }
    }
</code>```

refer https://vuex.vuejs.org/en/mutations.html

ContentLicense: CC BY-SA 3.0

Body:
I have a vuex getter that takes the value of an array from my state.

import Vue from 'vue'
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        tableRow: [
            {
                "name": 1,
                "numSongs": 2,
                "Year": 3
            }
        ]
    },
    getters:{
        tRow : state => {
            return state.tableRow
        }
    }
});

I have a function that takes the values from a table row and sets the value of it to my computed property for the getter.

       $("#table1 tr").click(function () {
            var list = [];

            var $row = $(this).closest("tr"),
                $tds = $row.find("td");

            list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() });
            // self.$store.state.tableRow = list;
            this.tabRow = list;
            console.log(this.tabRow);
             self.passData();
        });
    });
},

computed: {
    tabRow(){
     return this.$store.getters.tRow;
    }
},

Then in another one of my routed components i set the same computed property and then try to call it in the template but the value it outputs is the default values i gave it.

mounted: function () {
    var self = this;
    console.log(this.tabRow)
    // self.passedRow = self.$store.state.tableRow;
    self.passedRow = this.tabRow;
    this.startDoughnut(this.$refs.canvas, 'Doughnut');
},
    computed: {
    tabRow(){
     return this.$store.getters.tRow;
    }

I am not properly efficient with vuex yet so i am not sure why this won't work any help would be appreciated.

Body:
What you are trying to do here is not possible in vue compute property and also in Vuex. Computed properties and vuex getters areread only.

 this.tabRow = list;
======================
 computed: {
    tabRow(){
     return this.$store.getters.tRow;
    }

Do this

computed: {
  tabRow(){
    get: function () {
      return this.$store.getters.tRow;
    },
    set: function (newValue) {
      commit('SET_TABLEROW', newValue)
    });
    }
   }

In store add a mutation

 mutations:{
        SET_TABLEROW: (state,list) => {
            state.tableRow=list
        }
    }

refer https://vuex.vuejs.org/en/mutations.html


问:
Dependency for SMS Retriever API
I am trying to implement SMS Retriever API, but I am unable to find classes like SmsRetrieverClient. I'm not able to import them.

Refer to the following sample code:

```<code> SmsRetrieverClient client = SmsRetriever.getClient(context);
 Task<Void> task = client.startSmsRetriever();
 task.addOnSuccessListener(new OnSuccessListener<Void>() {});
</code>```

I have added following dependency, after which I am able to refer the classes:

```<code>compile 'com.google.android.gms:play-services:11.0.2'
</code>```

But as this include all service API, I want to know the dependency specific to SMS Retriever API

I have referred to this doc for all dependency and added following, but it did not work.

```<code>com.google.android.gms:play-services-auth:11.0.2
com.google.android.gms:play-services-identity:11.0.2
</code>```

Also, is it necessary to have 11.x.x versions?

答:
Do you have error logs that may show the problem? For the meantime, try the old version first from the SMS Retriever document:

The SMS Retriever API is available only on Android devices with Play
  services version 10.2 and newer.

Check this one if the old version imports SmsRetrieverClient successfully.

ContentLicense: CC BY-SA 4.0

Title: Dependency for SMS Retriever API

Body:
I am trying to implement SMS Retriever API, but I am unable to find classes like SmsRetrieverClient. I'm not able to import them.

Refer to the following sample code:

 SmsRetrieverClient client = SmsRetriever.getClient(context);
 Task<Void> task = client.startSmsRetriever();
 task.addOnSuccessListener(new OnSuccessListener<Void>() {});

I have added following dependency, after which I am able to refer the classes:

compile 'com.google.android.gms:play-services:11.0.2'

But as this include all service API, I want to know the dependency specific to SMS Retriever API

I have referred to this doc for all dependency and added following, but it did not work.

com.google.android.gms:play-services-auth:11.0.2
com.google.android.gms:play-services-identity:11.0.2

Also, is it necessary to have 11.x.x versions?


问:
mapr streams with spark streaming compatability
Does mapr streams work with pyspark.I downloaded the necessary jars and tried testing the following example.
https://github.com/ihijazi/data-engineering/blob/master/Kafka-MapR-DB-HBase.py
plz advise what i am missing.</p>

```<code>[mapr@ip-10-0-0-85 centos]$ /opt/mapr/spark/spark-2.1.0/bin/spark-
submit --jars /opt/mapr/spark/spark-2.1.0/jars/spark-streaming_2.10-
2.1.0.jar /home/mapr/kafka.py
Traceback (most recent call last):
File "/home/mapr/kafka.py", line 7, in <module>
from pyspark.streaming.kafka import *;
ImportError: No module named kafka
</code>```

答:
Get inside the spark folder

```<code>cd spark/python/pyspark/streaming
</code>```

Search if u have kafka or kafka08 or kafka09 and change accordingly in your import statement in your code

Body:
Does mapr streams work with pyspark.I downloaded the necessary jars and tried testing the following example.
https://github.com/ihijazi/data-engineering/blob/master/Kafka-MapR-DB-HBase.py
plz advise what i am missing.

[mapr@ip-10-0-0-85 centos]$ /opt/mapr/spark/spark-2.1.0/bin/spark-
submit --jars /opt/mapr/spark/spark-2.1.0/jars/spark-streaming_2.10-
2.1.0.jar /home/mapr/kafka.py
Traceback (most recent call last):
File "/home/mapr/kafka.py", line 7, in <module>
from pyspark.streaming.kafka import *;
ImportError: No module named kafka

Body:
Get inside the spark folder

cd spark/python/pyspark/streaming

Search if u have kafka or kafka08 or kafka09 and change accordingly in your import statement in your code


问:
Updating address bar with new URL without hash or reloading the page
I either dreamt about chrome (dev channel) implementing a way to update the address bar via javascript (the path, not domain) without reloading the page or they really have done this.

However, I can't find the article I think I read.

Am I crazy or is there a way to do this (in Chrome)?

p.s. I'm not talking about window.location.hash, et al. If the above exists the answer to this question will be untrue.

答:
Update to Davids answer to even detect browsers that do not support pushstate:

```<code>if (history.pushState) {
  window.history.pushState(stateObj, "title", "url");
} else {
  window.history.replaceState(stateObj, "title**", 'url');
  // ** It seems that current browsers other than Safari don't support pushState
  // title attribute. We can achieve the same thing by setting it in JS.
  document.title = "Title";
}
</code>```

stateObj

The state object is a JavaScript object which is associated with the history entry passed to the replaceState method. The state object can be null.

title

Most browsers currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state.

url Optional

The URL of the history entry. The new URL must be of the same origin as the current URL; otherwise replaceState throws an exception.

Body:
Update to Davids answer to even detect browsers that do not support pushstate:

if (history.pushState) {
  window.history.pushState(stateObj, "title", "url");
} else {
  window.history.replaceState(stateObj, "title**", 'url');
  // ** It seems that current browsers other than Safari don't support pushState
  // title attribute. We can achieve the same thing by setting it in JS.
  document.title = "Title";
}

stateObj

The state object is a JavaScript object which is associated with the history entry passed to the replaceState method. The state object can be null.

title

Most browsers currently ignore this parameter, although they may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state.

url Optional

The URL of the history entry. The new URL must be of the same origin as the current URL; otherwise replaceState throws an exception.


问:
Replacing byte in file
I'm trying to replace certain bytes from a file with some other specific bytes, but have a problem with my binary writer replacing too many bytes. What is wrong in my code?

```<code>using (BinaryWriter bw =
    new BinaryWriter(File.Open(fileName,
        FileMode.Open)))
{
    bw.BaseStream.Position = 0x3;
    bw.Write(0x50);
}
</code>```

This was supposed to change the letter "E" (hex 0x45) with the letter "P", but instead changes that byte and 3 more bytes; from "45 30 31 FF" to "50 00 00 00". I would like to keep the "30 31 FF", only change "45" to "50".

答:
Basically you don't want or need to use BinaryWriter for this. You're calling BinaryWriter.Write(int) which is behaving exactly as documented.

Just use FileStream to write a single byte:

```<code>using (var stream = File.Open(fileName))
{
    stream.Position = 3;
    stream.WriteByte(0x50);
}
</code>```

Simpler, easier to read (it's obviously only writing a single byte), and does what you want.

Title: Replacing byte in file

Body:
I'm trying to replace certain bytes from a file with some other specific bytes, but have a problem with my binary writer replacing too many bytes. What is wrong in my code?

using (BinaryWriter bw =
    new BinaryWriter(File.Open(fileName,
        FileMode.Open)))
{
    bw.BaseStream.Position = 0x3;
    bw.Write(0x50);
}

This was supposed to change the letter "E" (hex 0x45) with the letter "P", but instead changes that byte and 3 more bytes; from "45 30 31 FF" to "50 00 00 00". I would like to keep the "30 31 FF", only change "45" to "50".

Body:
Basically you don't want or need to use BinaryWriter for this. You're calling BinaryWriter.Write(int) which is behaving exactly as documented.

Just use FileStream to write a single byte:

using (var stream = File.Open(fileName))
{
    stream.Position = 3;
    stream.WriteByte(0x50);
}

Simpler, easier to read (it's obviously only writing a single byte), and does what you want.


问:
Deleting certain rows without a loop
I have a dataframe with car repair data. It also tells me if a car broke down (and got repaired). I would like to get rid of all rows with repair events after the car broke down.

```<code>Car <- c('A','A','B')
Damage <-c("Wheels","Motor","Motor")
date <-c('01-01-2015','01-01-2016','01-01-2016')
Broke_down <-c(1,0,1)

df <- as.data.frame(cbind(Car,date,Damage,Broke_down))
</code>```

Basically, I want to remove all lines that occur for a car after the dummy was 1.

So in this case the output would have to be:

```<code>"Car"        "date"          "Damage"     "Broke_down"
 A           01-01-2015       Wheels         1
 B           01-01-2016       Motor          1
</code>```

Best,
Felix

答:
Here's a solution using split and lapply, data preparation is the same as in the question:

```<code>df2 <- do.call(
  rbind,
  lapply(
    split(df, df$Car),
    function(x){
      x[1:which.min(x$Broke_down==1), ]
    })
)
</code>```

Explanation:

split gives a list of data.frames

lapply applies the function in it's second argument and returns a list of the results

finally do.call calls rbind with the resulting list of data.frames giving you one long data.frame again.

There are similar but faster solutions using data.table and dplyr.

Title: Deleting certain rows without a loop

Body:
I have a dataframe with car repair data. It also tells me if a car broke down (and got repaired). I would like to get rid of all rows with repair events after the car broke down.

Car <- c('A','A','B')
Damage <-c("Wheels","Motor","Motor")
date <-c('01-01-2015','01-01-2016','01-01-2016')
Broke_down <-c(1,0,1)

df <- as.data.frame(cbind(Car,date,Damage,Broke_down))

Basically, I want to remove all lines that occur for a car after the dummy was 1.

So in this case the output would have to be:

"Car"        "date"          "Damage"     "Broke_down"
 A           01-01-2015       Wheels         1
 B           01-01-2016       Motor          1

Best,
Felix

Body:
Here's a solution using split and lapply, data preparation is the same as in the question:

df2 <- do.call(
  rbind,
  lapply(
    split(df, df$Car),
    function(x){
      x[1:which.min(x$Broke_down==1), ]
    })
)

Explanation:

split gives a list of data.frames

lapply applies the function in it's second argument and returns a list of the results

finally do.call calls rbind with the resulting list of data.frames giving you one long data.frame again.

There are similar but faster solutions using data.table and dplyr.


问:
how to get USB harddisk physical serial number ,vendor id ,product id
I would like to get USB hard disk serial number ,vendor id ,product id without WMI,I found the

USBSTOR\Disk&Ven_ST932042&Prod___5VJ101RR&Rev_SDM1\222256410122&0

the serial number is 5VJ101RR but it show in the product id which is wrong,
how can i get the correct USB disk vendor id,product id, serial number
My develop environment is visual c++ 2008

thanks

答:
A simple way to get VID and PID would be to load the devices INI file from %WINDOWS%\System32, I think that is where the INIs are usually copied.  If you know the name of the INI file then it is trivial.  If you are looking for a programmatic method, you can enumerate the USB bus using the Win32 Setup API.

If you have installed the Wnidows Driver Kit on your machine, take a look at the USBVIEW sample application.  It demonstrates how you can enumerate the USB bus and get a list of all devices including their PID and VID.

To get the serial number, look at the GetVolumeInformation() system call.

ContentLicense: CC BY-SA 2.5


问:
Is it possible to turn text to speech using the Google assistant SDK?
Is it possible that after doing processing, I can turn a certain text result to speech using the SDK. Or say turn an alarm or warning message to speech eg. "You have left the gas on" .etc.</p>

答:
It sounds like you're looking for something that will do text-to-speech (TTS) generation.

While TTS is a component of the Assistant SDK, it is designed to do much more than this. The Assistant SDK also does speech-to-text (STT) to parse what the person is saying and provides a way to access the Google Assistant and Actions through this interface. So while it would be useful to help build a smoke detector that could also provide information about fire prevention if you ask it - it really isn't good at just providing audio output.

You have two options:

You can pre-record the audio. You've already suggested you want to do this for other sounds, so this is a logical next step. This is probably most reasonable for a safety system, since it would require minimal network interaction and won't have any latency.

You can use a Cloud API that is dedicated to TTS generation, such as Amazon Polly

Update To be more clear:

The Assistant SDK is meant to provide access to the Google Assistant. STT and TTS are side-effects and there is no direct access to these components in the current release (Developer Preview 1).

Right now, you must send all commands to the SDK via audio. There is no way to send a text command. So while in theory you can create an Action that receives a command and says something in reply - the command you send must be an audio stream. Since it makes more sense to just record the audio you want to play out in the first place, this isn't very useful in your application.

In the future, it might be possible to send text commands and get audio reply, and if/when such a thing exists, it is more feasible to cobble together a TTS system using the Assistant SDK and an Action. But this would be a pretty hackish way to do it.

There also doesn't appear to be a way to do TTS through other Google Cloud APIs (although there are web and Android libraries to do so - these don't really help you on your smoke detector). It looks like there used to be a way to use Google Translate to do this, but that feature seems to have been removed.


问:
Why after the use "free()" the value of the memory adress is always 0?
I have this code:

```<code>int * m = (int *)malloc(sizeof(int));
printf("%p %i\n", m, *m);
(*m) = 6;
printf("%p %i\n", m, *m);
free(m);
printf("%p %i\n", m, *m);
</code>```

I run it on Linux. Why the value of the memory address is always 0?

Why if I run it on Windows this value changes?

答:
After calling free(), the pointer itself contains the old address to memory which is now possibly invalid. The pointed-at value has an indeterminate value, which could be anything. Reading it can result in a crash, a random garbage value or some manner of seemingly deterministic value - what will happen is not well-defined.

You can't know what will happen and there are no guarantees. Therefore, pondering why you get a certain value when you do this is meaningless practice, even for learning purposes. You shouldn't access that memory, simple as that.

Body:
I have this code:

int * m = (int *)malloc(sizeof(int));
printf("%p %i\n", m, *m);
(*m) = 6;
printf("%p %i\n", m, *m);
free(m);
printf("%p %i\n", m, *m);

I run it on Linux. Why the value of the memory address is always 0?

Why if I run it on Windows this value changes?


问:
Universal library for C++ strings
Please recommend me universal library for C++ strings. I want to manipulate ascii text and unicode text in one build without making two versions of builds for std::string/char and for std::wstring/wchar; Also I want to convert them to each other (where it is possible);

Thank you very much!!!

答: Just use std::wstring, then. ASCII is a perfect subset of Unicode (and ISO 8859-1 Latin-1 sits in the middle). ASCII 0x5D is U+005D etcetera.

Title: Universal library for C++ strings


问:
cannot reslove symbol 'android'
I have written this code in my MapsActivity.java
In code android appears in red color and shows cannot resolve symbol 'android'.</p>

```<code>import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
</code>```

答:
Try this, may be helpful.

1.) Choose File option from menu on left top side of android studio.

2.) Select the option : "Invalidate Cache/ Restart.." It will open an dialog.

3.) Click on the first button with option : "Invalidate and Restart"

4.) It will close the studio and restart it. Start indexing of the project.

It resolved my problem:

File -> Invalidate Cache/ Restart -> Invalidate and Restart

Title: cannot reslove symbol 'android'

Body:
I have written this code in my MapsActivity.java
In code android appears in red color and shows cannot resolve symbol 'android'.

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;


问:
Cannot find stackview in accessibility indicator in XCUITest
I'm writing UI test cases for my view controller.it has three views

1.A header view ->Stackview -> 4 buttons

2.table View

3.footer view - > 5 buttons

All views are accessible except stackview and its child buttons

Can anyone guide me how do i get reference of stackview and its child elements?

答:
Set the header view and stack view to be inaccessible and the child elements to be accessible. You can do this using the UIAccessibility API, setting isAccessibilityElement to false for the containers. On the views you want to interact with, set isAccessibilityElement to true and also set accessibilityIdentifier on each view.

If a container view is accessible, its child views are often obscured to avoid confusion about what the user is trying to interact with.


问:
Validating HTTP response in swagger
Is it possible to validate an HTTP response in swagger editor and/or swagger ui? I need to check that a particular response has exactly the structure and data i want.
For example the body has to be {"message":"pong"}.</p>

答:
Swagger Editor and Swagger UI do not validate API responses against the schema. The corresponding feature request was marked as "nice to have" but "out of scope for the project for now".

However, since these projects are open source, you could implement this feature yourself and submit a pull request.

Title: Validating HTTP response in swagger


问:
Why does: string st = "" + 12; work in c# without conversion?
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

```<code> string st = "" + 12;
</code>```

this doesn't (of course):

```<code> string st = 12;
</code>```

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?

答:
It's because the compiler translates the addition to a call to String.Concat().

Internally, all operands are boxed (if necessary) and passed to the String.Concat method (which of course calls ToString() on all arguments).

Body:
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

 string st = "" + 12;

this doesn't (of course):

 string st = 12;

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?


问:
Opening a file stored in HDFS to edit in VI
I would like to edit a text file directly in HDFS using VI without having to copy it to local, edit it and then copy it back from local. Is this possible?

Edit: This used to be possible in Cloudera's Hue UI but is no longer the case.

答:
A simple way is to copy from and to hdfs, and edit locally (See here)

```<code>hvim <filename>
</code>```

Source code of hvim

```<code>hadoop fs -text $1>hvim.txt
vim hvim.txt
hadoop fs -rm -skipTrash $1
hadoop fs -copyFromLocal hvim.txt $1
rm hvim.txt
</code>```

Body:
A simple way is to copy from and to hdfs, and edit locally (See here)

hvim <filename>

Source code of hvim

hadoop fs -text $1>hvim.txt
vim hvim.txt
hadoop fs -rm -skipTrash $1
hadoop fs -copyFromLocal hvim.txt $1
rm hvim.txt


问:
Fullscreen image preview doesn't resize vertically
I've created a simple system to preview images on my website. The preview opens in a fullscreen view but the image should resize both horizontally and vertically. It does resize horizontally but it fails completely when I am trying to resize it vertically.

Here's the fiddle:

Fiddle

I'd appreciate some help with this. Vertical resizing seems to work when I give fullscreenImageContainer 100% height. The problem is that then the close button won't be located at the top right of the image.

答:
You may use vh and vw size property for your image(.descCoverFullscreen .fullscreenImageContainer img), vh stands for viewport height and vw stand for viewport width.

.descCoverFullscreen {
    cursor: pointer;
    position: fixed;
    z-index: 9999;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
    background-color: black;
}

.descCoverFullscreen .fullscreenImageContainer {
    max-width: 100%;
    max-height: 100%;
    position: relative;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    display: inline-block;
}

.descCoverFullscreen .fullscreenImageContainer img {
    height: 100vh;
    width: 100vw;
    max-width: 100%;
    max-height: 100%;
    position: relative;
    -webkit-transform: translate(0, 0);
    -moz-transform: translate(0, 0);
    -ms-transform: translate(0, 0);
    -o-transform: translate(0, 0);
    transform: translate(0, 0);
    top: auto;
    left: auto;
}

.descCoverFullscreen .fullscreenImageContainer button.close {
    position: absolute;
    top: 3px;
    right: 3px;
    left: auto;
    bottom: auto;
}

.remove-icon {
    width: 15px;
    height: 15px;
    stroke: #fff !important;
    stroke-width: 2;
    cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="descCoverFullscreen">
  <div class="fullscreenImageContainer">
    <img src="http://hdqwalls.com/wallpapers/think-twice-code-once.jpg">
    <button type="button" class="close" aria-hidden="true">
      <svg class="remove-icon" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
        <g transform="translate(0,-1036.3622)">
          <path d="m 2,1050.3622 12,-12"></path>
          <path d="m 2,1038.3622 12,12"></path>
        </g>
      </svg>
    </button>
  </div>
</div></code>```

Body:
You may use vh and vw size property for your image(.descCoverFullscreen .fullscreenImageContainer img), vh stands for viewport height and vw stand for viewport width.

.descCoverFullscreen {
    cursor: pointer;
    position: fixed;
    z-index: 9999;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
    background-color: black;
}

.descCoverFullscreen .fullscreenImageContainer {
    max-width: 100%;
    max-height: 100%;
    position: relative;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    display: inline-block;
}

.descCoverFullscreen .fullscreenImageContainer img {
    height: 100vh;
    width: 100vw;
    max-width: 100%;
    max-height: 100%;
    position: relative;
    -webkit-transform: translate(0, 0);
    -moz-transform: translate(0, 0);
    -ms-transform: translate(0, 0);
    -o-transform: translate(0, 0);
    transform: translate(0, 0);
    top: auto;
    left: auto;
}

.descCoverFullscreen .fullscreenImageContainer button.close {
    position: absolute;
    top: 3px;
    right: 3px;
    left: auto;
    bottom: auto;
}

.remove-icon {
    width: 15px;
    height: 15px;
    stroke: #fff !important;
    stroke-width: 2;
    cursor: pointer;
}

<div class="descCoverFullscreen">
  <div class="fullscreenImageContainer">
    <img src="http://hdqwalls.com/wallpapers/think-twice-code-once.jpg">
    <button type="button" class="close" aria-hidden="true">
      <svg class="remove-icon" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
        <g transform="translate(0,-1036.3622)">
          <path d="m 2,1050.3622 12,-12"></path>
          <path d="m 2,1038.3622 12,12"></path>
        </g>
      </svg>
    </button>
  </div>
</div>


答:
I have a function that takes the values from a table row and sets the value of it to my computed property for the getter.
Examining your second block of code:

You are trying to set the value of list to the computed property tabRow. Computed properties are by default getter-only, i.e we can only get or acess a value not set a value.

As far as I understood your problem you want to take the value from the table row and add it to the tableRow property in your vuex state. For that you need a mutation

```<code>$("#table1 tr").click(function () {

    var $row = $(this).closest("tr"),
    $tds = $row.find("td");

    var list = { name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() };
    self.$store.commit('addTableRow', list);
    self.passData();
});

</code>```

In you vuex store add the mutation

```<code>import Vue from 'vue'
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        tableRow: [
            {
                "name": 1,
                "numSongs": 2,
                "Year": 3
            }
        ]
    },
    getters:{
        tRow : state => {
            return state.tableRow
        }
    },
    mutations: {
        addTableRow: (state, list) => {
            state.tableRow.push(list);
        }
    }
});
</code>```

Title: Value of vuex getter not updating when switching between routed components

Body:
I have a function that takes the values from a table row and sets the value of it to my computed property for the getter.
Examining your second block of code:

You are trying to set the value of list to the computed property tabRow. Computed properties are by default getter-only, i.e we can only get or acess a value not set a value.

As far as I understood your problem you want to take the value from the table row and add it to the tableRow property in your vuex state. For that you need a mutation

$("#table1 tr").click(function () {

    var $row = $(this).closest("tr"),
    $tds = $row.find("td");

    var list = { name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() };
    self.$store.commit('addTableRow', list);
    self.passData();
});

In you vuex store add the mutation

import Vue from 'vue'
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: {
        tableRow: [
            {
                "name": 1,
                "numSongs": 2,
                "Year": 3
            }
        ]
    },
    getters:{
        tRow : state => {
            return state.tableRow
        }
    },
    mutations: {
        addTableRow: (state, list) => {
            state.tableRow.push(list);
        }
    }
});


问:
Should I prefer one general signal instead of multiple specific ones?
When the user creates a product, multiple actions have to be done in save() method before calling super(Product,self).save(*args,**kwargs).

I'm not sure if I should use just one pre_save signal to do all these actions or it is better to create a signal for each of these actions separately.

Simple example (I'm going to replace save overrides by signals):

```<code>class Product(..):
    def save(...):
        if not self.pk:
            if not self.category:
                self.category = Category.get_default()
            if not self.brand:
                self.brand = 'NA'
        super(Product,self).save(*args,**kwargs)
        ...
</code>```

SO

```<code>@receiver(pre_save,sender=Product)
def set_attrs(instance,**kwargs):
    if kwargs['created']:
        instance.category = Category.get_default()
        instance.brand = 'NA'
</code>```

OR

```<code>@receiver(pre_save,sender=Product)
def set_category(instance,**kwargs):
    if kwargs['created']:
        instance.category = Category.get_default()

@receiver(pre_save,sender=Product)
def set_brand(instance,**kwargs):
    if kwargs['created']:
        instance.brand = 'NA'
</code>```

This is just simple example. In this case, the general set_attrs should be probably enough but there are more complex situations with different actions like creating userprofile for user and then userplan etc.

Is there some best practice advice for this? Your opinions?

答:
To put the facts out simply, it could be pointed out as a single piece of advice,

If action on one model's instance affects another model, signals are the cleanest way to go about. This is an example where you can go with a signal, because you might want to avoid some_model.save() call from within the save() method of another_model, if you know what I mean.

To elaborate on an example, when overriding save() methods, common task is to create slugs from some fields in the model. If you are required to implement this process on multiple models, then using a pre_save signal would be a benefit, rather than hard-coding in save() method of each models.

Also, on bulk operations, these signals and methods are not necessarily called.

From the docs,

Overridden model methods are not called on bulk operations

Note that the delete() method for an object is not necessarily called when deleting objects in bulk using a QuerySet or as a result of a cascading delete. To ensure customized delete logic gets executed, you can use pre_delete and/or post_delete signals.

Unfortunately, there isn’t a workaround when creating or updating objects in bulk, since none of save(), pre_save, and post_save are called.

For more reference,

Django override save() or signals?

Overriding predefined model methods

Django: signal or model method?

Body:
When the user creates a product, multiple actions have to be done in save() method before calling super(Product,self).save(*args,**kwargs).

I'm not sure if I should use just one pre_save signal to do all these actions or it is better to create a signal for each of these actions separately.

Simple example (I'm going to replace save overrides by signals):

class Product(..):
    def save(...):
        if not self.pk:
            if not self.category:
                self.category = Category.get_default()
            if not self.brand:
                self.brand = 'NA'
        super(Product,self).save(*args,**kwargs)
        ...

SO

@receiver(pre_save,sender=Product)
def set_attrs(instance,**kwargs):
    if kwargs['created']:
        instance.category = Category.get_default()
        instance.brand = 'NA'

OR

@receiver(pre_save,sender=Product)
def set_category(instance,**kwargs):
    if kwargs['created']:
        instance.category = Category.get_default()

@receiver(pre_save,sender=Product)
def set_brand(instance,**kwargs):
    if kwargs['created']:
        instance.brand = 'NA'

This is just simple example. In this case, the general set_attrs should be probably enough but there are more complex situations with different actions like creating userprofile for user and then userplan etc.

Is there some best practice advice for this? Your opinions?


问:
Entity Framework : Table per Concrete Type and unique IDs across tables
I have a few tables that share only a few navigation properties and an ID.
I think Table per Concrete type inheritance would be interesting here.. (?)
It looks something like this :

Contact (Base, Abstract, not mapped)

- ContactID

- navigation properties to other tables (email, phone, ..)

Person : Contact (mapped to table Person with various properties + ContactID)

- various properties

Company : Contact (mapped to table Company with various properties + ContactID)

- various properties

Now for this to work, the primary key (contactID) should be unique across all tables.
2 options then:

- GUIDs (not a fan)

- an additional DB table generating identities (with just a ContactID field, deriving tables have FK), this would not be mapped in EF.

Is this setup doable ?
Also, what will happen in the ObjectContext ? What kind of temporary key does EF generate before calling SaveChanges ? Will it be unique across objects ?

Thanks for any thoughts.
mike.

答:
(not enough space in the comments section)

I've been running some tests.

The thing is you're OK as long as you ONLY specify the subtype you're querying for (ex. 'Address' in your case).

But if you query for the base type (even if you don't need the subtypes info), ex. only ContactPossibility.ID, the generated SQL will UNION all subtype tables.

So querying your 'trackable' collection of ContactPossibilities can create a performance problem.

I tried to work around this by unmapping the base entity and split the inherited entities to their own table + the common table, basically transforming the TPT into TPC : this worked fine from a conceptual perspective (after a lot of edmx editing).
Until I realized this was stupid... :) Indeed in that case you will always need to Union all underlying tables to query for the common data...

(Though I'm not sure in the case described at the end of this post, didn't pursue to test it)

So I guess, since mostly I will need to query for a specific type (person, company, address, phone,..), it's gonna be OK for now and hoping MS will come with a fix in EF4.5.

So I'll have to be careful when querying, another interesting example :

Let's say you want to select a person and then query for his address, something like (tried to follow your naming) :

var person = from b in context.ContactEntities.OfType-Person-()
                          where b.FirstName.StartsWith("X")
                          select b;

var address = from a in context.ContactPossibilities.OfType-Address-()
                         where **a.ContactEntity == person.FirstOrDefault()**
                         select a;

this will produce a Union between all the tables of the Contact derived entities, and performance issues : generated SQL takes ContactPossibility table and joins to Address on ContactPossibilityID, then joins a union of all Contact derived tables joined with the base Contact table, before finally joining a filtered Person table.

However, consider the following alternative :

var person = from b in context.ContactEntities.OfType-Person-()
                          where b.FirstName.StartsWith("X")

                          select b;

var address = from a in context.ContactPossibilities.OfType-Address-()
                         where **a.ContactID == person.FirstOrDefault().ID**
                         select a;

This will work fine : generated SQL takes ContactPossibility table and joins to Address on ContactPossibilityID, and then joins the filtered Person table.

Mike.

Body:
(not enough space in the comments section)

I've been running some tests.

The thing is you're OK as long as you ONLY specify the subtype you're querying for (ex. 'Address' in your case).

But if you query for the base type (even if you don't need the subtypes info), ex. only ContactPossibility.ID, the generated SQL will UNION all subtype tables.

So querying your 'trackable' collection of ContactPossibilities can create a performance problem.

I tried to work around this by unmapping the base entity and split the inherited entities to their own table + the common table, basically transforming the TPT into TPC : this worked fine from a conceptual perspective (after a lot of edmx editing).
Until I realized this was stupid... :) Indeed in that case you will always need to Union all underlying tables to query for the common data...

(Though I'm not sure in the case described at the end of this post, didn't pursue to test it)

So I guess, since mostly I will need to query for a specific type (person, company, address, phone,..), it's gonna be OK for now and hoping MS will come with a fix in EF4.5.

So I'll have to be careful when querying, another interesting example :

Let's say you want to select a person and then query for his address, something like (tried to follow your naming) :

var person = from b in context.ContactEntities.OfType-Person-()
                          where b.FirstName.StartsWith("X")
                          select b;

var address = from a in context.ContactPossibilities.OfType-Address-()
                         where **a.ContactEntity == person.FirstOrDefault()**
                         select a;

this will produce a Union between all the tables of the Contact derived entities, and performance issues : generated SQL takes ContactPossibility table and joins to Address on ContactPossibilityID, then joins a union of all Contact derived tables joined with the base Contact table, before finally joining a filtered Person table.

However, consider the following alternative :

var person = from b in context.ContactEntities.OfType-Person-()
                          where b.FirstName.StartsWith("X")<BR>
                          select b;

var address = from a in context.ContactPossibilities.OfType-Address-()
                         where **a.ContactID == person.FirstOrDefault().ID**
                         select a;

This will work fine : generated SQL takes ContactPossibility table and joins to Address on ContactPossibilityID, and then joins the filtered Person table.

Mike.


问:
various phone states differentiation
How can I differentiate between incoming and outgoing calls ?.
for both cases, the mobile is in an off-hook state, but for the incoming call it is in the ringing state then goes to the off-hook one,

I tried this code but it's not working effectively, as a ringing variable is always false.
and there is another question how can I get the outgoing call number .. thanks in advance

```<code>public class states extends BroadcastReceiver {
boolean Ringing = false;

public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) {
 Toast.makeText(context, "Ringing", Toast.LENGTH_SHORT).show();
        Ringing = true ;
 }
    else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
        if (Ringing) {
            // do nothing
        }else{
           // do something
}
 else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) {
        Ringing = false ;
    }
}
}
</code>```

these are my permissions

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

  <receiver android:name=".states">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
        </intent-filter>
    </receiver>
</code>```

答:
For differentiation of incoming and outgoing Calls you can use a broadcast Receiver for this :
add <action android:name="android.intent.action.NEW_OUTGOING_CALL" /> in your receiver and process it in your onReceive() method.

```<code><receiver android:name=".IncomingCallReceiver" >
    <intent-filter >
       <action android:name="android.intent.action.PHONE_STATE" />
       <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
    </intent-filter>
</receiver>
</code>```

For getting the outgoing number

```<code>public void onReceive(Context context, Intent intent)
{
    String state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if(state==null)
    {
        //Outgoing call
        String number=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        Log.i("tag","Outgoing number : "+number);
    }
    else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
    {
        //Incoming call
        String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Log.i("tag","Incoming number : "+number);
    }
}
</code>```

Title: various phone states differentiation

Body:
How can I differentiate between incoming and outgoing calls ?.
for both cases, the mobile is in an off-hook state, but for the incoming call it is in the ringing state then goes to the off-hook one,

I tried this code but it's not working effectively, as a ringing variable is always false.
and there is another question how can I get the outgoing call number .. thanks in advance

public class states extends BroadcastReceiver {
boolean Ringing = false;

public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) {
 Toast.makeText(context, "Ringing", Toast.LENGTH_SHORT).show();
        Ringing = true ;
 }
    else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
        if (Ringing) {
            // do nothing
        }else{
           // do something
}
 else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) {
        Ringing = false ;
    }
}
}

these are my permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

  <receiver android:name=".states">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
        </intent-filter>
    </receiver>

Body:
For differentiation of incoming and outgoing Calls you can use a broadcast Receiver for this :
add <action android:name="android.intent.action.NEW_OUTGOING_CALL" /> in your receiver and process it in your onReceive() method.

<receiver android:name=".IncomingCallReceiver" >
    <intent-filter >
       <action android:name="android.intent.action.PHONE_STATE" />
       <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
    </intent-filter>
</receiver>

For getting the outgoing number

public void onReceive(Context context, Intent intent)
{
    String state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if(state==null)
    {
        //Outgoing call
        String number=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        Log.i("tag","Outgoing number : "+number);
    }
    else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
    {
        //Incoming call
        String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Log.i("tag","Incoming number : "+number);
    }
}


问:
Reducibility Etm undecideable
I want to ask about reduction.

In the proof that Etm is undecideable in the definition of M1 is

1.if x!=w,reject

2.if x==w,run M on input w and accept if M does

In many proofs that I meet I see that bold line but i can not understand how can I do it because I do not know if it will stop.

I would be more than happy to know where am i wrong.

Thanks.

答:
Accepting with a Turing Machine means to stop in an accepting configuration. So if you simulate M and it accepts, it will stop and you will be able to notice this.

If M does not stop, this means that it does not accept w. In this case you should not accept either. One way of not accepting is running forever. So if your simulation of M runs forever, this makes you run forever, which is just what you should do.

Thus there is no need for you to know whether M will stop. This does not work the other way.  run M on input w and accept if M rejects would not be possible to compute, because you would need to detect infinite computations and accept their input.

Title: Reducibility Etm undecideable


问:
Prestashop 1.7 local environment and symfony server:run command
Prestashop 1.7+ is based on Symfony.

Symfony local environment debug mode means, that you runs command "php app/console (or bin/console at Symfony v3+) server:run" to start local webserver emulation and to view your project with local browser at localhost address (e.g. 127.0.0.1) without any WAMP, MAMP, XAMPP etc.

Also, local debug mode means, that you use app_dev.php prefix to view site in debug mode (with error and performance reports, profilers and other cool symfony features)

There is also commands in Symfony like "php app/console (or bin/console at Symfony v3+) doctrine:schema:validate)", to validate if Doctrine entities model correlate with Mysql database.

So my questions are:

Is Prestashop 1.7+ support "php app/console (or bin/console at Symfony v3+) server:run"?

Is Prestashop 1.7+ support Symfony app_dev.php debug mode?

Should I use "php app/console (or bin/console at Symfony v3+) doctrine:schema:validate)" to ensure that model and database are correct?

Are there any plans to use Twig instead of Smarty?

Thanks.

答:
Prestashop 1.7 only uses very few symfony components mainly for the backoffice product listing and the modules page.

You cannot use any of the symfony commands as the app/console is not included.
Also even though going through the source files you will find doctrine the doctrine entities are not used anywhere so you cannot validate the schema.

Twig is only used in the backoffice on the 2 pages I mentioned earlier.

All in all you won't really stumble upon any symfony unless you go into the core code and you cannot (easily) include any bundles or use any Symfony commands.


问:
Django forms input restriction
```<code>  tr_id = forms.CharField(required=False, max_length=20,
    widget=forms.TextInput(attrs={
        'class':'filter filter_tr_id',
        'placeholder':'TR ID'
    })
)
</code>```

I would like to restrict this Django input for only numbers and underscore. I've already got a js function which does the job. how I can add onkeyup feature in the input ?

```<code>function number_only(id_tr_id) {
var regex = /[^0-9\._]/g;
id_tr_id.value = id_tr_id.value.replace(regex,"");

}
</code>```

Is there any other way I can restrict the input for numbers and underscore only?

答:
yes, You can add a pattern attribute in input field

tr_id = forms.CharField(required=False, max_length=20,
    widget=forms.TextInput(attrs={
        'class':'filter filter_tr_id',
        'placeholder':'TR ID',
        'pattern':'[0-9_]'
    })
)```

Title: Django forms input restriction

Body:
  tr_id = forms.CharField(required=False, max_length=20,
    widget=forms.TextInput(attrs={
        'class':'filter filter_tr_id',
        'placeholder':'TR ID'
    })
)

I would like to restrict this Django input for only numbers and underscore. I've already got a js function which does the job. how I can add onkeyup feature in the input ?

function number_only(id_tr_id) {
var regex = /[^0-9\._]/g;
id_tr_id.value = id_tr_id.value.replace(regex,"");

}

Is there any other way I can restrict the input for numbers and underscore only?


问:
Rails check if HABTM association is changed
I have a roles table

```<code>select * from roles;

 id |   name
----+----------
  1 | admin
  2 | user
  3 | author
  4 | guest
  5 | manager
</code>```

and another table user_roles

```<code>select * from user_roles;

 role_id | user_id
---------+---------
       3 |       1
       3 |       2
       3 |       3
       4 |       5
       3 |       6
       5 |       7
       5 |       8
       1 |       9
       1 |      11

#role.rb

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, join_table: 'user_roles', class_name: user_class.to_s
end
</code>```

I am trying to do some actions when a user's role is updated say, from guest to author

```<code>#user.rb

class Use < ActiveRecord::Base
  after_update :print_role_updated if: :user_roles_changed?
  .
  .

  private

  def user_roles_changed?
    user_roles.any? { |role| role.changed? }
  end

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end
</code>```

But it is not working as expected (.changed? is checking whether the value in role table is updated ?).

How do I run print_role_updated method whenever user roles get updated to a diffrent one?

edit

I tried Doctor's answer but role_updated? is returning false even though the record is being updated

```<code>class Use < ActiveRecord::Base
  has_many :user_roles
  after_update :print_role_updated if: role_updated?
  .
  .

  private

  def role_updated?
    user_roles.any? {|a| a.changed?}
  end

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end
</code>```

答:
I think the _changed? does only work for attributes not classes.
And since you have a many to many association you can't check on one object.
I would try something in this direction:

```<code>if user_roles.any? {|a| a.changed?}
</code>```

if a user only has a single role (sorry it is not clear from your code) then the following should work, or doesn't it ?

```<code>if user_roles.changed?
</code>```

Update since you specified that a user can have many roles. There should be a few corrections you should consider:

```<code>class Use < ActiveRecord::Base
  has_many :user_roles
  after_update :print_role_updated if: user_roles.any? {|a| a.changed?}
  .
  .

  private

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end
</code>```

Update 2:
As it turns out, changed? is false on newly created objects, so my previous update is not working.

Try to change the changed? to the following:

```<code>user_roles.any? { |a| a.new_record? || a.marked_for_destruction? || a.changed? }
</code>```

To be honest it is a bit a guessing I do here, but can you please try it? I would love to see if that works

Body:
I have a roles table

select * from roles;

 id |   name
----+----------
  1 | admin
  2 | user
  3 | author
  4 | guest
  5 | manager

and another table user_roles

select * from user_roles;

 role_id | user_id
---------+---------
       3 |       1
       3 |       2
       3 |       3
       4 |       5
       3 |       6
       5 |       7
       5 |       8
       1 |       9
       1 |      11

#role.rb

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, join_table: 'user_roles', class_name: user_class.to_s
end

I am trying to do some actions when a user's role is updated say, from guest to author

#user.rb

class Use < ActiveRecord::Base
  after_update :print_role_updated if: :user_roles_changed?
  .
  .

  private

  def user_roles_changed?
    user_roles.any? { |role| role.changed? }
  end

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end

But it is not working as expected (.changed? is checking whether the value in role table is updated ?).

How do I run print_role_updated method whenever user roles get updated to a diffrent one?

edit

I tried Doctor's answer but role_updated? is returning false even though the record is being updated

class Use < ActiveRecord::Base
  has_many :user_roles
  after_update :print_role_updated if: role_updated?
  .
  .

  private

  def role_updated?
    user_roles.any? {|a| a.changed?}
  end

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end

Body:
I think the _changed? does only work for attributes not classes.
And since you have a many to many association you can't check on one object.
I would try something in this direction:

if user_roles.any? {|a| a.changed?}

if a user only has a single role (sorry it is not clear from your code) then the following should work, or doesn't it ?

if user_roles.changed?

Update since you specified that a user can have many roles. There should be a few corrections you should consider:

class Use < ActiveRecord::Base
  has_many :user_roles
  after_update :print_role_updated if: user_roles.any? {|a| a.changed?}
  .
  .

  private

  def print_role_updated
    puts "User role changed from #{old_role} to #{new_role}"
  end
end

Update 2:
As it turns out, changed? is false on newly created objects, so my previous update is not working.

Try to change the changed? to the following:

user_roles.any? { |a| a.new_record? || a.marked_for_destruction? || a.changed? }

To be honest it is a bit a guessing I do here, but can you please try it? I would love to see if that works


问:
What is a postgres superuser
I couldn't find the answer in the docs, what exactly is a superuser in postgres? </p>

<p>Does the superuser have all privileges? Is it per database? Per instance? </p>

答:
Superuser is per database. From manual:

SUPERUSER
 NOSUPERUSER
    These clauses determine whether the new role is a "superuser", who can override all access restrictions within the database. Superuser status is dangerous and should be used only when really needed. You must yourself be a superuser to create a new superuser. If not specified, NOSUPERUSER is the default.

The superuser role bypasses all permission checks.

The term "cluster" in PostgreSQL is a historical and it is un-related to the PostgreSQL command CLUSTER, which is about organizing tables - you set user per-database, not per-cluster. A cluster is created when PostgreSQL is installed. The installation will usually do initdb - it will create a new cluster with one database in for you. Cluster is just data dir with databases inside. For location of that data dir look into manual.

Title: What is a postgres superuser

Body:
I couldn't find the answer in the docs, what exactly is a superuser in postgres?

Does the superuser have all privileges? Is it per database? Per instance?


问:
$http post request doesn't work and sends an "Possible unhandled rejection" error
I am using angular to send a post request to a backend made with Symphony, with data coming from an HTML form. The problem is that it doesn't work at all, and it sends me a possible unhandled rejection error in the browser console. When I use the REST client of my browser it works fine. Here are some pieces of code:

Here is the HTML:

```<code><header>
    <div id="categorymenu">
        <nav class="subnav">
            <a href="#!welcome" class="logo pull-left">
                <img style="height:50%;  /* width: 70%; */ max-width: 100%;" title="Simplepxcreate" alt="Simplepxcreate" src="images/logo.png">
            </a>

            <ul class="nav-pills categorymenu container" style="color: #254F97 !important">
                <li>
                    <a class="{{menActive1}} home" href="#!welcome" style="box-shadow: #CCC 1.5px 1.5px 0px 0px;">
                        <i class="icon-home icon-white font18"></i>
                        <span> Accueil</span>
                    </a>
                </li>
                <li>
                    <a class="{{menActive2}}" href="#!catalogue/all/all" style="box-shadow: #CCC 1.5px 1.5px 0px 0px;">
                        <i class="icon-shopping-cart"></i>
                        Produits
                    </a>
                    <div style="border-radius: 0px; box-shadow: #254F9766 1.5px 1.5px 0px 0px;">
                        <div class="loader" ng-show="loader1" style="margin-left: 50%"></div>
                        <ul >
                            <li ng-repeat="cathegorie in Acccathegories" style="border-bottom: 1px solid; border-bottom-style: dotted;">
                                <a href="#!catalogue/{{cathegorie.category.id}}/all">
                                    <i class="icon-cogs"></i>
                                    {{cathegorie.category.name}}
                                </a>
                            </li>
                        </ul>
                    </div>
                    <!--
                       Debut
                        Ceci n'est pas utilisé voila pour quoi il ne s'affiche pas :
                    -->
                    <div style="display: none; /*width:1000px;*/">
                        <!--
                            <ul>
                                <li class="categorymenu" ng-repeat="cathegorie in finalCathegories"><a href="#!catalogue/{{cathegorie.id}}/all">{{cathegorie.name}}</a>
                                    <ul class="nav-pills" ng.if="cathegorie.subs!='nosubs'">
                                        <li ng-repeat="sub in cathegorie.subs"><a href="#!catalogue/{{cathegorie.id}}/{{sub.id}}">{{sub.name}}</a></li>
                                    </ul>
                                </li>
                            </ul>
                        -->
                        <div class="loader" ng-show="loader1" style="/*margin-left: 50%/*"></div>

                        <div>
                            <ul style="/*margin: 0; padding: 0; list-style: none;*/" style=" /*display: block; width: 1000px;*/">
                                <div style="padding: 15px; border-bottom: dotted;/*float: left; width: 25%; margin-top: 5px; margin-left: 5px;*/ /*float: left; width: 400px; margin-top: 20px; margin-left: 20px;*/" ng-repeat="cathegorie in Acccathegories">
                                    <li style="">
                                        <a href="#!catalogue/{{cathegorie.category.id}}/all" style=" background-color: #254F97; color: #FFF; padding: 5px; /*color: #254F97;*/ text-transform: uppercase; font-size: 14px; " id="mycats"  >
                                            <i class="fa fa-cogs"></i>
                                            <img ng-if="!showSubs" src="images/repair-tools.png"  style="width: 20px; height: 20px; margin-right: 10px; display: none;" >
                                            {{cathegorie.category.name}}
                                        </a>
                                        <ul style="/*margin-left: 30px;*/ ">
                                            <li ng-repeat=" sub in cathegorie.subs">
                                                <a id="mysubs" href="#!catalogue/{{sub.id}}/all">{{sub.name}}<span></span></a>
                                            </li>
                                        </ul>
                                    </li>
                                </div>
                            </ul>
                        </div>
                        <ul>

                        </ul>
                    </div>
                    <!--
                        Fin
                    -->
                </li>
                <li>
                    <a class="{{menActive3}}" href="#!nosservices" style="box-shadow: #CCC 1.5px 1.5px 0px 0px;">
                        <i class="icon-cogs"></i>
                        Services
                    </a>
                </li>

                <li>
                    <a class="{{menActive4}}" href="#!devis/all" style="box-shadow: #CCC 1.5px 1.5px 0px 0px;">
                        <i class="icon-check"></i>
                        Devis
                    </a>
                </li>
                <li>
                    <a class="{{menActive5}}" href="#!contact" style="box-shadow: #CCC 1.5px 1.5px 0px 0px;">
                        <i class="icon-envelope"></i>
                        Nous contacter
                    </a>
                </li>
            </ul>
        </nav>
    </div>
</header>

<div id="maincontainer">

  <section>
    <div class="container">
      <!--  breadcrumb -->
      <ul class="breadcrumb">
        <li>
          <a href="#">Home</a>
          <span class="divider">/</span>
        </li>
        <li class="active">Devis</li>
      </ul>

      <div class="row mt40">
        <div class="span8">
          <h2 class="heading2">
            <span>
              <i class="icon-phone"></i>
              Demandez un devis
            </span>
          </h2>
          <form class="form-vertical contactform"  method="post" name="devis">
            <div class="control-group">
              <label for="name" class="control-label">
                Name
                <span class="required">*</span>
              </label>
              <div class="controls">
                <input type="text"  placeholder="Votre nom et prénom ou celui de votre société" class="required" id="name" value="" name="name" ng-model="devis.nom" style="width: 80%; border-radius: inherit;">
              </div>
            </div>
            <div class="control-group">
              <label for="email" class="control-label">
                Email
                <span class="required">*</span>
              </label>
              <div class="controls">
                <input type="email" placeholder="Votre adresse mail" class="required email" id="email" value="" ng-model="devis.email" style="width: 80%; border-radius: inherit;">
              </div>
            </div>
            <div class="control-group">
              <label for="url" class="control-label">
                Telephone
              </label>
              <div class="controls">
                <input type="text" id="name" placeholder="Votre numéro de téléphone" value="" name="url" ng-model="devis.telephone" style="width: 80%; border-radius: inherit;">
              </div>
            </div>
            <div class="control-group">
              <label for="url" class="control-label">
                Objet
              </label>
              <div class="controls">
                <input type="text" placeholder="Objet de votre devis" id="name" value="" name="url" ng-model="devis.objet" style="width: 80%; border-radius: inherit;">
              </div>
            </div>
            <div class="control-group">
              <label for="url" class="control-label">
                Service :
              </label>
              <div class="controls">
                <select id="select" style="width: 80%; border-radius: inherit;" ng-model="devis.service">
                  <option ng-repeat="service in Accservices" value="{{service.name}}"  ng-selected="choosen.name=service.name">
                    {{service.name}}
                  </option>
                </select>
              </div>
            </div>
            <div class="control-group">
              <label for="message" class="control-label">
                Message
              </label>
              <div class="controls">
                <textarea placeholder="Décrivez votre besoin ici" class="required" rows="6" cols="40" id="message" ng-model="devis.message" style="width: 80%; border-radius: inherit;"></textarea>
              </div>
            </div>

            <div class="form-actions">
              <input class="btn" type="reset" value="Annuler" ng-click="abort()">
              <input class="btn btn-orange pull-right" type="submit" value="Envoyer" id="submit_id" style="margin-right: 20px" ng-click="askDevis(devis)">
            </div>
          </form>
        </div>

        <!-- Sidebar Start-->
        <div class="span4">
          <aside>
            <div class="sidewidt">
              <h2 class="heading2">
                <span>
                  <i class="icon-envelope"></i>
                  Nos coordonnées
                </span>
              </h2>
              <p>
                Horraires:<br>
                Lundi-Vendrdi: 08h-19h<br>
                Samedi: 08h-15h<br>
                <br>
                <i class="icon-phone"></i>
                Phone: (237) 33 40 53 50<br>
                <i class="icon-envelope"></i>
                Email: infos@auto-22.com / client@auto-22.com<br>
                <i class="icon-globe"></i>
                Web: Auto22.com<br>
              </p>
            </div>
          </aside>
        </div>
        <!-- Sidebar End-->
      </div>
    </div>
  </section>
</div>

<!-- Footer -->
<footer id="footer">
    <section class="footersocial">
        <div class="container">
            <div class="row">
                <div class="span3 info">
                    <h2> <i class="icon-link"></i> LA propos </h2>
                   <ul>
                        <li><a href="">Qui sommes-nous</a> </li>
                        <li><a href="">Notre mission</a> </li>
                        <li><a href="">Notre équipe</a> </li>
                    </ul>
                </div>
                <div class="span3 contact">
                    <h2> <i class="icon-phone-sign"></i> Contact </h2>
                    <ul>
                        <li class="location"> Douala, Cameroun.</li>
                        <li class="phone"> Phone: (237) 33 40 53 50</li>
                        <li class="mobile"> Email: infos@auto-22.com / client@auto-22.com</li>
                        <li class="email"> Web: Auto22.com</li>
                    </ul>
                </div>
                <div class="span3 twitter">
                    <h2>  Temoignages </h2>
                    <div class="flexslider" id="testimonialsidebar">
                        <ul class="slides">
                            <li ng-repeat="temoignage in Temoignages">{{temoignage.content}} <br>
                                <span class="pull-right orange">By : {{temoignage.nameby}}</span> </li>

                        </ul>
                    </div>
                </div>
                <div class="span3 facebook">
                    <h2> Newsletter </h2>
                    <section id="newslettersignup">
                        <div class="pull-left mt20">
                            <form class="form-horizontal">
                                <div class="input-prepend">
                                    <input type="text" placeholder="votre mail ici" id="inputIcon" class="span2">
                                    <input value="Souscrire" class="btn btn-orange" type="submit">
                                    Envoyer </div>
                            </form>
                        </div>
                    </section>

                </div>
            </div>
        </div>
    </section>
    <section class="copyrightbottom">
        <div class="container">
            <div class="row">
                <div class="span5 social">
                    <ul>
                        <li><a href="#"><i class="icon-facebook"></i></a></li>
                        <li><a href="#"><i class="icon-twitter"></i></a></li>
                    </ul>
                </div>
                <div class="span2 textcenter"> Auto22 @ 2017 powered by Njangihost </div>
            </div>
        </div>
    </section>
    <a id="gotop" href="#">Back to top</a>
</footer>

<script type="text/javascript" language="javascript">
    $(function () {
        $('#categorymenu').stickThis();
    });
</script>
</code>```

And here is the controller and the service:

```<code>'use strict';
angular.module('Auto22', ['ngRoute', 'ui.bootstrap'])
.config(function($routeProvider){
  $routeProvider
  .when('/welcome', {
    templateUrl : 'views/welcome.html',
    controller: 'welcomeCtrl'
  })
  .when('/catalogue/:name/:subname', {
    templateUrl : 'views/catalogue.html',
    controller: 'catalogueCtrl'
  })
  .when('/services/:servicename', {
    templateUrl : 'views/services.html',
    controller: 'servicesCtrl'
  })
  .when('/nosservices', {
    templateUrl : 'views/nosServices.html',
    controller: 'nosservicesCtrl'
  })
  .when('/produit/:idproduct', {
    templateUrl: 'views/produit.html',
    controller: 'produitCtrl'
  })
  .when('/devis/:servicename', {
    templateUrl: 'views/devis.html',
    controller: 'devisCtrl'
  })
  .when('/contact', {
    templateUrl: 'views/contact.html',
    controller: 'contactCtrl'
  })
  .when('/promotion', {
    templateUrl : 'views/promotion.html',
    controller: 'promotionCtrl'
  })
  .when('/resultats/:produit', {
    templateUrl : 'views/resultats.html',
    controller: 'resultatsCtrl'
  })
  .otherwise({
       redirectTo: '/welcome'
    });
})
.config(function($sceProvider) {
    $sceProvider.enabled(false);
})
.controller('devisCtrl', function($scope, $uibModal, cathegorie, devis, temoignages, subCathegorie, $rootScope, services, $routeParams){
  document.title="Devis";
  $scope.menActive1="";
  $scope.menActive2="";
  $scope.menActive3="";
  $scope.menActive4="active";
  $scope.menActive5="";
  $scope.loader1=true;
  $rootScope.apiAddress2="http://www.auto22industry.com/auto22new/manager/web/api/corporate";
  $rootScope.apiAddress="http://www.auto22industry.com/auto22new/manager/web/api/catalog";
  $rootScope.apiAddress3="http://www.auto22industry.com/auto22new/manager/web/api";
  $scope.choosen={};
  services.listservices().then(function(allServices){
    $scope.Accservices=[];
    $scope.Accservices=allServices.data;
    for(var i=0; i<=$scope.Accservices.length; i++){
      if($routeParams.servicename==$scope.Accservices[i].id){
        $scope.choosen=$scope.Accservices[i];
        break;
      };
    };
    console.log($scope.choosen.name);
  });

  /*List all the cathegories and their subcathegories*/
  subCathegorie.listSubCathegorie().then(function(subcathegories){
    $scope.Acccathegories=[];
    if(subcathegories.data){$scope.loader1=false;}
    $scope.Acccathegories=subcathegories.data;
    console.log($scope.Acccathegories);
  });
  $scope.messages={};

  $scope.askDevis = function(Devis){
    console.log("In the ask devis function");
    /*for(var monService in $scope.Accservices){
      console.log("In the for loop");
      console.log(Devis.service);
      console.log(Devis.nom);
      console.log($scope.Accservices[monService].name);
      if(Devis.service == $scope.Accservices[monService].name){
        $scope.askedService = $scope.Accservices[monService];
        console.log($scope.askedService);
        break;
      };
    };*/

    devis.sendDevisRequest(Devis.nom, Devis.email, Devis.telephone, Devis.objet, Devis.service, Devis.message).then(function(validation){
      $scope.messages=validation;
      console.log($scope.messages);
    });

    if($scope.messages){
      console.log('opening pop up');
      var $uibModalInstance = $uibModal.open({
      templateUrl: 'Popup.html',
      controller: 'PopupCont'
      });
    }else{
      console.log('opening pop up');
      var $uibModalInstance = $uibModal.open({
      templateUrl: 'PopupErr.html',
      controller: 'PopupCont'
      });
    }
  };

  temoignages.listalltemoignages().then(function(allTemoignages){
    $scope.Temoignages=[];
    $scope.Temoignages=allTemoignages.data.data;
  });

})
.controller('PopupCont', function($scope, $uibModalInstance){
  $scope.close = function () {
    $uibModalInstance.dismiss('');
  };
})
.service('devis', function($http, $rootScope){
  var validation={};

  this.sendDevisRequest = function(nom, email, telephone, objet, service, description) {
    var req = {
      method: 'POST',
      url: $rootScope.apiAddress + '/devis/create',
      data: {
        "name": nom,
        "email": email,
        "phone": telephone,
        "object": objet,
        "service": service,
        "description": description
      }
    }

    return $http(req).then(function(response){
      validation=response;
    });
  }
});
</code>```

答:
in the service just return the http instead of catching the promise.Catch it in the controller.

```<code>.service('devis', function($http, $rootScope){
  var validation={};

  this.sendDevisRequest = function(nom, email, telephone, objet, service, description) {
    var req = {
 method: 'POST',
 url: $rootScope.apiAddress + '/devis/create',
 data: {
  "name": nom,
  "email": email,
  "phone": telephone,
  "object": objet,
  "service": service,
  "description": description
  }
}
    return $http(req)
  }
});
</code>```

also data comes under data property in the promise

```<code>devis.sendDevisRequest(Devis.nom, Devis.email, Devis.telephone, Devis.objet, Devis.service, Devis.message).then(function(validation){

    $scope.messages=validation.data; // data property
    console.log($scope.messages);

})
</code>```

Body:
I am using angular to send a post request to a backend made with Symphony, with data coming from an HTML form. The problem is that it doesn't work at all, and it sends me a possible unhandled rejection error in the browser console. When I use the REST client of my browser it works fine. Here are some pieces of code:

Here is the HTML:

                         Accueil

                        Produits

                                    {{cathegorie.category.name}}

                                            {{cathegorie.category.name}}

                                                {{sub.name}}

                        Services

                        Devis

                        Nous contacter

          Home
          /

Devis

              Demandez un devis

          <form class="form-vertical contactform"  method="post" name="devis">

                Name
                *

                <input type="text"  placeholder="Votre nom et prénom ou celui de votre société" class="required" id="name" value="" name="name" ng-model="devis.nom" style="width: 80%; border-radius: inherit;">

                Email
                *

                <input type="email" placeholder="Votre adresse mail" class="required email" id="email" value="" ng-model="devis.email" style="width: 80%; border-radius: inherit;">

                Telephone

                <input type="text" id="name" placeholder="Votre numéro de téléphone" value="" name="url" ng-model="devis.telephone" style="width: 80%; border-radius: inherit;">

                Objet

                <input type="text" placeholder="Objet de votre devis" id="name" value="" name="url" ng-model="devis.objet" style="width: 80%; border-radius: inherit;">

                Service :

                <select id="select" style="width: 80%; border-radius: inherit;" ng-model="devis.service">
                  <option ng-repeat="service in Accservices" value="{{service.name}}"  ng-selected="choosen.name=service.name">
                    {{service.name}}
                  </option>
                </select>

                Message

                <textarea placeholder="Décrivez votre besoin ici" class="required" rows="6" cols="40" id="message" ng-model="devis.message" style="width: 80%; border-radius: inherit;"></textarea>

              <input class="btn" type="reset" value="Annuler" ng-click="abort()">
              <input class="btn btn-orange pull-right" type="submit" value="Envoyer" id="submit_id" style="margin-right: 20px" ng-click="askDevis(devis)">

          </form>

                  Nos coordonnées

                Horraires:

                Lundi-Vendrdi: 08h-19h

                Samedi: 08h-15h

                Phone: (237) 33 40 53 50

                Email: infos@auto-22.com / client@auto-22.com

                Web: Auto22.com

  LA propos

Qui sommes-nous

Notre mission

Notre équipe

  Contact

 Douala, Cameroun.

 Phone: (237) 33 40 53 50

 Email: infos@auto-22.com / client@auto-22.com

 Web: Auto22.com

  Temoignages

{{temoignage.content}}

                                By : {{temoignage.nameby}}

 Newsletter

                            <form class="form-horizontal">

                                    <input type="text" placeholder="votre mail ici" id="inputIcon" class="span2">
                                    <input value="Souscrire" class="btn btn-orange" type="submit">
                                    Envoyer

                            </form>

 Auto22 @ 2017 powered by Njangihost

    Back to top

And here is the controller and the service:

'use strict';
angular.module('Auto22', ['ngRoute', 'ui.bootstrap'])
.config(function($routeProvider){
  $routeProvider
  .when('/welcome', {
    templateUrl : 'views/welcome.html',
    controller: 'welcomeCtrl'
  })
  .when('/catalogue/:name/:subname', {
    templateUrl : 'views/catalogue.html',
    controller: 'catalogueCtrl'
  })
  .when('/services/:servicename', {
    templateUrl : 'views/services.html',
    controller: 'servicesCtrl'
  })
  .when('/nosservices', {
    templateUrl : 'views/nosServices.html',
    controller: 'nosservicesCtrl'
  })
  .when('/produit/:idproduct', {
    templateUrl: 'views/produit.html',
    controller: 'produitCtrl'
  })
  .when('/devis/:servicename', {
    templateUrl: 'views/devis.html',
    controller: 'devisCtrl'
  })
  .when('/contact', {
    templateUrl: 'views/contact.html',
    controller: 'contactCtrl'
  })
  .when('/promotion', {
    templateUrl : 'views/promotion.html',
    controller: 'promotionCtrl'
  })
  .when('/resultats/:produit', {
    templateUrl : 'views/resultats.html',
    controller: 'resultatsCtrl'
  })
  .otherwise({
       redirectTo: '/welcome'
    });
})
.config(function($sceProvider) {
    $sceProvider.enabled(false);
})
.controller('devisCtrl', function($scope, $uibModal, cathegorie, devis, temoignages, subCathegorie, $rootScope, services, $routeParams){
  document.title="Devis";
  $scope.menActive1="";
  $scope.menActive2="";
  $scope.menActive3="";
  $scope.menActive4="active";
  $scope.menActive5="";
  $scope.loader1=true;
  $rootScope.apiAddress2="http://www.auto22industry.com/auto22new/manager/web/api/corporate";
  $rootScope.apiAddress="http://www.auto22industry.com/auto22new/manager/web/api/catalog";
  $rootScope.apiAddress3="http://www.auto22industry.com/auto22new/manager/web/api";
  $scope.choosen={};
  services.listservices().then(function(allServices){
    $scope.Accservices=[];
    $scope.Accservices=allServices.data;
    for(var i=0; i<=$scope.Accservices.length; i++){
      if($routeParams.servicename==$scope.Accservices[i].id){
        $scope.choosen=$scope.Accservices[i];
        break;
      };
    };
    console.log($scope.choosen.name);
  });

  /*List all the cathegories and their subcathegories*/
  subCathegorie.listSubCathegorie().then(function(subcathegories){
    $scope.Acccathegories=[];
    if(subcathegories.data){$scope.loader1=false;}
    $scope.Acccathegories=subcathegories.data;
    console.log($scope.Acccathegories);
  });
  $scope.messages={};

  $scope.askDevis = function(Devis){
    console.log("In the ask devis function");
    /*for(var monService in $scope.Accservices){
      console.log("In the for loop");
      console.log(Devis.service);
      console.log(Devis.nom);
      console.log($scope.Accservices[monService].name);
      if(Devis.service == $scope.Accservices[monService].name){
        $scope.askedService = $scope.Accservices[monService];
        console.log($scope.askedService);
        break;
      };
    };*/

    devis.sendDevisRequest(Devis.nom, Devis.email, Devis.telephone, Devis.objet, Devis.service, Devis.message).then(function(validation){
      $scope.messages=validation;
      console.log($scope.messages);
    });

    if($scope.messages){
      console.log('opening pop up');
      var $uibModalInstance = $uibModal.open({
      templateUrl: 'Popup.html',
      controller: 'PopupCont'
      });
    }else{
      console.log('opening pop up');
      var $uibModalInstance = $uibModal.open({
      templateUrl: 'PopupErr.html',
      controller: 'PopupCont'
      });
    }
  };

  temoignages.listalltemoignages().then(function(allTemoignages){
    $scope.Temoignages=[];
    $scope.Temoignages=allTemoignages.data.data;
  });

})
.controller('PopupCont', function($scope, $uibModalInstance){
  $scope.close = function () {
    $uibModalInstance.dismiss('');
  };
})
.service('devis', function($http, $rootScope){
  var validation={};

  this.sendDevisRequest = function(nom, email, telephone, objet, service, description) {
    var req = {
      method: 'POST',
      url: $rootScope.apiAddress + '/devis/create',
      data: {
        "name": nom,
        "email": email,
        "phone": telephone,
        "object": objet,
        "service": service,
        "description": description
      }
    }

    return $http(req).then(function(response){
      validation=response;
    });
  }
});

Body:
in the service just return the http instead of catching the promise.Catch it in the controller.

.service('devis', function($http, $rootScope){
  var validation={};

  this.sendDevisRequest = function(nom, email, telephone, objet, service, description) {
    var req = {
 method: 'POST',
 url: $rootScope.apiAddress + '/devis/create',
 data: {
  "name": nom,
  "email": email,
  "phone": telephone,
  "object": objet,
  "service": service,
  "description": description
  }
}
    return $http(req)
  }
});

also data comes under data property in the promise

devis.sendDevisRequest(Devis.nom, Devis.email, Devis.telephone, Devis.objet, Devis.service, Devis.message).then(function(validation){

    $scope.messages=validation.data; // data property
    console.log($scope.messages);

})


问:
Is there a way to create an action in eclipse to export my jar to a certain directory?
Is there someone to configure a one click or one key action to export my build product to a certain directory? I'm coming from Visual Studio where I can set the output directory and press F6 to do this.

答: You can right click on project. Export... Then click on Java/Jar file and next. You will se something like this. Specify output filename, and on the next screen click on save description ( see pictures below ). Then after you saved jardesc to the project root, right click and "Create JAR" command. Two click, not one (if you check overwrite in first screen). If you want to automate with a shortcut, try the plugin in this answer.


问:
Changing the Font and font Size in a textarea field
Using the following code sample:

```<code><html>
<body>

<script language = "Javascript">

maxL=240;
var bName = navigator.appName;
function taLimit(taObj) {
 if (taObj.value.length==maxL) return false;
 return true;
}

function taCount(taObj,Cnt) {
 objCnt=createObject(Cnt);
 objVal=taObj.value;
 if (objVal.length>maxL) objVal=objVal.substring(0,maxL);
 if (objCnt) {
  if(bName == "Netscape"){
   objCnt.textContent=maxL-objVal.length;}
  else{objCnt.innerText=maxL-objVal.length;}
 }
 return true;
}
function createObject(objId) {
 if (document.getElementById) return document.getElementById(objId);
 else if (document.layers) return eval("document." + objId);
 else if (document.all) return eval("document.all." + objId);
 else return eval("document." + objId);
}
</script>
<font face="Arial" font size="2">
Maximum Number of characters for this text box is 240.</font><br>

<textarea onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')" name="Message" rows=6 wrap="physical" cols=42>
</textarea>
<br>
<font face="Arial" font size="2">
You have <B><SPAN id=myCounter>240</SPAN></B> characters remaining
for your message</font>

</body>
</html>
</code>```

How do I change the font and font size in the textarea?

答:
Use CSS to define a style for the textarea element. For example:

```<code>textarea {
   font-size: 20pt;
   font-family: Arial;
}
</code>```

Note that there are three ways to add CSS to your website -- you can use an external stylesheet, an internal stylesheet, or inline styles (or a combination thereof).

Using an internal stylesheet might look like this:

```<code><head>
<style type="text/css">
textarea {
   font-size: 20pt;
   font-family: Arial;
}
</style>
</head>

<!-- rest of your code goes here... -->
</code>```

See here for more information on styling textarea.

Body:
Using the following code sample:

Maximum Number of characters for this text box is 240.

<textarea onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')" name="Message" rows=6 wrap="physical" cols=42>
</textarea>

You have 240 characters remaining
for your message

How do I change the font and font size in the textarea?

Body:
Use CSS to define a style for the textarea element. For example:

textarea {
   font-size: 20pt;
   font-family: Arial;
}

Note that there are three ways to add CSS to your website -- you can use an external stylesheet, an internal stylesheet, or inline styles (or a combination thereof).

Using an internal stylesheet might look like this:

<head>
<style type="text/css">
textarea {
   font-size: 20pt;
   font-family: Arial;
}
</style>
</head>

<!-- rest of your code goes here... -->

See here for more information on styling textarea.


问:
2 different ul inside div block and show same lineage column css not effect overflow
I want to list 2 different ul like a table and each list element like a     column lineage. ı did it but when I school on x line some ul  CSS does not effect (hover background color).

Second UL 4 and first UL 4  not effect background color.

ul {
  padding: 5px;
  background-color: red;
  display: block;
  white-space: nowrap;
}

li {
  width: 33%;
  display: inline-block;
}

.dataBlock {
  overflow-x: auto;
  width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div clas="dataBlock">

  <ul>
    <li> first UL 1
      <li> first UL 2
        <li> first UL 3
          <li> first UL 4
            <li> first UL 5
  </ul>
  <ul>
    <li> second UL 1
      <li>second UL 2
        <li>second UL 3
          <li>second UL 4
            <li> second UL 5
  </ul>
</div></code>```

答:
you are missing
 at the end of each li and you can achieve the desired effect using flexbox

.dataBlock {
  overflow-x: auto;
}

ul {
  padding: 5px;
  background-color: red;
  display: flex;
  min-width: 200%;
  list-style: none
}

li {
  flex: 0 33%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div clas="dataBlock">
  <ul>
    <li> first UL 1</li>
    <li> first UL 2 </li>
    <li> first UL 3 </li>
    <li> first UL 4 </li>
    <li> first UL 5</li>
  </ul>
  <ul>
    <li> second UL 1</li>
    <li>second UL 2</li>
    <li>second UL 3</li>
    <li>second UL 4 </li>
    <li> second UL 5</li>
  </ul>
</div></code>```

Body:
I want to list 2 different ul like a table and each list element like a     column lineage. ı did it but when I school on x line some ul  CSS does not effect (hover background color).

Second UL 4 and first UL 4  not effect background color.

ul {
  padding: 5px;
  background-color: red;
  display: block;
  white-space: nowrap;
}

li {
  width: 33%;
  display: inline-block;
}

.dataBlock {
  overflow-x: auto;
  width: auto;
}

 first UL 1

 first UL 2

 first UL 3

 first UL 4

 first UL 5

 second UL 1

second UL 2

second UL 3

second UL 4

 second UL 5

Body:
you are missing </li> at the end of each li and you can achieve the desired effect using flexbox

.dataBlock {
  overflow-x: auto;
}

ul {
  padding: 5px;
  background-color: red;
  display: flex;
  min-width: 200%;
  list-style: none
}

li {
  flex: 0 33%;
}

<div clas="dataBlock">
  <ul>
    <li> first UL 1</li>
    <li> first UL 2 </li>
    <li> first UL 3 </li>
    <li> first UL 4 </li>
    <li> first UL 5</li>
  </ul>
  <ul>
    <li> second UL 1</li>
    <li>second UL 2</li>
    <li>second UL 3</li>
    <li>second UL 4 </li>
    <li> second UL 5</li>
  </ul>
</div>