问:
open specific page using firebase api
I am sending push notification to devices using below code.

```<code>      var nTitle = "New message from " + $rootScope.clients_firstName;
      var to = "DeviceToken is here";
      var notification = {
        'title': nTitle,
        //'body': 'Click here to more details...',
        'icon': 'firebase-logo.png',
        'click_action': 'openapp'
      };

      var key = 'your key';
      fetch('https://fcm.googleapis.com/fcm/send', {
      'method': 'POST',
        'headers': {
        'Authorization': 'key=' + key,
        'Content-Type': 'application/json'
      },
      'body': JSON.stringify({
        'notification': data,
        'to': to
      })
      }).then(function(response) {
        //console.log("res ", response);
      }).catch(function(error) {
        console.error("err ", error);
     });
</code>```

push notification sends on device successfully.

But when I click on notification the specific page should be open.

For example 'click_action' : 'openapp/somepage'

Then the 'somepage' should be open when I click on pushnotification.

AndroidManifest.xml

```<code><activity android:name="MainActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">

        <intent-filter>
            <action android:name="openapp" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>

</activity>
</code>```

My project structure

```<code>--platforms
--plugins
--www
  --app
    --about
      --about.html
      --about.ctrl.js
    --product
      --product.html
      --product.ctrl.js
  --css
  --js
  --lib
  index.html
</code>```

If I click on notification and I want to open product or about page then what I have to do?

What is wrong here? Please tell me the proper solution.

答:
For notifications to be clickable when your app is in the background, you need the click_action attribute in your notification payload.

Please check this section of the Firebase docs.

Also, when you define the click_action attribute, you will also need a corresponding <action> attribute in the <intent-filter> of the activity that you wish to launch.

This video explains it in quite a detailed manner.

Though, please note that you can not set the click__action attribute if you're sending notifications from the Firebase Console. You can only do so if you send a notification from your own Admin server or using Firebase Cloud Functions.

Lastly, in the activity that is launched, you can set additional Data using the data attribute ( also shown in the same doc that I linked above ). And when you launch your app by clicking on a notification, you can  obtain the notification data using getIntent(). Check out this answer for more details on how to do that.

Edit after question update :-

Instead of putting that <intent-filter> in MainActivity, put the filter in the <activity> tag of the activity that you want to open when the notification is clicked. An example is the following :-

```<code><activity android:name="ProductDetailsActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">

    <intent-filter>
        <action android:name="openapp" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>
</code>```

Now that your specified activity opens, you can get information from the data part of your notification using getIntent().

For example, if your notification payload has the following structure,

```<code>payload = {
  notification: {
    title: `You ordered a new product`,
    click_action : 'HANDLE_NOTIFICATION',

  },
  data : {
        product_id : 'ABC98292',
        type : `Clothes`,
        product_name : 'Cotton spring shirt'
    }
};
</code>```

Then you can get the product_id from the notification using getIntent().getStringsExtra("product_id") and so on.

This way, you'll be opening the required activity, and can populate it with the relevant details obtained from your notification without using any additional frameworks.

Title: open specific page using firebase api

Body:
I am sending push notification to devices using below code.

      var nTitle = "New message from " + $rootScope.clients_firstName;
      var to = "DeviceToken is here";
      var notification = {
        'title': nTitle,
        //'body': 'Click here to more details...',
        'icon': 'firebase-logo.png',
        'click_action': 'openapp'
      };

      var key = 'your key';
      fetch('https://fcm.googleapis.com/fcm/send', {
      'method': 'POST',
        'headers': {
        'Authorization': 'key=' + key,
        'Content-Type': 'application/json'
      },
      'body': JSON.stringify({
        'notification': data,
        'to': to
      })
      }).then(function(response) {
        //console.log("res ", response);
      }).catch(function(error) {
        console.error("err ", error);
     });

push notification sends on device successfully.

But when I click on notification the specific page should be open.

For example 'click_action' : 'openapp/somepage'

Then the 'somepage' should be open when I click on pushnotification.

AndroidManifest.xml

<activity android:name="MainActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">

        <intent-filter>
            <action android:name="openapp" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>

</activity>

My project structure

--platforms
--plugins
--www
  --app
    --about
      --about.html
      --about.ctrl.js
    --product
      --product.html
      --product.ctrl.js
  --css
  --js
  --lib
  index.html

If I click on notification and I want to open product or about page then what I have to do?

What is wrong here? Please tell me the proper solution.

Body:
For notifications to be clickable when your app is in the background, you need the click_action attribute in your notification payload.

Please check this section of the Firebase docs.

Also, when you define the click_action attribute, you will also need a corresponding <action> attribute in the <intent-filter> of the activity that you wish to launch.

This video explains it in quite a detailed manner.

Though, please note that you can not set the click__action attribute if you're sending notifications from the Firebase Console. You can only do so if you send a notification from your own Admin server or using Firebase Cloud Functions.

Lastly, in the activity that is launched, you can set additional Data using the data attribute ( also shown in the same doc that I linked above ). And when you launch your app by clicking on a notification, you can  obtain the notification data using getIntent(). Check out this answer for more details on how to do that.

Edit after question update :-

Instead of putting that <intent-filter> in MainActivity, put the filter in the <activity> tag of the activity that you want to open when the notification is clicked. An example is the following :-

<activity android:name="ProductDetailsActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">

    <intent-filter>
        <action android:name="openapp" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>

Now that your specified activity opens, you can get information from the data part of your notification using getIntent().

For example, if your notification payload has the following structure,

payload = {
  notification: {
    title: `You ordered a new product`,
    click_action : 'HANDLE_NOTIFICATION',

  },
  data : {
        product_id : 'ABC98292',
        type : `Clothes`,
        product_name : 'Cotton spring shirt'
    }
};

Then you can get the product_id from the notification using getIntent().getStringsExtra("product_id") and so on.

This way, you'll be opening the required activity, and can populate it with the relevant details obtained from your notification without using any additional frameworks.


来源: stackexchange

问:
removing duplicates rows of a dataframe python
I need to remove duplicate rows from a dataset. Basically, I should perform

```<code>proc sort data=mydata noduprecs dupout=mydata_dup;run;
</code>```

I need to remove duplicates as well as save those duplicate rows in a separate dataframe. How can I do that?

答:
Assuming your dataset is a pandas dataframe.

To remove the duplicated rows:

```<code>data = data.drop_duplicates()
</code>```

To select all the duplicated rows:

```<code>dup = data.ix[data.duplicated(), :]
</code>```

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
I need to remove duplicate rows from a dataset. Basically, I should perform

proc sort data=mydata noduprecs dupout=mydata_dup;run;

I need to remove duplicates as well as save those duplicate rows in a separate dataframe. How can I do that?

Body:
Assuming your dataset is a pandas dataframe.

To remove the duplicated rows:

data = data.drop_duplicates()

To select all the duplicated rows:

dup = data.ix[data.duplicated(), :]

Hope it helps.


问:
Can't fully round images on Safari
I can't make my images perfectly round on Safari using border-radius. What's wrong with my code?

HTML:

```<code><div class="people_photo_wrap">
  <img class="people_photo" src="image.jpg">
</div>
</code>```

CSS:

```<code>.people_photo_wrap {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  overflow: hidden;
}
.people_photo {
  width: 100px;
  height: 100px;
  border: 3px solid transparent;
}
</code>```

答:
Add the radius to the image. Should do the trick.</p>

```<code>.people_photo {
  width: 100px;
  height: 100px;
  border: 3px solid transparent;
  border-radius: 50%;
}
</code>```

Title: Can't fully round images on Safari

Body:
I can't make my images perfectly round on Safari using border-radius. What's wrong with my code?

HTML:

CSS:

.people_photo_wrap {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  overflow: hidden;
}
.people_photo {
  width: 100px;
  height: 100px;
  border: 3px solid transparent;
}

Body:
Add the radius to the image. Should do the trick.

.people_photo {
  width: 100px;
  height: 100px;
  border: 3px solid transparent;
  border-radius: 50%;
}


问:
Extracting the inner text from span using vba
I am trying to scrap some data from a webpage into Excel using vba.

The html code is

```<code><span id="lastPrice">300.21</span>
</code>```

I want the number 300.21

I tried this but didn't work (returned nothing in st)

```<code>Dim st As String

st = htmldoc.getElementById("lastPrice").getElementsByTagName("span")(5).innerText
</code>```

How can I get the desired output ?

答:
Try this: </p>

```<code>Dim element as Object
Set element = htmldoc.getElementById("lastPrice")

Dim price as String
If Not element Is Nothing Then price = element.innerText
</code>```

Body:
I am trying to scrap some data from a webpage into Excel using vba.

The html code is

300.21

I want the number 300.21

I tried this but didn't work (returned nothing in st)

Dim st As String

st = htmldoc.getElementById("lastPrice").getElementsByTagName("span")(5).innerText

How can I get the desired output ?

Body:
Try this:

Dim element as Object
Set element = htmldoc.getElementById("lastPrice")

Dim price as String
If Not element Is Nothing Then price = element.innerText


问:
Angular 2: Pass a function to the ngClass tag on the template
I have done some searching on this but haven't come across anything that works.

When i pass a function to the ngStyle i get the following error:

Expression 'getClass()' in ProductView has changed after it was checked.

My Template looks like:

```<code><div class="itemContainer">
    <div class="well imageHolder" [ngClass]="getClass()">
        <img [src]="'img/thumbs/' + item.images[0]" class="productImage" id="productImage">
    </div>
</div>
</code>```

Im not sure what would fix this or even if it can currently be done. I have noticed that this error also occurs with ngStyle.

All help would be appreciated.

答:
The answer is simple, you can do that with a function, just make sure the function will return the class name

on html:

```<code><div [ngClass]="getClassByValue('a')"> My Div</div>
</code>```

on ts file:

```<code>  getClassByValue(value: string) {
    switch (value) {
      case "a": return "class-a";
      case "b": return "class-b";
    }
  }
</code>```

will end up with class name "class-a" on your element.

Hope it helps :)

Body:
I have done some searching on this but haven't come across anything that works.

When i pass a function to the ngStyle i get the following error:

Expression 'getClass()' in ProductView has changed after it was checked.

My Template looks like:

Im not sure what would fix this or even if it can currently be done. I have noticed that this error also occurs with ngStyle.

All help would be appreciated.

Body:
The answer is simple, you can do that with a function, just make sure the function will return the class name

on html:

<div [ngClass]="getClassByValue('a')"> My Div</div>

on ts file:

  getClassByValue(value: string) {
    switch (value) {
      case "a": return "class-a";
      case "b": return "class-b";
    }
  }

will end up with class name "class-a" on your element.

Hope it helps :)


问:
How can i download image using selenium webdriver by right clicking the image in java?
I need to save the image by right clicking using selenium and also by "Authenticating the browser with username and password". the link which i am sending through selenium looks like this  "http://111.111.2.125/capture".

As I am new this concept, any suggestions will be highly helpful.

答:
Hope answer by @sForSujit has helped you for 'Right Clicking' on the image.

For Authenticating the browser with username and password, You could consider passing credentials in URL
First, visit the URL with credentials then visit the URL without credentials

Example:
First, access

http://username:password@111.111.2.125/capture

Then, access below one-

http://111.111.2.125/capture


问:
(Python 3.6) TypeError: can't concat bytes to tuple
I am trying to insert scraped items ('title') into a mySQL database.

This is the snippet of my spider.py file that scrapes 'title' content:

```<code>#get more details
def parse_detail_page(self, response):
    item = response.meta["item"]

    #title
    title = response.xpath(".//*[@id='titletextonly']/text()").extract()[0]
    item["title"] = title

    return item
</code>```

This is my pipelines.py file:

```<code>import pymysql.cursors

class mySQLTest(object):

    def __init__(self):
        self.conn = pymysql.connect(host='localhost',
                             user='root',
                             password='',
                             db='testDB',
                             charset='utf8mb4',
                          cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    def process_item (self, item, spider):
        sql = "INSERT INTO items (title) VALUES (%s)", (item['title'])
        self.cursor.execute(sql)
        self.conn.commit()

        return item
</code>```

I am running into the following error:

```<code>    Traceback (most recent call last):
  File "/Users/venv1/lib/python3.6/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/Users/venv1/tutorial/tutorial/pipelines.py", line 31, in process_item
    self.cursor.execute(sql)
  File "/Users/venv1/lib/python3.6/site-packages/pymysql/cursors.py", line 166, in execute
    result = self._query(query)
  File "/Users/sandysu/PyCharmProjects/venv1/lib/python3.6/site-packages/pymysql/cursors.py", line 322, in _query
    conn.query(q)
  File "/Users/venv1/lib/python3.6/site-packages/pymysql/connections.py", line 855, in query
    self._execute_command(COMMAND.COM_QUERY, sql)
  File "/Users/venv1/lib/python3.6/site-packages/pymysql/connections.py", line 1091, in _execute_command
    packet = prelude + sql[:packet_size-1]
TypeError: can't concat bytes to tuple
</code>```

What does this TypeError: can't concat bytes to tuple mean?  How should it be fixed?

答:
This was the syntax that was able to finally insert data into the database:</p>

```<code>def process_item (self, item, spider):
    sql = "INSERT INTO items (title) VALUES (%s)"
    data = item['title']

    self.cursor.execute(sql, data)
    self.conn.commit()

    return item
</code>```

Body:
I am trying to insert scraped items ('title') into a mySQL database.

This is the snippet of my spider.py file that scrapes 'title' content:

#get more details
def parse_detail_page(self, response):
    item = response.meta["item"]

    #title
    title = response.xpath(".//*[@id='titletextonly']/text()").extract()[0]
    item["title"] = title

    return item

This is my pipelines.py file:

import pymysql.cursors

class mySQLTest(object):

    def __init__(self):
        self.conn = pymysql.connect(host='localhost',
                             user='root',
                             password='',
                             db='testDB',
                             charset='utf8mb4',
                          cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    def process_item (self, item, spider):
        sql = "INSERT INTO items (title) VALUES (%s)", (item['title'])
        self.cursor.execute(sql)
        self.conn.commit()

        return item

I am running into the following error:

    Traceback (most recent call last):
  File "/Users/venv1/lib/python3.6/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/Users/venv1/tutorial/tutorial/pipelines.py", line 31, in process_item
    self.cursor.execute(sql)
  File "/Users/venv1/lib/python3.6/site-packages/pymysql/cursors.py", line 166, in execute
    result = self._query(query)
  File "/Users/sandysu/PyCharmProjects/venv1/lib/python3.6/site-packages/pymysql/cursors.py", line 322, in _query
    conn.query(q)
  File "/Users/venv1/lib/python3.6/site-packages/pymysql/connections.py", line 855, in query
    self._execute_command(COMMAND.COM_QUERY, sql)
  File "/Users/venv1/lib/python3.6/site-packages/pymysql/connections.py", line 1091, in _execute_command
    packet = prelude + sql[:packet_size-1]
TypeError: can't concat bytes to tuple

What does this TypeError: can't concat bytes to tuple mean?  How should it be fixed?

Body:
This was the syntax that was able to finally insert data into the database:

def process_item (self, item, spider):
    sql = "INSERT INTO items (title) VALUES (%s)"
    data = item['title']

    self.cursor.execute(sql, data)
    self.conn.commit()

    return item


问:
I could use some Regex help
EDIT: What I'm looking for below is a REGEX statement that says something like this:

Grab lines beginning with div class='productBundle' ending with .html.

Grab all of them (I think this is called greedy)

I'll store these in an array, then I'll fetch the pages. For each page, I'll then need to grab the image url, so I'll need the regex code for that. I know it's brittle, but it'll get the job done for what I need.

I have a page of html, with groups of the following:

```<code><div class='productBundle' id='4086472'>
<table cellpadding="0" cellspacing="0" class='inv'>
<tr><td valign="middle" align="center" width="100%">
<a href="http://listing.com/product/view/4086794.html" alt="472">
</code>```

I'd like to retrieve all the urls listed under the div class='productBundle'. There could be any number per page, but always under the productBundle div.

Then from those html pages, I need to get product image url

```<code><img id=productImage' src='http://listing.com/item/472248/472.jpg'>
</code>```

For example, I need "http://listing.com/item/472248/472.jpg" from the html code above.

I could use the help with the REGEX code to grab the pages in the first part, then the REGEX code to grab the url from the productImage.

Thanks

答:
This does the trick.

"http:\/\/listing.com\/product+([^""])*html"

ContentLicense: CC BY-SA 2.5

Title: I could use some Regex help

Body:
EDIT: What I'm looking for below is a REGEX statement that says something like this:

Grab lines beginning with div class='productBundle' ending with .html.

Grab all of them (I think this is called greedy)

I'll store these in an array, then I'll fetch the pages. For each page, I'll then need to grab the image url, so I'll need the regex code for that. I know it's brittle, but it'll get the job done for what I need.

I have a page of html, with groups of the following:

I'd like to retrieve all the urls listed under the div class='productBundle'. There could be any number per page, but always under the productBundle div.

Then from those html pages, I need to get product image url

For example, I need "http://listing.com/item/472248/472.jpg" from the html code above.

I could use the help with the REGEX code to grab the pages in the first part, then the REGEX code to grab the url from the productImage.

Thanks


问:
Spring Data JPA ManyToOne Bidirectional
Problem: it works till i try to add Student obejcts to Database, but the tables are being created correctly .
I can't simplify the post any further. But it's mainly code that doesn't require a lot of reading, it's a simple spring data repository service model. I posted it all due to the fact idk what am i doing wrong. Problem is in the JPA mapping.
I got the example from over here http://www.java2s.com/Tutorial/Java/0355__JPA/OneToManyBidirectional.htm

MDOELS

```<code>@Entity
public class Department {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;

    @OneToMany(mappedBy="department")
    private Collection<Student> students;

    public Department() {
    }

    public Department(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Collection<Student> getStudents() {
        return students;
    }

    public void setStudent(Collection<Student> students) {
        this.students = students;
    }

    public String toString() {
        return "Department id: " + getId() +
                ", name: " + getName();
    }
}

@Entity
public class Student {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;

    @ManyToOne (cascade=CascadeType.ALL)
    private Department department;

    public Student() {
    }

    public Student(String name, Department department) {
        this.name = name;
        this.department = department;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String toString() {
        return "\n\nID:" + id + "\nName:" + name + "\n\n" + department;
    }
}
</code>```

REPOSITORIES

```<code>@Repository
public interface DepartmentRepository extends JpaRepository<Department, Integer> {
    Department findByName(String name);

}

@Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
    Student findByName(String name);
}
</code>```

SERVICES

```<code>@Service
public class StudentService {
    private final StudentRepository studentRepository;

    @Autowired
    public StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;

    }

    public void addToDatabase(Student student) {
        this.studentRepository.saveAndFlush(student);

    }

    public Student getStudentByName(String name) {
        return studentRepository.findByName(name);
    }
}
@Service
public class DepartmentService {
    private final DepartmentRepository departmentRepository;

    @Autowired
    public DepartmentService(DepartmentRepository departmentRepository) {
        this.departmentRepository = departmentRepository;

    }

    public void addToDataBase(List<Department> department) {
        this.departmentRepository.save(department);
        department.forEach(this.departmentRepository::saveAndFlush);
    }
    public Department getDepartmentByName(String name){
        return  this.departmentRepository.findByName(name);
    }
}
</code>```

My main method

```<code>@Component
public class Terminal implements CommandLineRunner {
    private final StudentService studentService;
    private final DepartmentService departmentService;

    @Autowired
    public Terminal(StudentService studentService, DepartmentService departmentService) {
        this.studentService = studentService;
        this.departmentService = departmentService;
    }

        @Override
        public void run(String... strings) throws Exception {
            Department department = new Department("dep1");
            Department department1 = new Department("dep2");
            Department department2 = new Department("dep3");
            Department department3 = new Department("dep4");
            List<Department> departments = new ArrayList<>(Arrays.asList(department, department1, department2, department3));
            this.departmentService.addToDataBase(departments);
    //
            Student student = new Student("pesho", department);
            Student student11 = new Student("gosho", department1);
            this.studentService.addToDatabase(student11);
            this.studentService.addToDatabase(student);
            student = new Student("sasho", department2);
            this.studentService.addToDatabase(student);
    //        System.out.println(this.studentService.getStudentByName("gosho").getDepartment1());
    //        System.out.println("CHECKING ONE TO ONE BIDIRECTIONAL: " + this.departmentService.getDepartmentByName("dep1").getStudent());

        }
    }
</code>```

So here when i try to add students in the students table it gives an error
The error is the fallowing

```<code>Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: app.models.Department
</code>```

答:
you added cascade= CascadeType.ALL for Department in Student class and save departments separete. this.departmentService.addToDataBase(departments);

fix : dont call

```<code>departmentService.addToDataBase(departments);
</code>```

or remove CascadeType.ALL from Student

Title: Spring Data JPA ManyToOne Bidirectional

Body:
Problem: it works till i try to add Student obejcts to Database, but the tables are being created correctly .
I can't simplify the post any further. But it's mainly code that doesn't require a lot of reading, it's a simple spring data repository service model. I posted it all due to the fact idk what am i doing wrong. Problem is in the JPA mapping.
I got the example from over here http://www.java2s.com/Tutorial/Java/0355__JPA/OneToManyBidirectional.htm

MDOELS

@Entity
public class Department {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;

    @OneToMany(mappedBy="department")
    private Collection<Student> students;

    public Department() {
    }

    public Department(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Collection<Student> getStudents() {
        return students;
    }

    public void setStudent(Collection<Student> students) {
        this.students = students;
    }

    public String toString() {
        return "Department id: " + getId() +
                ", name: " + getName();
    }
}

@Entity
public class Student {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;

    @ManyToOne (cascade=CascadeType.ALL)
    private Department department;

    public Student() {
    }

    public Student(String name, Department department) {
        this.name = name;
        this.department = department;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String toString() {
        return "\n\nID:" + id + "\nName:" + name + "\n\n" + department;
    }
}

REPOSITORIES

@Repository
public interface DepartmentRepository extends JpaRepository<Department, Integer> {
    Department findByName(String name);

}

@Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
    Student findByName(String name);
}

SERVICES

@Service
public class StudentService {
    private final StudentRepository studentRepository;

    @Autowired
    public StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;

    }

    public void addToDatabase(Student student) {
        this.studentRepository.saveAndFlush(student);

    }

    public Student getStudentByName(String name) {
        return studentRepository.findByName(name);
    }
}
@Service
public class DepartmentService {
    private final DepartmentRepository departmentRepository;

    @Autowired
    public DepartmentService(DepartmentRepository departmentRepository) {
        this.departmentRepository = departmentRepository;

    }

    public void addToDataBase(List<Department> department) {
        this.departmentRepository.save(department);
        department.forEach(this.departmentRepository::saveAndFlush);
    }
    public Department getDepartmentByName(String name){
        return  this.departmentRepository.findByName(name);
    }
}

My main method

@Component
public class Terminal implements CommandLineRunner {
    private final StudentService studentService;
    private final DepartmentService departmentService;

    @Autowired
    public Terminal(StudentService studentService, DepartmentService departmentService) {
        this.studentService = studentService;
        this.departmentService = departmentService;
    }

        @Override
        public void run(String... strings) throws Exception {
            Department department = new Department("dep1");
            Department department1 = new Department("dep2");
            Department department2 = new Department("dep3");
            Department department3 = new Department("dep4");
            List<Department> departments = new ArrayList<>(Arrays.asList(department, department1, department2, department3));
            this.departmentService.addToDataBase(departments);
    //
            Student student = new Student("pesho", department);
            Student student11 = new Student("gosho", department1);
            this.studentService.addToDatabase(student11);
            this.studentService.addToDatabase(student);
            student = new Student("sasho", department2);
            this.studentService.addToDatabase(student);
    //        System.out.println(this.studentService.getStudentByName("gosho").getDepartment1());
    //        System.out.println("CHECKING ONE TO ONE BIDIRECTIONAL: " + this.departmentService.getDepartmentByName("dep1").getStudent());

        }
    }

So here when i try to add students in the students table it gives an error
The error is the fallowing

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: app.models.Department

Body:
you added cascade= CascadeType.ALL for Department in Student class and save departments separete. this.departmentService.addToDataBase(departments);

fix : dont call

departmentService.addToDataBase(departments);

or remove CascadeType.ALL from Student


问:
How do I format a dataset for training in Python?
How do I format a dataset for training in Python?

I have 3000 grayscale BMP images of some handwritten digits (just like MNIST). Now I want to train my model with this dataset (I am using the Keras library) and I am using a convolution neural network for training.

I am using this code to convert one of the images into array

```<code>`import numpy
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = Image.open(open('CMATERdb 3.3.1\Ad02599.bmp')).convert("L")
print(img.format, img.size, img.mode)
img = numpy.asarray(img) / 255.
imgplot = plt.imshow(img)`
</code>```

and the result from the code was

None (32, 32) L

image from the 3000 image want to convert into dataset

Any help how I can convert all images and put them in the same MNIST datast format that will be highly appreciated.

答:
You can use any library that loads image files into arrays, such as Pillow.

Read Pillow's documentation to learn how to load an image file into an array.

Then, you should usually scale the array into values between 0 and 1. Usually, you just divide the image array by 255 (because they are RGB values between 0 and 255).

Be sure to end up with an array shaped like this: (3000, width, heigth, channels), where channels is usually 3 (Red, green, blue).

Body:
How do I format a dataset for training in Python?

I have 3000 grayscale BMP images of some handwritten digits (just like MNIST). Now I want to train my model with this dataset (I am using the Keras library) and I am using a convolution neural network for training.

I am using this code to convert one of the images into array

`import numpy
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = Image.open(open('CMATERdb 3.3.1\Ad02599.bmp')).convert("L")
print(img.format, img.size, img.mode)
img = numpy.asarray(img) / 255.
imgplot = plt.imshow(img)`

and the result from the code was

None (32, 32) L

image from the 3000 image want to convert into dataset

Any help how I can convert all images and put them in the same MNIST datast format that will be highly appreciated.


问:
C# NPOI rowStyle
Ii have applied NPOI to generate the excel. So far so good except that I want to bold a row.

I have tried:

```<code>tmpRow.RowStyle = workbook.CreateCellStyle();
tmpRow.RowStyle.SetFont(boldFont);
</code>```

However, nothing has changed.

While I can do it by setting it one by one:

```<code>ICellStyle boldFontCellStyle = workbook.CreateCellStyle();
IFont boldFont = workbook.CreateFont();
boldFont.IsBold = true;
boldFontCellStyle.SetFont(boldFont);
for (int p= 0; p <= 12; p++)
{
    tmpRow.GetCell(p).CellStyle = boldFontCellStyle;
}
//tmpRow.RowStyle = workbook.CreateCellStyle();
//tmpRow.RowStyle.SetFont(boldFont);
</code>```

I would like to know if there is any way to set an entire row style in NPOI?

Thanks.

答:
Try this for Row styling </p>

```<code>XSSFFont defaultFont = (XSSFFont)workbook.CreateFont();
defaultFont.FontHeightInPoints = (short)10;
defaultFont.FontName = "Arial";
defaultFont.Color = IndexedColors.Black.Index;
defaultFont.IsBold = true;

XSSFCellStyle yourCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
yourCellStyle.SetFont(defaultFont);

var row = sheet.CreateRow(0);
row.RowStyle = yourCellStyle;
</code>```

<p>Below one was for cell style </p>

```<code> XSSFFont yourFont = (XSSFFont)workbook.CreateFont();
    yourFont.FontHeightInPoints = (short)12;
    yourFont.FontName = "Arial";
    yourFont.IsBold = true;
    yourFont.IsItalic = false;
    yourFont.Boldweight = 700;
    XSSFCellStyle yourStyle = (XSSFCellStyle)workbook.CreateCellStyle();
    yourStyle.SetFont(yourFont);
    for (int p= 0; p <= 12; p++)
      {
        row.Cells[p].CellStyle = yourStyle;
      }
</code>```

Title: C# NPOI rowStyle

Body:
Ii have applied NPOI to generate the excel. So far so good except that I want to bold a row.

I have tried:

tmpRow.RowStyle = workbook.CreateCellStyle();
tmpRow.RowStyle.SetFont(boldFont);

However, nothing has changed.

While I can do it by setting it one by one:

ICellStyle boldFontCellStyle = workbook.CreateCellStyle();
IFont boldFont = workbook.CreateFont();
boldFont.IsBold = true;
boldFontCellStyle.SetFont(boldFont);
for (int p= 0; p <= 12; p++)
{
    tmpRow.GetCell(p).CellStyle = boldFontCellStyle;
}
//tmpRow.RowStyle = workbook.CreateCellStyle();
//tmpRow.RowStyle.SetFont(boldFont);

I would like to know if there is any way to set an entire row style in NPOI?

Thanks.

Body:
Try this for Row styling

XSSFFont defaultFont = (XSSFFont)workbook.CreateFont();
defaultFont.FontHeightInPoints = (short)10;
defaultFont.FontName = "Arial";
defaultFont.Color = IndexedColors.Black.Index;
defaultFont.IsBold = true;

XSSFCellStyle yourCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
yourCellStyle.SetFont(defaultFont);

var row = sheet.CreateRow(0);
row.RowStyle = yourCellStyle;

Below one was for cell style

 XSSFFont yourFont = (XSSFFont)workbook.CreateFont();
    yourFont.FontHeightInPoints = (short)12;
    yourFont.FontName = "Arial";
    yourFont.IsBold = true;
    yourFont.IsItalic = false;
    yourFont.Boldweight = 700;
    XSSFCellStyle yourStyle = (XSSFCellStyle)workbook.CreateCellStyle();
    yourStyle.SetFont(yourFont);
    for (int p= 0; p <= 12; p++)
      {
        row.Cells[p].CellStyle = yourStyle;
      }


问:
Creating a reusable component reactjs
I read an article that creating small reusable components decreases the file size, makes unit testing faster and easier and a lot more. So I'm now trying to create one, however I am very new to reactjs and I'm maintaining this project for a friend, so I haven't written all the code.

Heres a code snippet:

```<code>class ObjectKeyDisplay extends Component {
  constructor(props) {
    super(props)
    this.state = { open: false } // Sets open to false (closed)
  }

  renderInner() {
    const { schema, parentDocumentId, collectionName, value } = this.props
    const { open } = this.state // equals const open = this.state.open

    let expandButton
    if (schema.type === 'belongs_to') {
      expandButton = (
        <button onClick={e => this.setState({ open: !open })}> // Sets it to true (opened)
          {open ? 'Minimera' : 'Expandera'}
        </button>
      )
    }
</code>```

So I basically want to make the whole open/close process to a component, so I easily reuse the logic for other buttons. I would really appreciate if someone could help me out here!

答:
Here's a working example.

Move the button into it's own component where it can control it's own open state. Also, it'd be a good idea to provide some callbacks when the state changes that can be used in the parent component. There are multiple ways of conditionally rendering the button contents. What I've done here is pass in an array of children and if open is true, then render the first child in the array.

```<code>class Main extends React.Component {
    render(){
    return (
        <div>
        Expand button
        <ExpandButton onOpen={() => console.log('opened')} onClose={() => console.log('closed')} >
            <div>Open</div>
          <div>Close</div>
        </ExpandButton>
      </div>
    )
  }
}
class ExpandButton extends React.Component {
    constructor(){
    super();
    this.toggleOpen = this.toggleOpen.bind(this);
    this.state = {
        open: false
    }
  }
  toggleOpen(){
    this.setState({
        open: !this.state.open
    }, () => {
        // Trigger callbacks
        if(this.state.open){
        this.props.onOpen();
      }else{
        this.props.onClose();
      }
    })
  }
    render(){
    const { open } = this.state;
    return (
        <button onClick={this.toggleOpen}>
        {open ? this.props.children[0] : this.props.children[1]}
      </button>
    )
  }
}
React.render(<Main />, document.getElementById('container'));
</code>```

Title: Creating a reusable component reactjs

Body:
I read an article that creating small reusable components decreases the file size, makes unit testing faster and easier and a lot more. So I'm now trying to create one, however I am very new to reactjs and I'm maintaining this project for a friend, so I haven't written all the code.

Heres a code snippet:

class ObjectKeyDisplay extends Component {
  constructor(props) {
    super(props)
    this.state = { open: false } // Sets open to false (closed)
  }

  renderInner() {
    const { schema, parentDocumentId, collectionName, value } = this.props
    const { open } = this.state // equals const open = this.state.open

    let expandButton
    if (schema.type === 'belongs_to') {
      expandButton = (
        <button onClick={e => this.setState({ open: !open })}> // Sets it to true (opened)
          {open ? 'Minimera' : 'Expandera'}
        </button>
      )
    }

So I basically want to make the whole open/close process to a component, so I easily reuse the logic for other buttons. I would really appreciate if someone could help me out here!

Body:
Here's a working example.

Move the button into it's own component where it can control it's own open state. Also, it'd be a good idea to provide some callbacks when the state changes that can be used in the parent component. There are multiple ways of conditionally rendering the button contents. What I've done here is pass in an array of children and if open is true, then render the first child in the array.

class Main extends React.Component {
    render(){
    return (
        <div>
        Expand button
        <ExpandButton onOpen={() => console.log('opened')} onClose={() => console.log('closed')} >
            <div>Open</div>
          <div>Close</div>
        </ExpandButton>
      </div>
    )
  }
}
class ExpandButton extends React.Component {
    constructor(){
    super();
    this.toggleOpen = this.toggleOpen.bind(this);
    this.state = {
        open: false
    }
  }
  toggleOpen(){
    this.setState({
        open: !this.state.open
    }, () => {
        // Trigger callbacks
        if(this.state.open){
        this.props.onOpen();
      }else{
        this.props.onClose();
      }
    })
  }
    render(){
    const { open } = this.state;
    return (
        <button onClick={this.toggleOpen}>
        {open ? this.props.children[0] : this.props.children[1]}
      </button>
    )
  }
}
React.render(<Main />, document.getElementById('container'));


问:
Modularity support with Gradle
I understand from this link that gradle 3 enables Java 9 support but don't support modulepath.

https://blog.gradle.org/java-9-support

Also, i found this github link which talks about jdk 9 support.

https://github.com/gradle/gradle/blob/master/design-docs/jdk9-support.md

Does gradle 3.5 support compilation of modular code using jdk 9? Has anyone tried it?

答:
Per this tweet, Gradle 4.1 milestone 1 will run under JDK 9. That is, legacy builds will work using JDK 9.

I believe that support for JDK 9 modules is still in development, per comments in this thread.

Title: Modularity support with Gradle


问:
Django image does not display in template
I am using Django and i want to import an image to my about.html file

Both the picture and the about.html are in the same file, see the picture down

i am trying to insert the image like this, but i get a broken picture icon

```<code><img src="templates/WebApp/rolomatik_logo_crna_verzija.png"
</code>```

Any suggestions please?

答:
You cannot insert an image in that way. You need to keep that in a static folder.

Create a folder named static and place your image inside it.

Then use {% load static %} at the top of your template.

Your img tag should look like this:

For more details refer: https://docs.djangoproject.com/en/1.11/howto/static-files/

Body:
I am using Django and i want to import an image to my about.html file

Both the picture and the about.html are in the same file, see the picture down

i am trying to insert the image like this, but i get a broken picture icon

<img src="templates/WebApp/rolomatik_logo_crna_verzija.png"

Any suggestions please?

Body:
You cannot insert an image in that way. You need to keep that in a static folder.

Create a folder named static and place your image inside it.

Then use {% load static %} at the top of your template.

Your img tag should look like this: <img src="{% static "rolomatik_logo_crna_verzija.png" %}" />

For more details refer: https://docs.djangoproject.com/en/1.11/howto/static-files/


问:
How to get a unit count of records from total count of record
I have a gridview on aspx page. I'm filtering by units, example: unit 1, unit 2 and so on. By default when the page opens I get the total count of records in my database:

```<code>protected void sdsTACStudents_Selected(object sender, SqlDataSourceStatusEventArgs e)
        {
            if (txtSearchByName.Text == "")
            {
                int rowCount = e.AffectedRows;
                txtRecordCount.Text = rowCount.ToString();
            }
        }
But if ddlSearchBy.Text == "Last Name, "First Name" or "ssn", I need to display the current units count:
protected void sdsTACStudents_Selected(object sender, SqlDataSourceStatusEventArgs e)
        {
            if (txtSearchByName.Text == "")
            {
                int rowCount = e.AffectedRows;
                txtRecordCount.Text = rowCount.ToString();
            }
            else if ((ddlSearchBy.Text == "Last Name") || (ddlSearchBy.Text == "First Name") || (ddlSearchBy.Text == "SSN"))
            {
                display the current unit count which is less than the total count of all units.
            }
        }
</code>```

Do I need to use a stored procedure to get the number of people in the unit?

答:
The answer to your question is Yes. You need a stored procedure or parametrized query that can take any of those parameters (Last Name, First Name or SSN) and return the number of rows that match the criteria.

One example would be:

```<code>SELECT COUNT(*) as NUM_RECORDS FROM YOUR_TABLE
WHERE FirstName LIKE '%'+@FirstName+'%'; -- assuming you only want to do partial matching
</code>```

It's up to you whether you create a stored proc or simply create a parametrized query, but this is the general idea.

Body:
I have a gridview on aspx page. I'm filtering by units, example: unit 1, unit 2 and so on. By default when the page opens I get the total count of records in my database:

protected void sdsTACStudents_Selected(object sender, SqlDataSourceStatusEventArgs e)
        {
            if (txtSearchByName.Text == "")
            {
                int rowCount = e.AffectedRows;
                txtRecordCount.Text = rowCount.ToString();
            }
        }
But if ddlSearchBy.Text == "Last Name, "First Name" or "ssn", I need to display the current units count:
protected void sdsTACStudents_Selected(object sender, SqlDataSourceStatusEventArgs e)
        {
            if (txtSearchByName.Text == "")
            {
                int rowCount = e.AffectedRows;
                txtRecordCount.Text = rowCount.ToString();
            }
            else if ((ddlSearchBy.Text == "Last Name") || (ddlSearchBy.Text == "First Name") || (ddlSearchBy.Text == "SSN"))
            {
                display the current unit count which is less than the total count of all units.
            }
        }

Do I need to use a stored procedure to get the number of people in the unit?

Body:
The answer to your question is Yes. You need a stored procedure or parametrized query that can take any of those parameters (Last Name, First Name or SSN) and return the number of rows that match the criteria.

One example would be:

SELECT COUNT(*) as NUM_RECORDS FROM YOUR_TABLE
WHERE FirstName LIKE '%'+@FirstName+'%'; -- assuming you only want to do partial matching

It's up to you whether you create a stored proc or simply create a parametrized query, but this is the general idea.


问:
Restrict date in jquery datepicker based on another datepicker or textbox
I have two text boxes with a datepicker hooked up to them. The text boxes are for start date and end date. The first datepicker is setup so that the user cannot choose a date before today, but can choose any date in the future.

How can I setup the second datepicker so that it cannot choose a date before the date chosen in the first date picker? For example: If today is 12/11/10 and I choose 12/15/10 in the first datepicker, then the second date picker shouldn't be able to choose anything before 12/15/10.

Heres what I have so far:

```<code>$("#txtStartDate").datepicker({ minDate: 0 });
$("#txtEndDate").datepicker({});
</code>```

答:
For example, in this sample code, startDatePicker is selected as 2010-12-12, change event of startDatePicker sets the minDate of endDatePicker 2010-12-13. It locks the cells before this date. This is a sample for what @Victor mentioned..I hope it helps...Regards...Ozlem.</p>

```<code>$("#startDatePicker").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    minDate: new Date(),
    maxDate: '+2y',
    onSelect: function(date){

        var selectedDate = new Date(date);
        var msecsInADay = 86400000;
        var endDate = new Date(selectedDate.getTime() + msecsInADay);

       //Set Minimum Date of EndDatePicker After Selected Date of StartDatePicker
        $("#endDatePicker").datepicker( "option", "minDate", endDate );
        $("#endDatePicker").datepicker( "option", "maxDate", '+2y' );

    }
});

$("#endDatePicker").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true
});
</code>```

Body:
I have two text boxes with a datepicker hooked up to them. The text boxes are for start date and end date. The first datepicker is setup so that the user cannot choose a date before today, but can choose any date in the future.

How can I setup the second datepicker so that it cannot choose a date before the date chosen in the first date picker? For example: If today is 12/11/10 and I choose 12/15/10 in the first datepicker, then the second date picker shouldn't be able to choose anything before 12/15/10.

Heres what I have so far:

$("#txtStartDate").datepicker({ minDate: 0 });
$("#txtEndDate").datepicker({});

Body:
For example, in this sample code, startDatePicker is selected as 2010-12-12, change event of startDatePicker sets the minDate of endDatePicker 2010-12-13. It locks the cells before this date. This is a sample for what @Victor mentioned..I hope it helps...Regards...Ozlem.

$("#startDatePicker").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    minDate: new Date(),
    maxDate: '+2y',
    onSelect: function(date){

        var selectedDate = new Date(date);
        var msecsInADay = 86400000;
        var endDate = new Date(selectedDate.getTime() + msecsInADay);

       //Set Minimum Date of EndDatePicker After Selected Date of StartDatePicker
        $("#endDatePicker").datepicker( "option", "minDate", endDate );
        $("#endDatePicker").datepicker( "option", "maxDate", '+2y' );

    }
});

$("#endDatePicker").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true
});


问:
how to compare time stamp with the current date in sequelize query method
How to write this query in sequelized one:</p>

```<code>select COUNT(*)
    from r5.users
WHERE
    DATE_FORMAT(createdAt,'%Y%c%d')=DATE_FORMAT(current_date(),'%Y%c%d')
</code>```

答:
You can do it this way,

```<code>Model.users.count({
where: Model.Sequelize.where(
    Model.Sequelize.fn('DATE_FORMAT',Model.Sequelize.col('createdAt'),"%Y%c%d"),
    {like:Model.Sequelize.fn('DATE_FORMAT',Model.Sequelize.fn('current_date'),"%Y%c%d")})
});
</code>```

Sequelize.fn can be used to call Database functions, it expects a syntax of the form Sequelize.fn(functionToCall, argumentsToPassToIt)

Sequelize.Col is used to refer to a particular column, say createdAt

Sequelize.where can be used to add functions to the columns to compare

Body:
How to write this query in sequelized one:

select COUNT(*)
    from r5.users
WHERE
    DATE_FORMAT(createdAt,'%Y%c%d')=DATE_FORMAT(current_date(),'%Y%c%d')

Body:
You can do it this way,

Model.users.count({
where: Model.Sequelize.where(
    Model.Sequelize.fn('DATE_FORMAT',Model.Sequelize.col('createdAt'),"%Y%c%d"),
    {like:Model.Sequelize.fn('DATE_FORMAT',Model.Sequelize.fn('current_date'),"%Y%c%d")})
});

Sequelize.fn can be used to call Database functions, it expects a syntax of the form Sequelize.fn(functionToCall, argumentsToPassToIt)

Sequelize.Col is used to refer to a particular column, say createdAt

Sequelize.where can be used to add functions to the columns to compare


问:
Allow only a single marker on a Google Map
I want the user to place a marker on a Google Map on a page. If the user clicks again, the first marker should disappear, and be replaced by the new one. How would I do this, starting from this code, as provided by Google:

```<code>function myMap() {
        var mapCanvas = document.getElementById("map");
        var mapOptions = {
        center: new google.maps.LatLng(51.7, 5), zoom: 6
        };
        var map = new google.maps.Map(mapCanvas, mapOptions);

        google.maps.event.addListener(map, 'click', function(event) {
            marker = new google.maps.Marker({
            position: event.latLng,
            map: map
            });
        });
</code>```

My first attempt was to add marker.remove(); at the start of the addListener function, this did not work for me.

Thanks in advance for any help!

答:
Found the answer myself. Replacing the AddListener with the below worked great:

GoogleMaps v3 API Create only 1 marker on click

```<code>var marker;

function placeMarker(location) {
 if ( marker ) {
   marker.setPosition(location);
 } else {
  marker = new google.maps.Marker({
  position: location,
  map: map
  });
 }
}

google.maps.event.addListener(map, 'click', function(event) {
  placeMarker(event.latLng);
});
</code>```

Body:
I want the user to place a marker on a Google Map on a page. If the user clicks again, the first marker should disappear, and be replaced by the new one. How would I do this, starting from this code, as provided by Google:

function myMap() {
        var mapCanvas = document.getElementById("map");
        var mapOptions = {
        center: new google.maps.LatLng(51.7, 5), zoom: 6
        };
        var map = new google.maps.Map(mapCanvas, mapOptions);

        google.maps.event.addListener(map, 'click', function(event) {
            marker = new google.maps.Marker({
            position: event.latLng,
            map: map
            });
        });

My first attempt was to add marker.remove(); at the start of the addListener function, this did not work for me.

Thanks in advance for any help!

Body:
Found the answer myself. Replacing the AddListener with the below worked great:

GoogleMaps v3 API Create only 1 marker on click

var marker;

function placeMarker(location) {
 if ( marker ) {
   marker.setPosition(location);
 } else {
  marker = new google.maps.Marker({
  position: location,
  map: map
  });
 }
}

google.maps.event.addListener(map, 'click', function(event) {
  placeMarker(event.latLng);
});


问:
What is format from url in AJAX to send POST method with RESPONSE ENTITY
I already search tutorial in spring for method POST, insert the data with response entity (without query) and I getting error in ajax. I want to confirm, What is format url from ajax to java? below my assumption:

localhost:8080/name-project/insert?id=1&name=bobby

is the above url is correct? because I failed with this url. the parameter is id and name.

mycontroller:

```<code>@PostMapping(value={"/insertuser"}, consumes={"application/json"})
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> insertUser(@RequestBody UserEntity user) throws Exception {
    Map result = new HashMap();
    userService.insertTabelUser(user);
    return new ResponseEntity<>(result, HttpStatus.CREATED);
}
</code>```

my daoimpl:

```<code>@Transactional
public String insertUser(UserEntity user) {
    return (String) this.sessionFactory.getCurrentSession().save(user);
}
</code>```

the code running in swagger (plugin maven) but not run in postman with above url.

Thanks.
Bobby

答: As above answer suggest. You are trying to pass data as query parameters.but you are not reading those values in your rest API.either you need to read those query parameters in your API and then form an object or try to pass a json serialized object to your Post api as recommendation. Hope it helps.</p>

Body:
I already search tutorial in spring for method POST, insert the data with response entity (without query) and I getting error in ajax. I want to confirm, What is format url from ajax to java? below my assumption:

localhost:8080/name-project/insert?id=1&name=bobby

is the above url is correct? because I failed with this url. the parameter is id and name.

mycontroller:

@PostMapping(value={"/insertuser"}, consumes={"application/json"})
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> insertUser(@RequestBody UserEntity user) throws Exception {
    Map result = new HashMap();
    userService.insertTabelUser(user);
    return new ResponseEntity<>(result, HttpStatus.CREATED);
}

my daoimpl:

@Transactional
public String insertUser(UserEntity user) {
    return (String) this.sessionFactory.getCurrentSession().save(user);
}

the code running in swagger (plugin maven) but not run in postman with above url.

Thanks.
Bobby


问:
413 Request Entity Too Large only via phantom js
Sending a POST request with large data set in node js/phantom js results in 413 error. However, using fiddler, if I proxy out the request, it returns data fine when sent in Fiddler or browser.

I have played with maxReceivedMessageSize web.config setting but nothing seems to work with phantom js request.

Do I need any phantom js configuration while setting up the 'page'?

答:
This turned out to be something to do with user certificates and that uploadReadAheadSize needed to be changed from default of 49KB. Once I figured how to change the setting (its locked and can’t be changed via web.config), now I am getting 200 OK.

A good explanation of the error at: https://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/7e0d74d3-ca01-4d36-8ac7-6b2ca03fd383.mspx?mfr=true


问:
How can I use long options with the Bash getopts builtin?
I am trying to parse a -temp option with Bash getopts. I'm calling my script like this:

```<code>./myscript -temp /foo/bar/someFile
</code>```

Here is the code I'm using to parse the options.

```<code>while getopts "temp:shots:o:" option; do
    case $option in
        temp) TMPDIR="$OPTARG" ;;
        shots) NUMSHOTS="$OPTARG" ;;
        o) OUTFILE="$OPTARG" ;;
        *) usage ;;
    esac
done
shift $(($OPTIND - 1))

[ $# -lt 1 ] && usage
</code>```

答:
thanks to @mcoolive .

I was able to use your $@ idea to convert whole word and long options to single letter options. Wanted to note to anyone using this idea that I also had to include shift $(expr $OPTIND - 1) prior to running the arguments through the getopts loop.

Totally different purpose but this is working well.

```<code># convert long word options to short word for ease of use and portability

for argu in "$@"; do
  shift
  #echo "curr arg = $1"
  case "$argu" in
"-start"|"--start")
                   # param=param because no arg is required
                   set -- "$@" "-s"
                   ;;
"-pb"|"--pb"|"-personalbrokers"|"--personalbrokers")
                   # pb +arg required
                   set -- "$@" "-p $1"; #echo "arg=$argu"
                   ;;
"-stop"|"--stop")
                   # param=param because no arg is required
                   set -- "$@" "-S"
                   ;;
                #  the catch all option here removes all - symbols from an
                #  argument. if an option is attempted to be passed that is
                #  invalid, getopts knows what to do...
               *)  [[ $(echo $argu | grep -E "^-") ]] && set -- "$@" "${argu//-/}" || echo "no - symbol. not touching $argu" &>/dev/null
                   ;;
esac
done

#echo -e "\n final option conversions = $@\n"
# remove options from positional parameters for getopts parsing
shift $(expr $OPTIND - 1)

declare -i runscript=0
# only p requires an argument hence the p:
 while getopts "sSp:" param; do
[[ "$param" == "p" ]] && [[ $(echo $OPTARG | grep -E "^-") ]] && funcUsage "order"
#echo $param
#echo "OPTIND=$OPTIND"
case $param in
s)
       OPTARG=${OPTARG/ /}
       getoptsRan=1
       echo "$param was passed and this is it's arg $OPTARG"
       arg0=start
       ;;
 p)
       OPTARG=${OPTARG/ /}
       getoptsRan=1
       echo "$param was passed and this is it's arg $OPTARG"
       [[ "$OPTARG" == "all" ]] && echo -e "argument \"$OPTARG\" accepted. continuing." && (( runscript += 1 )) || usage="open"
       [[ $( echo $pbString | grep -w "$OPTARG" ) ]] && echo -e "pb $OPTARG was validated. continuing.\n" && (( runscript += 1 )) || usage="personal"
       [[ "$runscript" -lt "1" ]] && funcUsage "$usage" "$OPTARG"
       arg0=start
       ;;
S)
       OPTARG=${OPTARG/ /}
       getoptsRan=1
       echo "$param was passed and this is it's arg $OPTARG"
       arg0=stop
       ;;
*)
       getoptsRan=1
       funcUsage
       echo -e "Invalid argument\n"
       ;;
esac
done
funcBuildExcludes "$@"
shift $((OPTIND-1))
</code>```

Body:
I am trying to parse a -temp option with Bash getopts. I'm calling my script like this:

./myscript -temp /foo/bar/someFile

Here is the code I'm using to parse the options.

while getopts "temp:shots:o:" option; do
    case $option in
        temp) TMPDIR="$OPTARG" ;;
        shots) NUMSHOTS="$OPTARG" ;;
        o) OUTFILE="$OPTARG" ;;
        *) usage ;;
    esac
done
shift $(($OPTIND - 1))

[ $# -lt 1 ] && usage

Body:
thanks to @mcoolive .

I was able to use your $@ idea to convert whole word and long options to single letter options. Wanted to note to anyone using this idea that I also had to include shift $(expr $OPTIND - 1) prior to running the arguments through the getopts loop.

Totally different purpose but this is working well.

# convert long word options to short word for ease of use and portability

for argu in "$@"; do
  shift
  #echo "curr arg = $1"
  case "$argu" in
"-start"|"--start")
                   # param=param because no arg is required
                   set -- "$@" "-s"
                   ;;
"-pb"|"--pb"|"-personalbrokers"|"--personalbrokers")
                   # pb +arg required
                   set -- "$@" "-p $1"; #echo "arg=$argu"
                   ;;
"-stop"|"--stop")
                   # param=param because no arg is required
                   set -- "$@" "-S"
                   ;;
                #  the catch all option here removes all - symbols from an
                #  argument. if an option is attempted to be passed that is
                #  invalid, getopts knows what to do...
               *)  [[ $(echo $argu | grep -E "^-") ]] && set -- "$@" "${argu//-/}" || echo "no - symbol. not touching $argu" &>/dev/null
                   ;;
esac
done

#echo -e "\n final option conversions = $@\n"
# remove options from positional parameters for getopts parsing
shift $(expr $OPTIND - 1)

declare -i runscript=0
# only p requires an argument hence the p:
 while getopts "sSp:" param; do
[[ "$param" == "p" ]] && [[ $(echo $OPTARG | grep -E "^-") ]] && funcUsage "order"
#echo $param
#echo "OPTIND=$OPTIND"
case $param in
s)
       OPTARG=${OPTARG/ /}
       getoptsRan=1
       echo "$param was passed and this is it's arg $OPTARG"
       arg0=start
       ;;
 p)
       OPTARG=${OPTARG/ /}
       getoptsRan=1
       echo "$param was passed and this is it's arg $OPTARG"
       [[ "$OPTARG" == "all" ]] && echo -e "argument \"$OPTARG\" accepted. continuing." && (( runscript += 1 )) || usage="open"
       [[ $( echo $pbString | grep -w "$OPTARG" ) ]] && echo -e "pb $OPTARG was validated. continuing.\n" && (( runscript += 1 )) || usage="personal"
       [[ "$runscript" -lt "1" ]] && funcUsage "$usage" "$OPTARG"
       arg0=start
       ;;
S)
       OPTARG=${OPTARG/ /}
       getoptsRan=1
       echo "$param was passed and this is it's arg $OPTARG"
       arg0=stop
       ;;
*)
       getoptsRan=1
       funcUsage
       echo -e "Invalid argument\n"
       ;;
esac
done
funcBuildExcludes "$@"
shift $((OPTIND-1))


问:
Error handling in spring integration
I have three different systems. I am using Spring integration to sync data in all these system.

System 1 calls --- > System 2 via http:inbound gateway

```<code><int-http:inbound-gateway id="gateway"
    path="/save" supported-methods="POST, PUT"
    request-channel="requestChannel" reply-channel="replyChannel"
    request-payload-type="com.model.Request"
    mapped-request-headers="source" error-channel="errorChannel" />
</code>```

System 2 will call service method to persist data which returns response if request is valid else throws exception

```<code><int:service-activator ref="serviceMethod"
    method="saveIfValid" input-channel="requestChannel"
    output-channel="serviceOutput" />

<int:recipient-list-router id="id1"
    input-channel="serviceOutput">
    <int:recipient channel="system1" />
    <int:recipient channel="system3" />
</int:recipient-list-router>
</code>```

I need to send service method response to system 1 and system 3 only if operation is successful.
 After calling service method, based on service method response, request for system 3 will be generated using transformer. After transformer I am putting request in mq queue.

```<code><int:transformer id="transformer1"
    method="convert" input-channel="system3"
    output-channel="jmsInput">
    <bean
        class="com.transformer.System3Transformer" />
</int:transformer>

<int-jms:outbound-channel-adapter id="adapter"
    channel="jmsInput" destination-name="queueName">
</int-jms:outbound-channel-adapter>
</code>```

Updated JMS outbound code

<int-jms:outbound-channel-adapter id="jms1"
  channel="jmsIn" destination-name="queueName">
  <int-jms:request-handler-advice-chain>
   <bean
    class="org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice">
     <property name="onSuccessExpression" value="T(Boolean).TRUE" />
    <property name="successChannelName" value="afterSuccessDeleteChannel" />
       <property name="onFailureExpression" value="T(Boolean).FALSE" />
    <property name="failureChannelName" value="afterFailRenameChannel" />
   </bean>
  </int-jms:request-handler-advice-chain>
 </int-jms:outbound-channel-adapter>```

My question is

if service class fails I need to send error response and stop the flow

if service method successful persisted data, but transformation fails, system 1 should get success response and error should be logged.

Here as I am using error channel in outbound adapter, even if error occurs in transformer it is returned to system 1.

please suggest how can i  handle error without using global error channel and how to handle error in jms outbound adapter.

thank you for answering my quesion

答:
For the first case you should really just rely on the exception propagation - the flow stops and error is sent to the system1 as an HTTP response.

For the second (transformer) case you should take a look into the ExpressionEvaluatingRequestHandlerAdvice and use it with the <request-handler-advice-chain> for the <transformer>.

The same can be applied for the <int-jms:outbound-channel-adapter>, if you should acknowledge to the system1.

http://docs.spring.io/spring-integration/reference/html/messaging-endpoints-chapter.html#expression-advice

https://github.com/spring-projects/spring-integration-samples/tree/master/intermediate/retry-and-more

Title: Error handling in spring integration

Body:
I have three different systems. I am using Spring integration to sync data in all these system.

System 1 calls --- > System 2 via http:inbound gateway

<int-http:inbound-gateway id="gateway"
    path="/save" supported-methods="POST, PUT"
    request-channel="requestChannel" reply-channel="replyChannel"
    request-payload-type="com.model.Request"
    mapped-request-headers="source" error-channel="errorChannel" />

System 2 will call service method to persist data which returns response if request is valid else throws exception

<int:service-activator ref="serviceMethod"
    method="saveIfValid" input-channel="requestChannel"
    output-channel="serviceOutput" />

<int:recipient-list-router id="id1"
    input-channel="serviceOutput">
    <int:recipient channel="system1" />
    <int:recipient channel="system3" />
</int:recipient-list-router>

I need to send service method response to system 1 and system 3 only if operation is successful.
 After calling service method, based on service method response, request for system 3 will be generated using transformer. After transformer I am putting request in mq queue.

<int:transformer id="transformer1"
    method="convert" input-channel="system3"
    output-channel="jmsInput">
    <bean
        class="com.transformer.System3Transformer" />
</int:transformer>

<int-jms:outbound-channel-adapter id="adapter"
    channel="jmsInput" destination-name="queueName">
</int-jms:outbound-channel-adapter>

Updated JMS outbound code

<int-jms:outbound-channel-adapter id="jms1"
  channel="jmsIn" destination-name="queueName">
  <int-jms:request-handler-advice-chain>
   <bean
    class="org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice">
     <property name="onSuccessExpression" value="T(Boolean).TRUE" />
    <property name="successChannelName" value="afterSuccessDeleteChannel" />
       <property name="onFailureExpression" value="T(Boolean).FALSE" />
    <property name="failureChannelName" value="afterFailRenameChannel" />
   </bean>
  </int-jms:request-handler-advice-chain>
 </int-jms:outbound-channel-adapter>

My question is

if service class fails I need to send error response and stop the flow

if service method successful persisted data, but transformation fails, system 1 should get success response and error should be logged.

Here as I am using error channel in outbound adapter, even if error occurs in transformer it is returned to system 1.

please suggest how can i  handle error without using global error channel and how to handle error in jms outbound adapter.

thank you for answering my quesion


问:
ViewComponents in Areas
I may be doing this wrong (I cannot find any documentation on how to do it any other way).
When you create a ViewComponent in an Area, the Search paths are incorrect:

```<code>namespace HelloWorld
{
    [Area("Test")]
    public class HelloViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
            return View();
        }
    }
}
</code>```

Instead of searching for the view at /Areas/Test/Views/Components/Hello/Default.cshtml the following exception is thrown:

```<code>InvalidOperationException: The view 'Components/Hello/Default' was not found. The following locations were searched:
/Views/Home/Components/Hello/Default.cshtml
/Views/Shared/Components/Hello/Default.cshtml.
</code>```

I am invoking the view by doing the following: (in /Views/Home/Index.cshtml)

```<code>@Component.Invoke("Hello")
</code>```

There does not seem to be a way to include an area to invoke the view from.

Any ideas on either the correct way to invoke a ViewComponent from within an Area or if the above is incorrect and I am making a mistake.

https://github.com/aspnet/Mvc/issues/2640

答:
The ViewComponents files should be placed as below:

Then invoke from the View:

```<code>@await Component.InvokeAsync(typeof(Swastika.Web.Start.Areas.Portal.ViewComponents.MainSidebar));
</code>```

This works for me. I hope it helps!

Title: ViewComponents in Areas

Body:
I may be doing this wrong (I cannot find any documentation on how to do it any other way).
When you create a ViewComponent in an Area, the Search paths are incorrect:

namespace HelloWorld
{
    [Area("Test")]
    public class HelloViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
            return View();
        }
    }
}

Instead of searching for the view at /Areas/Test/Views/Components/Hello/Default.cshtml the following exception is thrown:

InvalidOperationException: The view 'Components/Hello/Default' was not found. The following locations were searched:
/Views/Home/Components/Hello/Default.cshtml
/Views/Shared/Components/Hello/Default.cshtml.

I am invoking the view by doing the following: (in /Views/Home/Index.cshtml)

@Component.Invoke("Hello")

There does not seem to be a way to include an area to invoke the view from.

Any ideas on either the correct way to invoke a ViewComponent from within an Area or if the above is incorrect and I am making a mistake.

https://github.com/aspnet/Mvc/issues/2640

Body:
The ViewComponents files should be placed as below:

Then invoke from the View:

@await Component.InvokeAsync(typeof(Swastika.Web.Start.Areas.Portal.ViewComponents.MainSidebar));

This works for me. I hope it helps!

ContentLicense: CC BY-SA 4.0


问:
Add/removing div block jQuery
I'm writing a script to add div block after clicking the add button.

Everything is fine, however after adding second block that incrementing.

For example: After second clicking that adding 4 block overall 6.

After clicking the removing that is deleting the last one also.

```<code>var removeBtn = $("#removeField");
$("body").on("click", "#addField", function(e) {
  e.preventDefault();

  var room = $(".room-type").first();
  var count = removeBtn.data("count");

  if (count > 0) {
    removeBtn.data("count", count++).attr("data-count", count++);
  } else {
    removeBtn.data("count", 1).attr("data-count", 1);
  }

  room.clone(false).appendTo(".room-type");
});

$("body").on("click", "#removeField:not([data-count=0])", function(e) {
  e.preventDefault();
  var count = removeBtn.data("count");

  if (count > 0) {

    $(".room-type").data("count", count--).attr("data-count", count--).last().remove();
  }
});
</code>```

HTML

```<code><div class="form_element select room-type">

    <div class="duo_left">
    <label class="form_name"><?=pll__('Room type')?></label>
    <select name="room-type[]" class="selectpicker multi-fields">
    <?if($single != null) :?>
    <option value="Single Room">Single Room</option>
<? endif; ?>
<?if($double != null) :?>
<option value="Single Room">Double Room</option>
<? endif; ?>
<?if($deluxe != null) :?>
<option value="Single Room">Deluxe Room</option>
<? endif; ?>
<?if($deluxe_double != null) :?>
<option value="Single Room">Deluxe Double Room</option>
<? endif; ?>
<?if($executive_room != null) :?>
<option value="Single Room">Deluxe Double Room</option>
<? endif; ?>
<?if($gloria_room != null) :?>
<option value="Single Room">Gloria Room</option>
<? endif; ?>
</select>
</div>

<div class="duo_right">
<label class="form_name"><?=pll__('Number')?></label>
<select name="room-number[]" class="selectpicker multi-fields">
<option value="0" selected>0</option>
<? for ($i=1; $i<=10; $i++) : ?>
<option value="<?=$i?>"><?=$i?></option>
<? endfor; ?>
<option value="10+">10+</option>
</select>
</div>
</div>
</code>```

答:
you need to append to a parent div, add an additional div

like "container" on top of your "room-type"
and append your clone to it

```<code>room.clone().appendTo("#container");
</code>```

also before removing check the length of your "room-type" class

here is a working fiddle for you

https://jsfiddle.net/fxabnk4o/12/

Title: Add/removing div block jQuery

Body:
I'm writing a script to add div block after clicking the add button.

Everything is fine, however after adding second block that incrementing.

For example: After second clicking that adding 4 block overall 6.

After clicking the removing that is deleting the last one also.

var removeBtn = $("#removeField");
$("body").on("click", "#addField", function(e) {
  e.preventDefault();

  var room = $(".room-type").first();
  var count = removeBtn.data("count");

  if (count > 0) {
    removeBtn.data("count", count++).attr("data-count", count++);
  } else {
    removeBtn.data("count", 1).attr("data-count", 1);
  }

  room.clone(false).appendTo(".room-type");
});

$("body").on("click", "#removeField:not([data-count=0])", function(e) {
  e.preventDefault();
  var count = removeBtn.data("count");

  if (count > 0) {

    $(".room-type").data("count", count--).attr("data-count", count--).last().remove();
  }
});

HTML

    <?=pll__('Room type')?>
    <select name="room-type[]" class="selectpicker multi-fields">
    <?if($single != null) :?>
    <option value="Single Room">Single Room</option>
<? endif; ?>
<?if($double != null) :?>
<option value="Single Room">Double Room</option>
<? endif; ?>
<?if($deluxe != null) :?>
<option value="Single Room">Deluxe Room</option>
<? endif; ?>
<?if($deluxe_double != null) :?>
<option value="Single Room">Deluxe Double Room</option>
<? endif; ?>
<?if($executive_room != null) :?>
<option value="Single Room">Deluxe Double Room</option>
<? endif; ?>
<?if($gloria_room != null) :?>
<option value="Single Room">Gloria Room</option>
<? endif; ?>
</select>

<?=pll__('Number')?>
<select name="room-number[]" class="selectpicker multi-fields">
<option value="0" selected>0</option>
<? for ($i=1; $i<=10; $i++) : ?>
<option value="<?=$i?>"><?=$i?></option>
<? endfor; ?>
<option value="10+">10+</option>
</select>

Body:
you need to append to a parent div, add an additional div

like "container" on top of your "room-type"
and append your clone to it

room.clone().appendTo("#container");

also before removing check the length of your "room-type" class

here is a working fiddle for you

https://jsfiddle.net/fxabnk4o/12/


问:
How can I represent a range in Java?
Let's say an integer should be within the range: [0...2147483647]

I want to check whether an integer variable falls within this range. I know it can be accomplished by a simple if-else statement, but is there a more efficient way to check whether it's within the range?

I'd rather not do this:

```<code>if (foo >= 0 && foo <= 2147483647)
{
    // do something
}
</code>```

答:
I know this is quite an old question, but with Java 8's Streams you can get a range of ints like this:

```<code>// gives an IntStream of integers from 0 through Integer.MAX_VALUE
IntStream.rangeClosed(0, Integer.MAX_VALUE);
</code>```

Then you can do something like this:

```<code>if (IntStream.rangeClosed(0, Integer.MAX_VALUE).matchAny(n -> n == A)) {
    // do something
} else {
    // do something else
}
</code>```

Title: How can I represent a range in Java?

Body:
Let's say an integer should be within the range: [0...2147483647]

I want to check whether an integer variable falls within this range. I know it can be accomplished by a simple if-else statement, but is there a more efficient way to check whether it's within the range?

I'd rather not do this:

if (foo >= 0 && foo <= 2147483647)
{
    // do something
}

Body:
I know this is quite an old question, but with Java 8's Streams you can get a range of ints like this:

// gives an IntStream of integers from 0 through Integer.MAX_VALUE
IntStream.rangeClosed(0, Integer.MAX_VALUE);

Then you can do something like this:

if (IntStream.rangeClosed(0, Integer.MAX_VALUE).matchAny(n -> n == A)) {
    // do something
} else {
    // do something else
}


问:
Difference in features between WildFly 8.2 and WildFly 10
I have to document main configuration related features that are present in wildfly 10 but not in 8.2 (as we are moving from 8.2 to 10).

I am trying to find the feature documentation but all I find is admin and developer guide. To find the difference between two versions, I have to compare guides of both of these two version, which may take some time.

Can any body suggest me some faster way to do this.

Many Thanks in advance.
Rahul

答: There are likely some blog posts on some highlights at wildfly.org. You could also run a JIRA release notes report. Other than that it just depends on what kinds of differences you're looking for.</p>


问:
Issue with IE11 multi-height TH and positioning of pseudo elements
I am trying to add few icons on the  by putting them to position: relative and then positioning the icons as ::after pseudo element using position: absolute inside the  and giving the icons as background (since they are sprites). This works perfectly in Google Chrome and Firefox, but not in Internet Explorer.

Here's the snippet that demonstrates the problem (which is reproducible only in Internet Explorer, my version 11):

* {font-family: 'Segoe UI';}
.arrow {border: 1px solid #ccc; padding: 5px; line-height: 1; background-color: #00f; color: #fff; position: relative; cursor: pointer; padding-right: 20px;}
.arrow-normal::after {width: 9px; height: 12px; margin-top: -6px;}
.arrow-up::after {width: 9px; height: 6px; margin-top: -3px;}
.arrow-down::after {width: 9px; height: 6px; margin-top: -3px; background-position: 0 -6px;}
.arrow::after {
  top: 50%;
  position: absolute;
  right: 5px;
  content: ' ';
  display: block;
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAMCAYAAABiDJ37AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAnZJREFUeNpsk99rUmEYx1/l+Hvmj8HwQgQvvHKS0LqJQCOIMnTmqOb8UTfdDjb/iYneDAaCIhgSE/NnTOZNMAapkCFYbMEIuiswaHPq5tHj6XlsR3TsCw/nfR/e9/M+vw4RCAQEDWW325+0Wq0fDofDKhKJyMLCwthYlh1btVolpVKJHB4eklgsdlur1X4LBALPCoUCSSaTJJvNkgnM6XTaz0FwkYVP2+VyPRIKhTPASqVCDg4OSCQSWZqfn/8F11h4uLe5ufk8l8v9B6JWVlacl5eXF+yUOp3OOfjHUA7YbDbJzs7Oklqt/o0wziiKotfX11fL5TIha2trL/v9Ps3eIIB2fT7fMgeMx+P35+bm/kzDpozZ2Njw8xqNxkeDwXC32+22eSByJQTKZLJbJycnn81m80P0QRneQcp2uVz+F7aTsyjIUKbX65s8t9st1Gg0gsFgwE7BCLKhvryzs7MBREajv16vU0qlUsDn81kOeHV2vO/1egxlMpkYm82GL5DrwvpBRAy3h1qNisXigGvktCAgsri4OKJgVEqwuAOOzrUzLFyUSySSL7B+jI6tra14Pp9/ClGeQmQzKUN0MqPR+JVsb2/7R6MRc1NThsNhP5FIvOCasre390ChUJze1BRMOxgMvsGRIdFodBUinOk0TdO9VCrlgBmbjA08QPb39++pVKqZTkNNmVAo9Ap+CsKXSqU4sCmYfA9ALjB8/GYymdWjo6MPYrF4khY0iFit1sru7u4yDDZCsXE0wF57vd637Xab8NGJ0Fqt9h4idcOln+l02nV8fDwDQ2HnEWqxWD7BGZtOp/seDof9Ho8niTDM4p8AAwB6jpihgDknYAAAAABJRU5ErkJggg==");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th class="arrow arrow-normal">Two Line<br />Column</th>
      <th class="arrow arrow-up">Single</th>
      <th class="arrow arrow-down">Three<br />Line<br />Column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Item 1</td>
      <td>Item 2</td>
      <td>Item 3</td>
    </tr>
  </tbody>
</table></code>```

When I run this in Google Chrome, I get the expected output:

All the icons in Google Chrome are aligned perfectly in middle.

Whereas, in Internet Explorer, the problem is, all the  elements take the right height, when they have different contents, but the positioning is messed up.

What I see is that, in Internet Explorer, the heights are calculated right, but for position, the initial heights before adjusting the tables are taken into account. Is there anything that can be done to fix this?

Note 1: I have also looked into IE vertical centering bug with table-cell parent and absolutely positioned pseudo-element, which requires me to use another element and give position: relative, but this is not possible in my case as my HTML is fixed and can't be changed. It is generated by an enterprise application, which I have no control over.

Note 2: Since I already know the heights of each element, I am using the negative margin technique.

Please let me know if this is possible.

答:
Despite what I said in chat earlier, here's what I wrangled up. It's still not using sprites and positioning, but it might be worth something/helpful to someone:

If you are just wanting arrows, you can use elements instead of replaced content like images. In addition to not using sprites, it also doesn't use any position properties. It's still ugly, and includes more convoluted markup, but at least it works in IE11 (you can adjust margins as needed) and you can click/interact with the arrows more easily than you can as background-images:

.arrow {
    border: 1px solid #ccc;
    padding: 5px;
    line-height: 1;
    background-color: #00f;
    color: #fff;
    cursor: pointer;
    padding-right: 20px;
}
.arrow > p {
    display: inline-block;
    margin: 0;
}
.arrow:last-child > p:last-child {
    margin: 16px 0;
}
.arrow-up {
    border-bottom: 5px solid white;
    margin-left: 5px;
}
.arrow-down {
    border-top: 5px solid white;
}
*[class^="arrow-"] {
    display: inline-block;
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
    <thead>
        <tr>
            <th class="arrow">
                <p>Two Line
                    <br />Column</p>
                <p style="margin: 0;"><span class="arrow-up"></span>
                   <br> <span class="arrow-down"></span></p>
            </th>
            <th class="arrow">Single<span class="arrow-up"></span></th>
            <th class="arrow">
                <p>Three
                    <br />Line
                    <br />Column</p>
                <p class="arrow-down"></p>
            </th>
        </tr>
    </thead>
</table></code>```

I removed the
 element from my demo as it was irrelevant to the arrow positioning issue.

Body:
I am trying to add few icons on the  by putting them to position: relative and then positioning the icons as ::after pseudo element using position: absolute inside the  and giving the icons as background (since they are sprites). This works perfectly in Google Chrome and Firefox, but not in Internet Explorer.

Here's the snippet that demonstrates the problem (which is reproducible only in Internet Explorer, my version 11):

* {font-family: 'Segoe UI';}
.arrow {border: 1px solid #ccc; padding: 5px; line-height: 1; background-color: #00f; color: #fff; position: relative; cursor: pointer; padding-right: 20px;}
.arrow-normal::after {width: 9px; height: 12px; margin-top: -6px;}
.arrow-up::after {width: 9px; height: 6px; margin-top: -3px;}
.arrow-down::after {width: 9px; height: 6px; margin-top: -3px; background-position: 0 -6px;}
.arrow::after {
  top: 50%;
  position: absolute;
  right: 5px;
  content: ' ';
  display: block;
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAMCAYAAABiDJ37AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAnZJREFUeNpsk99rUmEYx1/l+Hvmj8HwQgQvvHKS0LqJQCOIMnTmqOb8UTfdDjb/iYneDAaCIhgSE/NnTOZNMAapkCFYbMEIuiswaHPq5tHj6XlsR3TsCw/nfR/e9/M+vw4RCAQEDWW325+0Wq0fDofDKhKJyMLCwthYlh1btVolpVKJHB4eklgsdlur1X4LBALPCoUCSSaTJJvNkgnM6XTaz0FwkYVP2+VyPRIKhTPASqVCDg4OSCQSWZqfn/8F11h4uLe5ufk8l8v9B6JWVlacl5eXF+yUOp3OOfjHUA7YbDbJzs7Oklqt/o0wziiKotfX11fL5TIha2trL/v9Ps3eIIB2fT7fMgeMx+P35+bm/kzDpozZ2Njw8xqNxkeDwXC32+22eSByJQTKZLJbJycnn81m80P0QRneQcp2uVz+F7aTsyjIUKbX65s8t9st1Gg0gsFgwE7BCLKhvryzs7MBREajv16vU0qlUsDn81kOeHV2vO/1egxlMpkYm82GL5DrwvpBRAy3h1qNisXigGvktCAgsri4OKJgVEqwuAOOzrUzLFyUSySSL7B+jI6tra14Pp9/ClGeQmQzKUN0MqPR+JVsb2/7R6MRc1NThsNhP5FIvOCasre390ChUJze1BRMOxgMvsGRIdFodBUinOk0TdO9VCrlgBmbjA08QPb39++pVKqZTkNNmVAo9Ap+CsKXSqU4sCmYfA9ALjB8/GYymdWjo6MPYrF4khY0iFit1sru7u4yDDZCsXE0wF57vd637Xab8NGJ0Fqt9h4idcOln+l02nV8fDwDQ2HnEWqxWD7BGZtOp/seDof9Ho8niTDM4p8AAwB6jpihgDknYAAAAABJRU5ErkJggg==");
}

      Two Line
Column
      Single
      Three
Line
Column

      Item 1
      Item 2
      Item 3

When I run this in Google Chrome, I get the expected output:

All the icons in Google Chrome are aligned perfectly in middle.

Whereas, in Internet Explorer, the problem is, all the  elements take the right height, when they have different contents, but the positioning is messed up.

What I see is that, in Internet Explorer, the heights are calculated right, but for position, the initial heights before adjusting the tables are taken into account. Is there anything that can be done to fix this?

Note 1: I have also looked into IE vertical centering bug with table-cell parent and absolutely positioned pseudo-element, which requires me to use another element and give position: relative, but this is not possible in my case as my HTML is fixed and can't be changed. It is generated by an enterprise application, which I have no control over.

Note 2: Since I already know the heights of each element, I am using the negative margin technique.

Please let me know if this is possible.

Body:
Despite what I said in chat earlier, here's what I wrangled up. It's still not using sprites and positioning, but it might be worth something/helpful to someone:

If you are just wanting arrows, you can use elements instead of replaced content like images. In addition to not using sprites, it also doesn't use any position properties. It's still ugly, and includes more convoluted markup, but at least it works in IE11 (you can adjust margins as needed) and you can click/interact with the arrows more easily than you can as background-images:

.arrow {
    border: 1px solid #ccc;
    padding: 5px;
    line-height: 1;
    background-color: #00f;
    color: #fff;
    cursor: pointer;
    padding-right: 20px;
}
.arrow > p {
    display: inline-block;
    margin: 0;
}
.arrow:last-child > p:last-child {
    margin: 16px 0;
}
.arrow-up {
    border-bottom: 5px solid white;
    margin-left: 5px;
}
.arrow-down {
    border-top: 5px solid white;
}
*[class^="arrow-"] {
    display: inline-block;
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
}

<table>
    <thead>
        <tr>
            <th class="arrow">
                <p>Two Line
                    <br />Column</p>
                <p style="margin: 0;"><span class="arrow-up"></span>
                   <br>&nbsp;<span class="arrow-down"></span></p>
            </th>
            <th class="arrow">Single<span class="arrow-up"></span></th>
            <th class="arrow">
                <p>Three
                    <br />Line
                    <br />Column</p>
                <p class="arrow-down"></p>
            </th>
        </tr>
    </thead>
</table>

I removed the <tbody> element from my demo as it was irrelevant to the arrow positioning issue.


问:
Access object key with a string value
I have a hand-typed database with an object that has categories and a list of words for each category, as below:

```<code>var words =
{
    sports: [
        'baseball', 'football', 'volleyball', 'basketball', 'soccer'],

    animals: [
        'dog', 'cat', 'elephant', 'crocodile', 'bird'],

    entertainment: [
        'netflix', 'movies', 'music', 'concert', 'band', 'computer']
}
</code>```

My HTML has a bootstrap dropdown that will display all categories based on that list. I have the code working to give me the value of the category clicked as a string: as below:

```<code>$(document).on('click', '.dropdown-menu li a', function () {
    var selectedCategory;

    selectedCategory = $(this).text();
    //setting value of category to global variable
    categorySelected = selectedCategory;
});
</code>```

I need to be able to find the key in my database from that value.
The problem is that I can't access words."animals"
I need to take the quotation marks off my string to get the list of words like this:
words.animals

How do I do this? I've tried replace() but it doesn't work.

答:
You can pass the text(selected value from drop down) to a function to find the key

var words = {
  sports: [
    'baseball', 'football', 'volleyball', 'basketball', 'soccer'
  ],

  animals: [
    'dog', 'cat', 'elephant', 'crocodile', 'bird'
  ],

  entertainment: [
    'netflix', 'movies', 'music', 'concert', 'band', 'computer'
  ]
}
// function to find the key
function findKey(selText) {
 //loop through the object
  for (var keys in words) {
 //get the array
    var getArray = words[keys]
  //inside each array check if the selected text is present using index of
    if (getArray.indexOf(selText) !== -1) {
      console.log(keys)
    }

  }
}

findKey('music')```

Title: Access object key with a string value

Body:
I have a hand-typed database with an object that has categories and a list of words for each category, as below:

var words =
{
    sports: [
        'baseball', 'football', 'volleyball', 'basketball', 'soccer'],

    animals: [
        'dog', 'cat', 'elephant', 'crocodile', 'bird'],

    entertainment: [
        'netflix', 'movies', 'music', 'concert', 'band', 'computer']
}

My HTML has a bootstrap dropdown that will display all categories based on that list. I have the code working to give me the value of the category clicked as a string: as below:

$(document).on('click', '.dropdown-menu li a', function () {
    var selectedCategory;

    selectedCategory = $(this).text();
    //setting value of category to global variable
    categorySelected = selectedCategory;
});

I need to be able to find the key in my database from that value.
The problem is that I can't access words."animals"
I need to take the quotation marks off my string to get the list of words like this:
words.animals

How do I do this? I've tried replace() but it doesn't work.