问:
Unable to dinamically create objects from MongoDB results in Python 3.5.2
I'm pretty new to Python even though I have some OOP experience from working with PHP in the past.

I'm trying to create a module that will query mongoDB and create objects in a dictionary for every document it gets back from the db. The documents data will generate entries in the object's attributes dictionary.

```<code>#!/usr/bin/python3
from django.db import models
from pymongo import MongoClient

# abstract Class() blueprint
class Clase():
    attributes = {}

mongodb_connection = MongoClient('mongodb://localhost:27017/')
bi_db = mongodb_connection['bi']
sales_collection = bi_db['sales_data_it']
documents = sales_collection.find( {} )
print ('Documents: %d' % documents.count())

# Create instances from mongoDB documents
instance_dict = {}
i = 0
for result in documents:
    print('+++++++++++++++++++++++++++++')
    print('creating instance[%d]' % i)
    instance_dict[i] = Clase()  # create an object in instance_dict for each result

    for key, value in result.items() : # for every result log key,values into attributes dictionary
        print(result)
        instance_dict[i].attributes[key] = value
        print(key, ' = ', value, i)
    i += 1

# print ('Instances Created: %d' % len(instance_dict.keys()))
print('-------------INSTANCE 0--------------------')
print(instance_dict[0].attributes)
print('-------------INSTANCE 1--------------------')
print(instance_dict[1].attributes)
</code>```

My test database contains only 2 documents and the logic appears to work when debugging this code using the print() function. However, when reading the created objects attributes I see that they both contain the data for the second document instead of each containing the data for their respective document. Not sure if that made sense. Here's the output from my terminal when running this script:

```<code>root@django:~/Desktop/scripts# ./test.py
Documents: 2
+++++++++++++++++++++++++++++
creating instance[0]
Members  =  ['Marco Ravaglia', 'Mattia Castelluccia', 'Alberto Ballerini'] 0
_id  =  58d8e4492b9afb1045503665 0
Performance  =  0.85 0
Team Name  =  NCA-Milan 0
+++++++++++++++++++++++++++++
creating instance[1]
Team Leader  =  Isidoro De Pascale 1
Members  =  ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri'] 1
_id  =  58d8e4492b9afb1045503666 1
Team Name  =  NCA-Napoli 1
-------------INSTANCE 0--------------------
{'Team Leader': 'Isidoro De Pascale', 'Members': ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri'], '_id': ObjectId('58d8e4492b9afb1045503666'), 'Performance': '0.85', 'Team Name': 'NCA-Napoli'}
-------------INSTANCE 1--------------------
{'Team Leader': 'Isidoro De Pascale', 'Members': ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri'], '_id': ObjectId('58d8e4492b9afb1045503666'), 'Performance': '0.85', 'Team Name': 'NCA-Napoli'}
</code>```

As you can see both instances contain the same data. I dont understand why...
Sorry if this has been asked before but I've looked for an answer to this problem without success. I've also made my best to debug the problem but I just can't get to the bottom of it. I'm going crazy so any help would be greatly appreciated.

Thanks in advance!!!

答:
Turns out I was setting the attributes dict as a 'Class' variable instead of an 'Instance' variable. Therefore they were being overwritten by each object iteration.

I solved this by creating getter and setter methods that will deal with this variables on a per instance basis. Note that I decided to mangle the variables dict even though I read somewhere that this is not the "Python way" of doing things. I had to throw in a generator method to yield the contents of the variables_dict when needed as well.

```<code>#!/usr/bin/python3
from pymongo import MongoClient

def get_mongoDb_collection(conn, db, col):
    mongodb_connection = MongoClient(conn)
    database = mongodb_connection[db]
    collection = database[col]
    return collection

class Clase:
    def __init__(self, **kwargs):
        self.__variables = kwargs

    def set_variable(self, k, v):
        self.__variables[k] = v

    def get_variable(self, k):
        # return self.__variables[k] # raises KeyError exception if key doesn't exist, the get() method below returns None
        return self.__variables.get(k, '"{}" variable NOT Found'.format(k)) # returns None if default value NOT specified

    def get_all_variables(self):
        for k,v in self.__variables.items():
            yield k,v

def main():
    sales_collection = get_mongoDb_collection('mongodb://localhost:27017/', 'bi', 'sales_data_it')
    documents = sales_collection.find( {} )
    print ('Found Documents: {}'.format(documents.count()))

    instance_dict = {}
    i = 0
    for result in documents:
        print('+++++++++++++++++++ Creating instance[{}] +++++++++++++++++++'.format(i))
        # print(result)
        instance_dict[i] = Clase()  # create an object in instance_dict for each result
        for key, value in result.items() : # for every result log key,values into variables dictionary
            print(' {}= {}'.format(key, value))
            instance_dict[i].set_variable(key, value)
        i += 1

    print('------------------- Inspecting created instances -------------------')
    for key, instance in instance_dict.items():
        print(' ... Instance {} ...'.format(key))
        for key, value in instance.get_all_variables():
            print(' {}= {}'.format(key,value))

if __name__ == "__main__": main()
</code>```

Running this script now returns the expected objects with the correct data:

```<code>Found Documents: 2
+++++++++++++++++++ Creating instance[0] +++++++++++++++++++
    _id= 58d8e4492b9afb1045503665
    Team Name= NCA-Milan
    Performance= 0.85
    Members= ['Marco Ravaglia', 'Mattia Castelluccia', 'Alberto Ballerini']
+++++++++++++++++++ Creating instance[1] +++++++++++++++++++
    Team Leader= Isidoro De Pascale
    _id= 58d8e4492b9afb1045503666
    Team Name= NCA-Napoli
    Members= ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri']
------------------- Inspecting created instances -------------------
    ... Instance 0 ...
    Members= ['Marco Ravaglia', 'Mattia Castelluccia', 'Alberto Ballerini']
    _id= 58d8e4492b9afb1045503665
    Team Name= NCA-Milan
    Performance= 0.85
    ... Instance 1 ...
    Members= ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri']
    _id= 58d8e4492b9afb1045503666
    Team Leader= Isidoro De Pascale
    Team Name= NCA-Napoli
</code>```

I still thought to share the answer to my problem in case it may be useful to someone else in the future but rememember that if you really want something done you better do it yourself. Thanks for everything Stack Overflow, or whatever!

Body:
I'm pretty new to Python even though I have some OOP experience from working with PHP in the past.

I'm trying to create a module that will query mongoDB and create objects in a dictionary for every document it gets back from the db. The documents data will generate entries in the object's attributes dictionary.

#!/usr/bin/python3
from django.db import models
from pymongo import MongoClient

# abstract Class() blueprint
class Clase():
    attributes = {}

mongodb_connection = MongoClient('mongodb://localhost:27017/')
bi_db = mongodb_connection['bi']
sales_collection = bi_db['sales_data_it']
documents = sales_collection.find( {} )
print ('Documents: %d' % documents.count())

# Create instances from mongoDB documents
instance_dict = {}
i = 0
for result in documents:
    print('+++++++++++++++++++++++++++++')
    print('creating instance[%d]' % i)
    instance_dict[i] = Clase()  # create an object in instance_dict for each result

    for key, value in result.items() : # for every result log key,values into attributes dictionary
        print(result)
        instance_dict[i].attributes[key] = value
        print(key, ' = ', value, i)
    i += 1

# print ('Instances Created: %d' % len(instance_dict.keys()))
print('-------------INSTANCE 0--------------------')
print(instance_dict[0].attributes)
print('-------------INSTANCE 1--------------------')
print(instance_dict[1].attributes)

My test database contains only 2 documents and the logic appears to work when debugging this code using the print() function. However, when reading the created objects attributes I see that they both contain the data for the second document instead of each containing the data for their respective document. Not sure if that made sense. Here's the output from my terminal when running this script:

root@django:~/Desktop/scripts# ./test.py
Documents: 2
+++++++++++++++++++++++++++++
creating instance[0]
Members  =  ['Marco Ravaglia', 'Mattia Castelluccia', 'Alberto Ballerini'] 0
_id  =  58d8e4492b9afb1045503665 0
Performance  =  0.85 0
Team Name  =  NCA-Milan 0
+++++++++++++++++++++++++++++
creating instance[1]
Team Leader  =  Isidoro De Pascale 1
Members  =  ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri'] 1
_id  =  58d8e4492b9afb1045503666 1
Team Name  =  NCA-Napoli 1
-------------INSTANCE 0--------------------
{'Team Leader': 'Isidoro De Pascale', 'Members': ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri'], '_id': ObjectId('58d8e4492b9afb1045503666'), 'Performance': '0.85', 'Team Name': 'NCA-Napoli'}
-------------INSTANCE 1--------------------
{'Team Leader': 'Isidoro De Pascale', 'Members': ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri'], '_id': ObjectId('58d8e4492b9afb1045503666'), 'Performance': '0.85', 'Team Name': 'NCA-Napoli'}

As you can see both instances contain the same data. I dont understand why...
Sorry if this has been asked before but I've looked for an answer to this problem without success. I've also made my best to debug the problem but I just can't get to the bottom of it. I'm going crazy so any help would be greatly appreciated.

Thanks in advance!!!

Body:
Turns out I was setting the attributes dict as a 'Class' variable instead of an 'Instance' variable. Therefore they were being overwritten by each object iteration.

I solved this by creating getter and setter methods that will deal with this variables on a per instance basis. Note that I decided to mangle the variables dict even though I read somewhere that this is not the "Python way" of doing things. I had to throw in a generator method to yield the contents of the variables_dict when needed as well.

#!/usr/bin/python3
from pymongo import MongoClient

def get_mongoDb_collection(conn, db, col):
    mongodb_connection = MongoClient(conn)
    database = mongodb_connection[db]
    collection = database[col]
    return collection

class Clase:
    def __init__(self, **kwargs):
        self.__variables = kwargs

    def set_variable(self, k, v):
        self.__variables[k] = v

    def get_variable(self, k):
        # return self.__variables[k] # raises KeyError exception if key doesn't exist, the get() method below returns None
        return self.__variables.get(k, '"{}" variable NOT Found'.format(k)) # returns None if default value NOT specified

    def get_all_variables(self):
        for k,v in self.__variables.items():
            yield k,v

def main():
    sales_collection = get_mongoDb_collection('mongodb://localhost:27017/', 'bi', 'sales_data_it')
    documents = sales_collection.find( {} )
    print ('Found Documents: {}'.format(documents.count()))

    instance_dict = {}
    i = 0
    for result in documents:
        print('+++++++++++++++++++ Creating instance[{}] +++++++++++++++++++'.format(i))
        # print(result)
        instance_dict[i] = Clase()  # create an object in instance_dict for each result
        for key, value in result.items() : # for every result log key,values into variables dictionary
            print(' {}= {}'.format(key, value))
            instance_dict[i].set_variable(key, value)
        i += 1

    print('------------------- Inspecting created instances -------------------')
    for key, instance in instance_dict.items():
        print(' ... Instance {} ...'.format(key))
        for key, value in instance.get_all_variables():
            print(' {}= {}'.format(key,value))

if __name__ == "__main__": main()

Running this script now returns the expected objects with the correct data:

Found Documents: 2
+++++++++++++++++++ Creating instance[0] +++++++++++++++++++
    _id= 58d8e4492b9afb1045503665
    Team Name= NCA-Milan
    Performance= 0.85
    Members= ['Marco Ravaglia', 'Mattia Castelluccia', 'Alberto Ballerini']
+++++++++++++++++++ Creating instance[1] +++++++++++++++++++
    Team Leader= Isidoro De Pascale
    _id= 58d8e4492b9afb1045503666
    Team Name= NCA-Napoli
    Members= ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri']
------------------- Inspecting created instances -------------------
    ... Instance 0 ...
    Members= ['Marco Ravaglia', 'Mattia Castelluccia', 'Alberto Ballerini']
    _id= 58d8e4492b9afb1045503665
    Team Name= NCA-Milan
    Performance= 0.85
    ... Instance 1 ...
    Members= ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri']
    _id= 58d8e4492b9afb1045503666
    Team Leader= Isidoro De Pascale
    Team Name= NCA-Napoli

I still thought to share the answer to my problem in case it may be useful to someone else in the future but rememember that if you really want something done you better do it yourself. Thanks for everything Stack Overflow, or whatever!


来源: stackexchange

问:
How to run JavaScript when specific part of page is loaded when AJAX is involved?
I am working on a page where elements are loaded via AJAX, it is a CMS type software and I have no access to the ajax, nor do I know it's callbacks.

I want to run my function when a specific part of the page is loaded, how can I do this when AJAX is involved?

My JavaScript, which works fine by itself: Fiddle:

```<code>var personalitet = document.getElementById("personalitet").innerHTML;
document.getElementsByName("form[5553]")[0].value = personalitet;
</code>```

I have tried:

```<code>document.getElementById("personalitet").onload = function() {

document.addEventListener("DOMContentLoaded", function(event) {

window.onload = function(){
</code>```

None of which work, as the elements are not loaded at the time my script looks for them.

答:
You could use a mutation observer.

```<code>var observer = new MutationObserver(function(mutations) {
    for (var i = 0; i < mutations.length; i++) {
        // PUT ACTIONS HERE
        console.log(mutations[i].type);
    }
});

var observeElements = {
    attributes: true,
    childList: true,
    characterData: true
};

observer.observe(document.body, observeElements);
</code>```

This will let you know when anything in the body has changed. Read more about the MutationObserver if you wanna get fancy.

It's not quick, though, and you should investigate if you could abuse your CMS to not get in your way.
And it needs to call the last line before any mutations occur or it won't work.

ContentLicense: CC BY-SA 3.0

Body:
I am working on a page where elements are loaded via AJAX, it is a CMS type software and I have no access to the ajax, nor do I know it's callbacks.

I want to run my function when a specific part of the page is loaded, how can I do this when AJAX is involved?

My JavaScript, which works fine by itself: Fiddle:

var personalitet = document.getElementById("personalitet").innerHTML;
document.getElementsByName("form[5553]")[0].value = personalitet;

I have tried:

document.getElementById("personalitet").onload = function() {

document.addEventListener("DOMContentLoaded", function(event) {

window.onload = function(){

None of which work, as the elements are not loaded at the time my script looks for them.

Body:
You could use a mutation observer.

var observer = new MutationObserver(function(mutations) {
    for (var i = 0; i < mutations.length; i++) {
        // PUT ACTIONS HERE
        console.log(mutations[i].type);
    }
});

var observeElements = {
    attributes: true,
    childList: true,
    characterData: true
};

observer.observe(document.body, observeElements);

This will let you know when anything in the body has changed. Read more about the MutationObserver if you wanna get fancy.

It's not quick, though, and you should investigate if you could abuse your CMS to not get in your way.
And it needs to call the last line before any mutations occur or it won't work.


问:
enum combination, correct way - vb.net
I have a project in Vb.net and windows form application with dotnet framework 3.5. I am using Emum for storing and processing tasks As :

```<code>Public Enum TaskStatus
        none = 0
        completed = 2
        executing = 4
        executed = 8
        errors = 16      '' Means task got some error in performing some operations
        uploaded = 32
        incomplete = 64  '' Means Task Was Aborted or Process Stopped in between
End Enum
</code>```

One function is processing the task and the other one is Checking its completion status, as

```<code>Private Function Manage()
        Dim ts As TaskStatus = TaskStatus.none
        '' Performing Tasks
        ts = TaskStatus.executing
        '' Task Performed with Error
        ts = TaskStatus.errors Or TaskStatus.executed
        '' Task Uploading
        ts = ts Or TaskStatus.uploaded
        ts = ts Or TaskStatus.completed
        ts = TaskStatus.none
        CheckStatus(ts)
End Function

 Private Function CheckStatus(ByVal ts As TaskStatus)
    ' Now i Want to check
    If ts And (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' Which one of these(Below) is Correct
    End If
    If ts = (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' Which one of these(Above one) is Correct
    End If
    If ts And TaskStatus.incomplete Then
        '' Is it Correct way to check for incompletion
    End If
    If ts And TaskStatus.completed Then
        '' Task is Completed
        '' Is is correct way to check Task Completed
    End If
End Function
</code>```

In the Function CheckStatus, i want to know the correct way to manipulate with enum combinations?

答:
I would say that what you have done here is perfectly fine way of doing so, but if you want to check which of the ones are correct where you are using or, I suggest splitting them up into different if statements.

On top of this, I also suggest using elseif instead of normal if statements after each other, just to safe some time and resource :)

Here is how I would do it:

```<code>Private Function CheckStatus(ByVal ts As TaskStatus)
' Now i Want to check
If ts = TaskStatus.uploaded Then
    'Uploaded
Elseif ts = TaskStatus.errors Then
    'Error
Elseif ts = TaskStatus.incomplete Then
    'Incomplete
Elseif ts = TaskStatus.completed Then
    ' Task is Completed
End If
End Function
</code>```

This is just a quick sketch up of how i'd do it, but if I have misread something, let me know.

Title: enum combination, correct way - vb.net

Body:
I have a project in Vb.net and windows form application with dotnet framework 3.5. I am using Emum for storing and processing tasks As :

Public Enum TaskStatus
        none = 0
        completed = 2
        executing = 4
        executed = 8
        errors = 16      '' Means task got some error in performing some operations
        uploaded = 32
        incomplete = 64  '' Means Task Was Aborted or Process Stopped in between
End Enum

One function is processing the task and the other one is Checking its completion status, as

Private Function Manage()
        Dim ts As TaskStatus = TaskStatus.none
        '' Performing Tasks
        ts = TaskStatus.executing
        '' Task Performed with Error
        ts = TaskStatus.errors Or TaskStatus.executed
        '' Task Uploading
        ts = ts Or TaskStatus.uploaded
        ts = ts Or TaskStatus.completed
        ts = TaskStatus.none
        CheckStatus(ts)
End Function

 Private Function CheckStatus(ByVal ts As TaskStatus)
    ' Now i Want to check
    If ts And (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' Which one of these(Below) is Correct
    End If
    If ts = (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' Which one of these(Above one) is Correct
    End If
    If ts And TaskStatus.incomplete Then
        '' Is it Correct way to check for incompletion
    End If
    If ts And TaskStatus.completed Then
        '' Task is Completed
        '' Is is correct way to check Task Completed
    End If
End Function

In the Function CheckStatus, i want to know the correct way to manipulate with enum combinations?

Body:
I would say that what you have done here is perfectly fine way of doing so, but if you want to check which of the ones are correct where you are using or, I suggest splitting them up into different if statements.

On top of this, I also suggest using elseif instead of normal if statements after each other, just to safe some time and resource :)

Here is how I would do it:

Private Function CheckStatus(ByVal ts As TaskStatus)
' Now i Want to check
If ts = TaskStatus.uploaded Then
    'Uploaded
Elseif ts = TaskStatus.errors Then
    'Error
Elseif ts = TaskStatus.incomplete Then
    'Incomplete
Elseif ts = TaskStatus.completed Then
    ' Task is Completed
End If
End Function

This is just a quick sketch up of how i'd do it, but if I have misread something, let me know.


问:
Bytescout.Spreadsheet Number Formatting Multiplying By 100
I'm currently using the bytescout library to generate a PDF document. Here is some pseudo code of me setting the cell in question:

```<code>cell.Value = 20;
cell.NumberFormatString = "0.00%";
</code>```

When the Excel document is generated the Cell displays as 2000.00%

Does anyone have experience with this library?

答: Simple answer is to divide by 100. Seems Excel expects the % decimal value. The lightbulb eventually came on.</p>

Body:
I'm currently using the bytescout library to generate a PDF document. Here is some pseudo code of me setting the cell in question:

cell.Value = 20;
cell.NumberFormatString = "0.00%";

When the Excel document is generated the Cell displays as 2000.00%

Does anyone have experience with this library?


问:
page rendering takes more time
I have a aspx page which contains 6 user controls which will be displayed when the user clicks on any button using show model pop up extender. My page rendering takes more time. it taked 3 minuits to load the page. If i debug the page its traveling to page load of all the user controls.

Its not taking more time to fetch the data from database but its taking time to load the page. Is there any way to improve the perfomace .

Is there any place where i have to look into.

I am using VS 2010 and c# . Please let me know if you have any questions.

Regards,
Jebli.

答:
This might be page rendering performance problem or something else.
For example, if you have some large loop of dynamically rendered controls (in a repeater, grid, ..) and you accessing the db for couple of easy queries each iteration, it may take much more time than you guess.

Because I never heard that simple control rendering process takes much of time.

So the best way to optimize the code is a line-by-line analysis by using code profiler. Take a look on some of these:

XteProfiler is free

dotTrace gives 30 days for trial, good one

ANTS Profiler yet another profiler

By using a profiler you can find what parts of code gives a performance problems

ContentLicense: CC BY-SA 2.5

Title: page rendering takes more time


问:
Linking Services to components
I am importing my service in my component but for some reason it gives me cannot find module.

Here's my selectHotel.component.ts

```<code>import { Component } from '@angular/core';
import { GetHotelService } from '/src/app/services/gethotel/getHotel.service'; //Error Here

@Component({
    moduleId: module.id,
    selector: 'selectHotel',
    templateUrl: 'selectHotel.component.html',
    providers: [GetHotelService]
})
export class selectHotelComponent  {  }
</code>```

Here's my getHotel.service.ts

```<code>import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
    export class GetHotelService {
        constructor(private http: Http){
            console.log('Init');
        }
    }
</code>```

My project folder view is like this

Proj > src > app > components > selectHotel > selectHotel.component.ts

Proj > src > app > services > gethotel > getHotel.service.ts

What am I doing wrong here?

答:
It's best to use relative paths when importing items you wrote in your project.

so change your GetHotelService import to something like,

```<code>import { GetHotelService } from '../../services/gethotel/getHotel.service';
</code>```

The leading ..  (or ./ in other cases) indicates that this is a relative import.

PS.

Not to be too pedantic, but you may want to look at a different folder structure for your project - it's usually a better idea to group items that are related to a specific feature together, rather than grouping them by type. In other words, put your Hotel service in the same folder with your Hotel component, rather than grouping all your services together and separate from your components.

See the Angular Style guide for more information.

Title: Linking Services to components

Body:
I am importing my service in my component but for some reason it gives me cannot find module.

Here's my selectHotel.component.ts

import { Component } from '@angular/core';
import { GetHotelService } from '/src/app/services/gethotel/getHotel.service'; //Error Here

@Component({
    moduleId: module.id,
    selector: 'selectHotel',
    templateUrl: 'selectHotel.component.html',
    providers: [GetHotelService]
})
export class selectHotelComponent  {  }

Here's my getHotel.service.ts

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
    export class GetHotelService {
        constructor(private http: Http){
            console.log('Init');
        }
    }

My project folder view is like this

Proj > src > app > components > selectHotel > selectHotel.component.ts

Proj > src > app > services > gethotel > getHotel.service.ts

What am I doing wrong here?

Body:
It's best to use relative paths when importing items you wrote in your project.

so change your GetHotelService import to something like,

import { GetHotelService } from '../../services/gethotel/getHotel.service';

The leading ..  (or ./ in other cases) indicates that this is a relative import.

PS.

Not to be too pedantic, but you may want to look at a different folder structure for your project - it's usually a better idea to group items that are related to a specific feature together, rather than grouping them by type. In other words, put your Hotel service in the same folder with your Hotel component, rather than grouping all your services together and separate from your components.

See the Angular Style guide for more information.


问:
Sending boolean as request parameter
In my web application I have a link - "Create New User". From the jsp I am sending some request to the server like -

```<code><div style="float:right" class="view">
 <a href="/some/url/createUserMVC.do?hasCreatePermission=${user.hasPermission['createUser']}">Create New User</a>
</div>
</code>```

Here user.hasPermission[]  is an array of boolean. If the current user (that is user ) has the permission(that is 'createUser') to create an new user than it returns true.

Now from my controller I am trying to get the value from the request parameter, like -

```<code>request.getParameter("hasCreatePermission");
</code>```

But the problem is request.getParameter() returns a String. So how can I get the boolean value from the parameter. There is no overloaded version of request.getParameter() method for boolean.

答:
In servlet it will accept all inputs given by users as string.So, we should parse the input after we got the inputs.

e.g

```<code>boolean flag = Boolean.parseBoolean(req.getParameter("Flag "));
</code>```

I think this will be useful for you.

Title: Sending boolean as request parameter

Body:
In my web application I have a link - "Create New User". From the jsp I am sending some request to the server like -

 Create New User

Here user.hasPermission[]  is an array of boolean. If the current user (that is user ) has the permission(that is 'createUser') to create an new user than it returns true.

Now from my controller I am trying to get the value from the request parameter, like -

request.getParameter("hasCreatePermission");

But the problem is request.getParameter() returns a String. So how can I get the boolean value from the parameter. There is no overloaded version of request.getParameter() method for boolean.

Body:
In servlet it will accept all inputs given by users as string.So, we should parse the input after we got the inputs.

e.g

boolean flag = Boolean.parseBoolean(req.getParameter("Flag "));

I think this will be useful for you.


问:
field cross search in lucene
Hi:
I have two documents:

```<code>title                       body
Lucene In Action            A high-performance, full-featured text search engine library.
Lucene Practice             Use lucene in your application
</code>```

Now,I search "lucene performance" using

```<code>private String[] f = { "title", "body"};
private Occur[] should = { Occur.SHOULD, Occur.SHOULD};
Query q = MultiFieldQueryParser.parse(Version.LUCENE_29, "lucene performance", f, should,new IKAnalyzer());
</code>```

Then I get two hits:
"Lucene In Action" and "Lucene Practice".

However I do not want the "Lucene practice" in the search result.

That's to say,I just want the documents who own all my search terms can be returned,the "lucene parctice" does not contain the term "performance",so it should not be returned.

Any ideas?

答:
Lucene cannot match across fields. That is to say, for the query "a b", it won't match "a" in title and "b" in body. For that you need to create another field, say, all_text, which has title and body both indexed.

Also, when you are searching for "lucene performance" I suppose you are looking for documents that have both the terms - lucene as well as performance. By default, the boolean operator is OR. You need to specify default operator as AND to match all the terms in the query. (Otherwise in this case, the query "lucene performance" will start returning matches that talk about database performance.)

Title: field cross search in lucene

Body:
Hi:
I have two documents:

title                       body
Lucene In Action            A high-performance, full-featured text search engine library.
Lucene Practice             Use lucene in your application

Now,I search "lucene performance" using

private String[] f = { "title", "body"};
private Occur[] should = { Occur.SHOULD, Occur.SHOULD};
Query q = MultiFieldQueryParser.parse(Version.LUCENE_29, "lucene performance", f, should,new IKAnalyzer());

Then I get two hits:
"Lucene In Action" and "Lucene Practice".

However I do not want the "Lucene practice" in the search result.

That's to say,I just want the documents who own all my search terms can be returned,the "lucene parctice" does not contain the term "performance",so it should not be returned.

Any ideas?


问:
word2vec - get nearest words
Reading the tensorflow word2vec model output how can I output the words related to a specific word ?

Reading the src : https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/examples/tutorials/word2vec/word2vec_basic.py can view how the image is plotted.

But is there a data structure (e.g dictionary) created as part of training the model that allows to access nearest n words closest to given word ?
For example if word2vec generated image :

image src: https://www.tensorflow.org/versions/r0.11/tutorials/word2vec/index.html

In this image the words 'to , he , it' are contained in same cluster, is there a function which takes as input 'to' and outputs 'he , it' (in this case n=2) ?

答:
Get gensim and use similar_by_word method on gensim.models.Word2Vec model.

similar_by_word takes 3 parameters,

The input word

n - for top n similar words (optional, default=10)

restrict_vocab (optional, default=None)

Example

```<code>import gensim, nltk

class FileToSent(object):
   """A class to load a text file efficiently """
    def __init__(self, filename):
        self.filename = filename
        # To remove stop words (optional)
        self.stop = set(nltk.corpus.stopwords.words('english'))

    def __iter__(self):
        for line in open(self.filename, 'r'):
            ll = [i for i in unicode(line, 'utf-8').lower().split() if i not in self.stop]
            yield ll
</code>```

Then depending on your input sentences (sentence_file.txt),

```<code>sentences = FileToSent('sentence_file.txt')
model = gensim.models.Word2Vec(sentences=sentences, min_count=2, hs=1)
print model.similar_by_word('hack', 2) # Get two most similar words to 'hack'
# [(u'debug', 0.967338502407074), (u'patch', 0.952264130115509)] (Output specific to my dataset)
</code>```

Title: word2vec - get nearest words

Body:
Get gensim and use similar_by_word method on gensim.models.Word2Vec model.

similar_by_word takes 3 parameters,

The input word

n - for top n similar words (optional, default=10)

restrict_vocab (optional, default=None)

Example

import gensim, nltk

class FileToSent(object):
   """A class to load a text file efficiently """
    def __init__(self, filename):
        self.filename = filename
        # To remove stop words (optional)
        self.stop = set(nltk.corpus.stopwords.words('english'))

    def __iter__(self):
        for line in open(self.filename, 'r'):
            ll = [i for i in unicode(line, 'utf-8').lower().split() if i not in self.stop]
            yield ll

Then depending on your input sentences (sentence_file.txt),

sentences = FileToSent('sentence_file.txt')
model = gensim.models.Word2Vec(sentences=sentences, min_count=2, hs=1)
print model.similar_by_word('hack', 2) # Get two most similar words to 'hack'
# [(u'debug', 0.967338502407074), (u'patch', 0.952264130115509)] (Output specific to my dataset)


问:
aws lambda function getting access denied when getObject from s3
I am getting an acccess denied error from S3 AWS service on my Lambda function.

This is the code:

```<code>// dependencies
var async = require('async');
var AWS = require('aws-sdk');
var gm = require('gm').subClass({ imageMagick: true }); // Enable ImageMagick integration.

exports.handler = function(event, context) {
    var srcBucket = event.Records[0].s3.bucket.name;
    // Object key may have spaces or unicode non-ASCII characters.
    var key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
/*
{
    originalFilename: <string>,
    versions: [
        {
            size: <number>,
            crop: [x,y],
            max: [x, y],
            rotate: <number>
        }
    ]
}*/
    var fileInfo;
    var dstBucket = "xmovo.transformedimages.develop";
    try {
        //TODO: Decompress and decode the returned value
        fileInfo = JSON.parse(key);
        //download s3File

        // get reference to S3 client
        var s3 = new AWS.S3();

        // Download the image from S3 into a buffer.
        s3.getObject({
                Bucket: srcBucket,
                Key: key
            },
            function (err, response) {
                if (err) {
                    console.log("Error getting from s3: >>> " + err + "::: Bucket-Key >>>" + srcBucket + "-" + key + ":::Principal>>>" + event.Records[0].userIdentity.principalId, err.stack);
                    return;
                }

                // Infer the image type.
                var img = gm(response.Body);
                var imageType = null;
                img.identify(function (err, data) {
                    if (err) {
                        console.log("Error image type: >>> " + err);
                        deleteFromS3(srcBucket, key);
                        return;
                    }
                    imageType = data.format;

                    //foreach of the versions requested
                    async.each(fileInfo.versions, function (currentVersion, callback) {
                        //apply transform
                        async.waterfall([async.apply(transform, response, currentVersion), uploadToS3, callback]);

                    }, function (err) {
                        if (err) console.log("Error on excecution of watefall: >>> " + err);
                        else {
                            //when all done then delete the original image from srcBucket
                            deleteFromS3(srcBucket, key);
                        }
                    });
                });
            });
    }
    catch (ex){
        context.fail("exception through: " + ex);
        deleteFromS3(srcBucket, key);
        return;
    }
        function transform(response, version, callback){
            var imageProcess = gm(response.Body);
            if (version.rotate!=0) imageProcess = imageProcess.rotate("black",version.rotate);
            if(version.size!=null) {
                if (version.crop != null) {
                    //crop the image from the coordinates
                    imageProcess=imageProcess.crop(version.size[0], version.size[1], version.crop[0], version.crop[1]);
                }
                else {
                    //find the bigger and resize proportioned the other dimension
                    var widthIsMax = version.size[0]>version.size[1];
                    var maxValue = Math.max(version.size[0],version.size[1]);
                    imageProcess=(widthIsMax)?imageProcess.resize(maxValue):imageProcess.resize(null, maxValue);
                }
            }

            //finally convert the image to jpg 90%
            imageProcess.toBuffer("jpg",{quality:90}, function(err, buffer){
                if (err) callback(err);
                callback(null, version, "image/jpeg", buffer);
            });

        }

        function deleteFromS3(bucket, filename){
            s3.deleteObject({
                Bucket: bucket,
                Key: filename
            });
        }

        function uploadToS3(version, contentType, data, callback) {
            // Stream the transformed image to a different S3 bucket.
            var dstKey = fileInfo.originalFilename + "_" + version.size + ".jpg";
            s3.putObject({
                Bucket: dstBucket,
                Key: dstKey,
                Body: data,
                ContentType: contentType
            }, callback);
        }
};
</code>```

This is the error on Cloudwatch:

```<code>AccessDenied: Access Denied
</code>```

This is the stack error:

```<code>at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/services/s3.js:329:35)

at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)

at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)

at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:596:14)

at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:21:10)

at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)

at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10

at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:37:9)

at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:598:12)

at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:115:18)
</code>```

Without any other description or info
on S3 bucket permissions allow to everyone put list and delete.

What can I do to access the S3 bucket?

PS: on Lambda event properties the principal is correct and has administrative privileges.

答:
Interestingly enough, AWS returns 403 (access denied) when the file does not exist. Be sure the target file is in the S3 bucket.

From the comment from @Trajan , I think it's worth in the Answer itself...

It actually depends on the permission you have (see the doc) - If you
have the s3:ListBucket permission on the bucket, Amazon S3 will return
an HTTP status code 404 ("no such key") error. - if you don’t have the
s3:ListBucket permission, Amazon S3 will return an HTTP status code
403 ("access denied") error.

ContentLicense: CC BY-SA 4.0

Body:
I am getting an acccess denied error from S3 AWS service on my Lambda function.

This is the code:

// dependencies
var async = require('async');
var AWS = require('aws-sdk');
var gm = require('gm').subClass({ imageMagick: true }); // Enable ImageMagick integration.

exports.handler = function(event, context) {
    var srcBucket = event.Records[0].s3.bucket.name;
    // Object key may have spaces or unicode non-ASCII characters.
    var key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
/*
{
    originalFilename: <string>,
    versions: [
        {
            size: <number>,
            crop: [x,y],
            max: [x, y],
            rotate: <number>
        }
    ]
}*/
    var fileInfo;
    var dstBucket = "xmovo.transformedimages.develop";
    try {
        //TODO: Decompress and decode the returned value
        fileInfo = JSON.parse(key);
        //download s3File

        // get reference to S3 client
        var s3 = new AWS.S3();

        // Download the image from S3 into a buffer.
        s3.getObject({
                Bucket: srcBucket,
                Key: key
            },
            function (err, response) {
                if (err) {
                    console.log("Error getting from s3: >>> " + err + "::: Bucket-Key >>>" + srcBucket + "-" + key + ":::Principal>>>" + event.Records[0].userIdentity.principalId, err.stack);
                    return;
                }

                // Infer the image type.
                var img = gm(response.Body);
                var imageType = null;
                img.identify(function (err, data) {
                    if (err) {
                        console.log("Error image type: >>> " + err);
                        deleteFromS3(srcBucket, key);
                        return;
                    }
                    imageType = data.format;

                    //foreach of the versions requested
                    async.each(fileInfo.versions, function (currentVersion, callback) {
                        //apply transform
                        async.waterfall([async.apply(transform, response, currentVersion), uploadToS3, callback]);

                    }, function (err) {
                        if (err) console.log("Error on excecution of watefall: >>> " + err);
                        else {
                            //when all done then delete the original image from srcBucket
                            deleteFromS3(srcBucket, key);
                        }
                    });
                });
            });
    }
    catch (ex){
        context.fail("exception through: " + ex);
        deleteFromS3(srcBucket, key);
        return;
    }
        function transform(response, version, callback){
            var imageProcess = gm(response.Body);
            if (version.rotate!=0) imageProcess = imageProcess.rotate("black",version.rotate);
            if(version.size!=null) {
                if (version.crop != null) {
                    //crop the image from the coordinates
                    imageProcess=imageProcess.crop(version.size[0], version.size[1], version.crop[0], version.crop[1]);
                }
                else {
                    //find the bigger and resize proportioned the other dimension
                    var widthIsMax = version.size[0]>version.size[1];
                    var maxValue = Math.max(version.size[0],version.size[1]);
                    imageProcess=(widthIsMax)?imageProcess.resize(maxValue):imageProcess.resize(null, maxValue);
                }
            }

            //finally convert the image to jpg 90%
            imageProcess.toBuffer("jpg",{quality:90}, function(err, buffer){
                if (err) callback(err);
                callback(null, version, "image/jpeg", buffer);
            });

        }

        function deleteFromS3(bucket, filename){
            s3.deleteObject({
                Bucket: bucket,
                Key: filename
            });
        }

        function uploadToS3(version, contentType, data, callback) {
            // Stream the transformed image to a different S3 bucket.
            var dstKey = fileInfo.originalFilename + "_" + version.size + ".jpg";
            s3.putObject({
                Bucket: dstBucket,
                Key: dstKey,
                Body: data,
                ContentType: contentType
            }, callback);
        }
};

This is the error on Cloudwatch:

AccessDenied: Access Denied

This is the stack error:

at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/services/s3.js:329:35)

at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)

at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)

at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:596:14)

at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:21:10)

at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)

at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10

at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:37:9)

at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:598:12)

at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:115:18)

Without any other description or info
on S3 bucket permissions allow to everyone put list and delete.

What can I do to access the S3 bucket?

PS: on Lambda event properties the principal is correct and has administrative privileges.


问:
CSS - Make multiple divs in columns wrap back around
Say I have three divs - Red Green and Blue with the following basic markup and styles: https://jsfiddle.net/ar8sn1o6/

```<code><div class="red">Red</div>
<div class="green">Green</div>
<div class="blue">Blue</div>

.red, .green, .blue {
  display: inline-block;
  float: left;
  margin: 1%;
  width: 48%;
}

.red {
  background: red;
  height: 50px;
}

.green {
  background: green;
  height: 100px;
}

.blue {
  background: blue;
  height: 50px;
}
</code>```

But I want to be displayed in two column on desktop and one column on mobile like this. Whilst it is reasonably straight forward to have a Red -> Blue -> Green mobile layout, I need to instead have a Red -> Green -> Blue layout

Is this possible without duplicating any HTML?

答:
Put a container and add media-query

.red, .green, .blue {
  display: inline-block;
  margin: 1%;

}

.red {
  background: red;
  height: 50px;
  width:100%;
}

.green {
  background: green;
  height: 100px;

}

.blue {
   background: blue;
  height: 50px;
    width:100%;
}

.container, .green{
  float:left;
    width: 48%;
  }

  @media only screen
  and (max-width: 480px)  {

    .container, .green{
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="red">Red</div>
  <div class="blue">Blue</div>
</div>

<div class="green">Green</div></code>```

Body:
Say I have three divs - Red Green and Blue with the following basic markup and styles: https://jsfiddle.net/ar8sn1o6/

Red

Green

Blue

.red, .green, .blue {
  display: inline-block;
  float: left;
  margin: 1%;
  width: 48%;
}

.red {
  background: red;
  height: 50px;
}

.green {
  background: green;
  height: 100px;
}

.blue {
  background: blue;
  height: 50px;
}

But I want to be displayed in two column on desktop and one column on mobile like this. Whilst it is reasonably straight forward to have a Red -> Blue -> Green mobile layout, I need to instead have a Red -> Green -> Blue layout

Is this possible without duplicating any HTML?

Body:
Put a container and add media-query

.red, .green, .blue {
  display: inline-block;
  margin: 1%;

}

.red {
  background: red;
  height: 50px;
  width:100%;
}

.green {
  background: green;
  height: 100px;

}

.blue {
   background: blue;
  height: 50px;
    width:100%;
}

.container, .green{
  float:left;
    width: 48%;
  }

  @media only screen
  and (max-width: 480px)  {

    .container, .green{
    width: 100%;
  }
}

<div class="container">
  <div class="red">Red</div>
  <div class="blue">Blue</div>
</div>

<div class="green">Green</div>


问:
how to adjust x axis in matplotlib
I have a graph like this

The data on the x axis means hours, so I want the x axis to set as 0, 24, 48, 72.....instead of the value now, which is difficult to see the data between [0,100]

```<code>fig1 = plt.figure()
ax = fig1.add_subplot(111)
ax.set_yscale('log')
ax.plot(x,y,'b-')
</code>```

According to the the first answer, I got this:

答:
The size of the plot can be changed by setting the dynamic rc settings of Matplotlib. These are stored in a dictionary named rcParams. The size of the plot figure is stored with the key figure.figsize.

As an example, to get and set the size of a Matplotlib plot:
import matplotlib.pyplot as plt

```<code>fig_size = plt.rcParams["figure.figsize"] #Get current size
print "Current size:", fig_size           #Prints: [8.0, 6.0]
fig_size[0] = 12                          #Set figure width to 12 and height to 9
fig_size[1] = 9
plt.rcParams["figure.figsize"] = fig_size
</code>```

Title: how to adjust x axis in matplotlib

Body:
I have a graph like this

The data on the x axis means hours, so I want the x axis to set as 0, 24, 48, 72.....instead of the value now, which is difficult to see the data between [0,100]

fig1 = plt.figure()
ax = fig1.add_subplot(111)
ax.set_yscale('log')
ax.plot(x,y,'b-')

According to the the first answer, I got this:

Body:
The size of the plot can be changed by setting the dynamic rc settings of Matplotlib. These are stored in a dictionary named rcParams. The size of the plot figure is stored with the key figure.figsize.

As an example, to get and set the size of a Matplotlib plot:
import matplotlib.pyplot as plt

fig_size = plt.rcParams["figure.figsize"] #Get current size
print "Current size:", fig_size           #Prints: [8.0, 6.0]
fig_size[0] = 12                          #Set figure width to 12 and height to 9
fig_size[1] = 9
plt.rcParams["figure.figsize"] = fig_size


问:
Anybody interested in possible operation/use of quantum computers?
I went through a period of being interested in how quantum computers work and what they might be good for if they ever become practical. I know they are talked about for code-breaking. I was interested is using them for validating software by essentially trying all possible inputs (in parallel) and seeing if any error states are reached.

I know it's a bit of a blue-sky question, but I wonder if others are interested in quantum computers, how they might work, and what they would be useful for.

Added: Just for fun, let me throw out a mini-tutorial:

Suppose you've got N bits of memory to play with. Suppose you can load those bits (or some of them) with your input data. Then suppose there is a finite sequence of operations you can do on them (without using any additional memory) leaving the answer in them.

To do this with a quantum computer, it is only necessary that you make sure that the entire computation is reversible, by reserving some of the bits to record branches you took, so you can undo them. If you do that, then all the operations can be written as simple unitary matrix transformations on the N bits. (A unitary transform is a pure rotation in the N-dimensional coordinate system.) So performing the computation consists of applying a succession of pure rotations on the bit-vector.

If you do this, then if the N-bit vector is in a quantum computer, it can be initialized into a state where all 2^N (or fewer) possible inputs are superimposed at the same time in "parallel universes". Then if you do the computation, it is doing them all at the same time.

Now all you have to do to see if one of the inputs gives you a particular answer is to let it run to a particular state. If you halt it and examine the state, what it does is choose one of the universes at random and throw away all the rest. So what the Grover algorithm lets you do is, without halting it, accentuate the probability of the universes with the answer state. Then you run it forward, then backward, then forward, and so on for a number of iterations until the answer universe has very high probability. Then if you examine it, you have a high probability of seeing the answer you want.

Whew...

答:
Just to clarify, the link you have there talks about verification of finite state machines.
That could be a great thing in the HW market, but from there to software verification the way is long.

In particular, software runs over at least stack automata if not over Turing machines.

In addition, software verification without manual abstraction (a-la model checking) would require you to solve the halting problem. At best, a quantum computer can bring you from NP to P, it doesn't bring you from RE to R. Even if you run any infinite item in parallel, you can't in general determine if programs end. Though it is possible that for certain programs that can work.

Either way, I'll wait till I see an OS that runs on normal computers first. I can only imagine Quantum Computing's GPF... "The universe performed an illegal action and will now implode" or something like that.

OwnerDisplayName: Mike Dunlavey

LastEditorDisplayName: Mike Dunlavey

OwnerDisplayName: Uri

LastEditorDisplayName: derobert


问:
How to convert an html webpage to a picture
How to convert an html webpage to a picture  like google preview.

Is there a Java library permitting this?

Is there a command-line argument to call browsers to make them convert a web page into a picture .png for instance?

答:
Using Qt, you can create a simple window with a QWebView (this is webkit under the covers), and then use QWidget::render() method to get QPixmap, and then convert it to QImage.

Qt is C++, but python and java bindings exist also.


问:
Get maximum value of row in mysql ,using codeigniter
Get maximum value of row in mysql using codeigniter.

i have following mysql data

I need to get the details based on total_payment of each student.
like this

i tried code below

```<code> $student_id_dis = $this->db->query('SELECT DISTINCT(student_id) FROM student_fees')->result_array();
 $fee_cat_id_dis = $this->db->query('SELECT DISTINCT(fee_category_id) FROM student_fees')->result_array();
 $this->db->select(['student_fees.*', 'fee_categories.fee_category_name as fee_name', 'fee_categories.amount as fee_amount']);

 $this->db->join('student', 'student_fees.student_id = student.student_id');
 $this->db->join('fee_categories', 'student_fees.fee_category_id = fee_categories.fee_categories_id');

 $where = '';

 for ($i = 0; $i < count($student_id_dis); $i++) {
    if (isset($fee_cat_id_dis[$i]['fee_category_id'])) {
        $where .='total_paid = (SELECT max(stdp.total_paid)
                                   FROM student_fees stdp
                                   WHERE stdp.fee_category_id = ' . $fee_cat_id_dis[$i]['fee_category_id'] . ')';
     }

     $this->db->where($where);

     $this->db->get('student_fees')->result_array();
      }
</code>```

答:
try this </p>

```<code>select * from student_fees where student_fees_id in
(select student_fees_id from
  where total_paid =max(total_paid) group by fee_category_id)
</code>```

Body:
Get maximum value of row in mysql using codeigniter.

i have following mysql data

I need to get the details based on total_payment of each student.
like this

i tried code below

 $student_id_dis = $this->db->query('SELECT DISTINCT(student_id) FROM student_fees')->result_array();
 $fee_cat_id_dis = $this->db->query('SELECT DISTINCT(fee_category_id) FROM student_fees')->result_array();
 $this->db->select(['student_fees.*', 'fee_categories.fee_category_name as fee_name', 'fee_categories.amount as fee_amount']);

 $this->db->join('student', 'student_fees.student_id = student.student_id');
 $this->db->join('fee_categories', 'student_fees.fee_category_id = fee_categories.fee_categories_id');

 $where = '';

 for ($i = 0; $i < count($student_id_dis); $i++) {
    if (isset($fee_cat_id_dis[$i]['fee_category_id'])) {
        $where .='total_paid = (SELECT max(stdp.total_paid)
                                   FROM student_fees stdp
                                   WHERE stdp.fee_category_id = ' . $fee_cat_id_dis[$i]['fee_category_id'] . ')';
     }

     $this->db->where($where);

     $this->db->get('student_fees')->result_array();
      }

Body:
try this

select * from student_fees where student_fees_id in
(select student_fees_id from
  where total_paid =max(total_paid) group by fee_category_id)


问:
MySQL/phpMyAdmin comments in stored procedures removed
I'm facing a simple problem. I don't know, if it's a matter of MySQL or phpMyAdmin, but everytime I update a stored procedure with comments in it's definition, the comments are removed. I found many forums where it's discussed, but not solved. Anyone has a solution or an idea? MySQL 5.7.17 x64, phpMyAdmin 4.6.6, Windows 7 x64, Apache 2.4 VC14 x64.

Thanks a lot.

Edit - it happens only while importing sql file or through SQL textarea. The comments are preserved using the "pen tool"

Sample stored procedure to import:

```<code>DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_Test`$$
CREATE PROCEDURE `sp_Test`()
BEGIN
  -- this comment will be removed
  # this comment will be removed as well
  /* this comment too */

  SELECT 1;

END$$
DELIMITER ;
</code>```

Tried phpMyAdmin 4.7.0 - same problem...

The simpliest solution was to switch to a different application - Adminer (www.adminer.org), which consist of just one file, is extremely fast, does not do anything I don't want to, and can do everything phpMyAdmin can do as well. So long phpMyAdmin, never again.

答:
Your problem is quite common and there's an easy solution for it.
You should place your comments inside the procedure body, i.e., what's between BEGIN and END. The rest of the code are instructions to create the procedure and are lost once you run them.

Syntax for comments is:

/* ..... */

-- content

```<code>BEGIN
/*Comments*/
--Comments
END
</code>```

If this doesn't work, try this out:

Inside PhpMyAdmin, once you select the database relevant to you, click the wp_comments table on the left hand side.

This will bring up all the records associated with your comments. As you can see, each has a number of fields attached to it. If you scroll over to the right, you’ll see a field called comment_approved with values of either 1 or 0

Pending comments have a value of 0 and those that have been approved are 1. So to delete all pending comments in WordPress, we merely have to specify records with a comment_approved value of 1 which stops it from deleting them.

Also check if there exists a query which clears the wp_comments table.

Body:
I'm facing a simple problem. I don't know, if it's a matter of MySQL or phpMyAdmin, but everytime I update a stored procedure with comments in it's definition, the comments are removed. I found many forums where it's discussed, but not solved. Anyone has a solution or an idea? MySQL 5.7.17 x64, phpMyAdmin 4.6.6, Windows 7 x64, Apache 2.4 VC14 x64.

Thanks a lot.

Edit - it happens only while importing sql file or through SQL textarea. The comments are preserved using the "pen tool"

Sample stored procedure to import:

DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_Test`$$
CREATE PROCEDURE `sp_Test`()
BEGIN
  -- this comment will be removed
  # this comment will be removed as well
  /* this comment too */

  SELECT 1;

END$$
DELIMITER ;

Tried phpMyAdmin 4.7.0 - same problem...

The simpliest solution was to switch to a different application - Adminer (www.adminer.org), which consist of just one file, is extremely fast, does not do anything I don't want to, and can do everything phpMyAdmin can do as well. So long phpMyAdmin, never again.

Body:
Your problem is quite common and there's an easy solution for it.
You should place your comments inside the procedure body, i.e., what's between BEGIN and END. The rest of the code are instructions to create the procedure and are lost once you run them.

Syntax for comments is:

/* ..... */

-- content

BEGIN
/*Comments*/
--Comments
END

If this doesn't work, try this out:

Inside PhpMyAdmin, once you select the database relevant to you, click the wp_comments table on the left hand side.

This will bring up all the records associated with your comments. As you can see, each has a number of fields attached to it. If you scroll over to the right, you’ll see a field called comment_approved with values of either 1 or 0

Pending comments have a value of 0 and those that have been approved are 1. So to delete all pending comments in WordPress, we merely have to specify records with a comment_approved value of 1 which stops it from deleting them.

Also check if there exists a query which clears the wp_comments table.


问:
Yii Framework 2.0 -findModel returns an empty object
I am trying to show the form values which I have stored in the database.But it's not happening and also returning the empty values.I have added whatever I did.

Controller

```<code>protected function findModel($id)
    {
        if (($model = UserRegistration::find($id)->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
</code>```

Model

this is my model.I have declared all variables as public.Is that a problem? If I remove im getting error also.

```<code>class UserRegistration extends ActiveRecord
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $Country;
    public $State;
    public $City;
    public $phone_number;
    public $about_me;
    public $password;
    public $verify_password;
    public $photo;

    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['username','password', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'teespring_id'], 'integer'],
            [['username','lastname','firstname', 'password_hash', 'password_reset_token', 'email','about_me'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['role'], 'string', 'max' => 10],
            [['email','username'],'email'],
            [['email','username','password_reset_token'], 'unique'],
            ['phone_number','string','length'=>10],
            [['Country','State','City'],'string'],
            ['verify_password','compare','compareAttribute'=>'password'],
            [['photo'],'file', 'extensions' => 'png, jpg']
        ];
    }
}
</code>```

Update: I have tried $model = UserRegistration::findOne($id) also.no luck
Please help me.

答: It's UserRegistration::findOne($id) and you must not declare attributes that are coming from database because these will be empty.

Body:
I am trying to show the form values which I have stored in the database.But it's not happening and also returning the empty values.I have added whatever I did.

Controller

protected function findModel($id)
    {
        if (($model = UserRegistration::find($id)->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

Model

this is my model.I have declared all variables as public.Is that a problem? If I remove im getting error also.

class UserRegistration extends ActiveRecord
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $Country;
    public $State;
    public $City;
    public $phone_number;
    public $about_me;
    public $password;
    public $verify_password;
    public $photo;

    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['username','password', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'teespring_id'], 'integer'],
            [['username','lastname','firstname', 'password_hash', 'password_reset_token', 'email','about_me'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['role'], 'string', 'max' => 10],
            [['email','username'],'email'],
            [['email','username','password_reset_token'], 'unique'],
            ['phone_number','string','length'=>10],
            [['Country','State','City'],'string'],
            ['verify_password','compare','compareAttribute'=>'password'],
            [['photo'],'file', 'extensions' => 'png, jpg']
        ];
    }
}

Update: I have tried $model = UserRegistration::findOne($id) also.no luck
Please help me.


问:
Google Cloud Platform: Multiple *website.com in one project or per each website per project?
Is it ideal to put *.website.com into one GCP project or have one project per website? We are going to use Firebase to store the backend data, and the data between each *.website.com will be shared.

Any tips or more efficient ways to get a website started/hosted onto Google Cloud Platform? (So much stuff/information it is quite overwhelming)

答:
Best practices is usually to have a site per project so you can keep all your website related resources in a single project. Otherwise you'll have a lot of resources in a project going to different websites that will make it harder to maintain.

Alternatively if you are hosting multiple websites on the same infrastructure then you could consider a project per environment e.g staging, development etc.

Another possibility that some people use is put all front end resources in a project and then all the backend resources in another project and use googles cross project networking to communicate with them as this allows team separation of resources.

I'd need to know a little more about what you are trying to set up.


问:
What is AspectJ good for?
First let me note, that I use AspectJ and I like it, but what else can I do with it.

I know AspectJ can be/is used for Logging. In some cases it is used for Transaction controlling – mostly implemented in conjunction with annotations.
AspectJ can also be used to enhance classes with (code-generated) methods, like Spring Roo does.

But I believe AspectJ and AOP in general, can be used for more than: logging, transaction controlling, and simulation partial classes.

So what are other useful use cases for AspectJ and AOP?

答:
The Wikipedia entry gives you a few more examples (but not that many). Typically, Aspect Oriented Programing should be use only to implement simple behaviours that are not part of core concern of a class and are common to different classes. As soon as you begin to put too much logic in your aspects, the code becomes really unreadable.

The aspect you suggest (logging, transaction, ...) are the most commonly used. I would add security as well.

Title: What is AspectJ good for?


问:
MongoDB diacriticInSensitive search not showing all accented (words with diacritic mark) rows as expected and vice-versa
I have a document collection with following structure

```<code>uid, name
</code>```

With a Index

```<code>db.Collection.createIndex({name: "text"})
</code>```

It contains following data

```<code>1, iphone
2, iphóne
3, iphonë
4, iphónë
</code>```

When I am doing text search for iphone
I am getting only two records, which is unexpected

```<code>actual output
--------------
1, iphone
2, iphóne
</code>```

If I search for iphonë

```<code>db.Collection.find( { $text: { $search: "iphonë"} } );

I am getting
---------------------
3, iphonë
4, iphónë
</code>```

But Actually I am expecting following output

```<code>db.Collection.find( { $text: { $search: "iphone"} } );
db.Collection.find( { $text: { $search: "iphónë"} } );

    Expected output
    ------------------
    1, iphone
    2, iphóne
    3, iphonë
    4, iphónë
</code>```

am I missing something here?
How can I get above expected outputs, with search of iphone or iphónë?

答:
Since mongodb 3.2, text indexes are diacritic insensitive:

With version 3, text index is diacritic insensitive. That is, the
  index does not distinguish between characters that contain diacritical
  marks and their non-marked counterpart, such as é, ê, and e. More
  specifically, the text index strips the characters categorized as
  diacritics in Unicode 8.0 Character Database Prop List.

So the following query should work:

```<code>db.Collection.find( { $text: { $search: "iphone"} } );
db.Collection.find( { name: { $regex: "iphone"} } );
</code>```

but it looks like there is a bug with dieresis ( ¨ ), even if it's caterorized as diacritic in unicode 8.0 list (issue on JIRA: SERVER-29918 )

Solution

since mongodb 3.4 you can use collation which allows you to perform this kind of query :

for example, to get your expected output, run the following query:

```<code>db.Collection.find({name: "iphone"}).collation({locale: "en", strength: 1})
</code>```

this will output:

```<code>{ "_id" : 1, "name" : "iphone" }
{ "_id" : 2, "name" : "iphône" }
{ "_id" : 3, "name" : "iphonë" }
{ "_id" : 4, "name" : "iphônë" }
</code>```

in the collation, strength is the level of comparaison to perform

1 : base character only

2 : diacritic sensitive

3 : case sensitive + diacritic sensitive

Body:
I have a document collection with following structure

uid, name

With a Index

db.Collection.createIndex({name: "text"})

It contains following data

1, iphone
2, iphóne
3, iphonë
4, iphónë

When I am doing text search for iphone
I am getting only two records, which is unexpected

actual output
--------------
1, iphone
2, iphóne

If I search for iphonë

db.Collection.find( { $text: { $search: "iphonë"} } );

I am getting
---------------------
3, iphonë
4, iphónë

But Actually I am expecting following output

db.Collection.find( { $text: { $search: "iphone"} } );
db.Collection.find( { $text: { $search: "iphónë"} } );

    Expected output
    ------------------
    1, iphone
    2, iphóne
    3, iphonë
    4, iphónë

am I missing something here?
How can I get above expected outputs, with search of iphone or iphónë?

Body:
Since mongodb 3.2, text indexes are diacritic insensitive:

With version 3, text index is diacritic insensitive. That is, the
  index does not distinguish between characters that contain diacritical
  marks and their non-marked counterpart, such as é, ê, and e. More
  specifically, the text index strips the characters categorized as
  diacritics in Unicode 8.0 Character Database Prop List.

So the following query should work:

db.Collection.find( { $text: { $search: "iphone"} } );
db.Collection.find( { name: { $regex: "iphone"} } );

but it looks like there is a bug with dieresis ( ¨ ), even if it's caterorized as diacritic in unicode 8.0 list (issue on JIRA: SERVER-29918 )

Solution

since mongodb 3.4 you can use collation which allows you to perform this kind of query :

for example, to get your expected output, run the following query:

db.Collection.find({name: "iphone"}).collation({locale: "en", strength: 1})

this will output:

{ "_id" : 1, "name" : "iphone" }
{ "_id" : 2, "name" : "iphône" }
{ "_id" : 3, "name" : "iphonë" }
{ "_id" : 4, "name" : "iphônë" }

in the collation, strength is the level of comparaison to perform

1 : base character only

2 : diacritic sensitive

3 : case sensitive + diacritic sensitive


问:
How to display just the group name of groups user is member of in powershell
So I have the following script but it lists the full name of the AD group. (e.g. CN=GroupName,OU=OUName,DC=DomainName,DC=com) How do I specify only the group's name, so that it lists only the name itself. The part after CN=. I tried $group.Name but no such luck.

```<code>Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"

foreach ($username in $userlist) {
    $grplist = (Get-ADUser $username –Properties MemberOf | Select-Object MemberOf).MemberOf
    foreach ($group in $grplist) {
        write-host $group
    }
}
</code>```

Also as a second question is there some way to filter based on what the group name starts with?

答:
There is one simple way : Get-ADPrincipalGroupMembership -Identity blabla | Select-Object Name

Get-ADPrincipalGroupMembership outputs the group objects a user is a member of and it comes with the default AD module.

Body:
So I have the following script but it lists the full name of the AD group. (e.g. CN=GroupName,OU=OUName,DC=DomainName,DC=com) How do I specify only the group's name, so that it lists only the name itself. The part after CN=. I tried $group.Name but no such luck.

Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"

foreach ($username in $userlist) {
    $grplist = (Get-ADUser $username –Properties MemberOf | Select-Object MemberOf).MemberOf
    foreach ($group in $grplist) {
        write-host $group
    }
}

Also as a second question is there some way to filter based on what the group name starts with?


问:
error as "No such table" while inserting data in to table
Getting Error as NO such table,Table is not creating,Please help me with your answers.I think error is database.java file.So I uploaded it.In inserting values I am not changing fields of phone number into long...As I taken it as TEXT datatype in Database file.
           '

```<code>               public class MyDatabase extends SQLiteOpenHelper {

          Context c;

         // Database Name
           public static final String DATABASE_NAME = "BIRLA_ACCOUNTS";
        //Table Name
        public static final String TABLE_NAME = "MASTERACCOUNTS";
        //  Table Columns names
        public static final String CODE = "CODE";
        public static final String NAME = "NAME";
        public static final String TYPE = "TYPE";
        public static final String ADD1 = "ADD1";
        public static final String ADD2 = "ADD2";
        public static final String CITY = "CITY";
        public static final String COUNTRY = "COUNTRY";
        public static final String PHONENO = "PHONENO";
        public static final String CONTACTPERSON = "CONTACTPERSON";
         public static final String EMAILID = "EMAILID";
        public static final String FAX = "FAX";
         public static final String TNO = "TNO";
        public static final String CSTNO = "CSTNO";
        public static final String GSTNO = "GSTNO";
        public static final String SERVICENO = "SERVICENO";

        public MyDatabase(Context context) {
        super(context, DATABASE_NAME, null, 1);
        c = context;

       }

         @Override
          public void onCreate(SQLiteDatabase db) {
          try {

            db.execSQL("CREATE TABLE "+TABLE_NAME+"("+CODE+" INTEGER
                     AUTOINCREMENT,"+NAME+" TEXT PRIMARY KEY ,"+TYPE+" TEXT,
                       "+ADD1+" TEXT,"+ADD2+" TEXT,"+CITY+" TEXT,"+COUNTRY+
                          " TEXT,"+PHONENO+" TEXT,"
                    +CONTACTPERSON+" TEXT,"+EMAILID +" VARCHAR(50),"+FAX+"
                        REAL,"+TNO+" REAL,"+CSTNO+" REAL,"+GSTNO+" REAL,"
            +SERVICENO +" REAL)");
              Toast.makeText(c, "Table Created", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                  Log.e("AccountsMaster creation", "" + e);
                       }

                  }

               @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion,
                   int  newVersion) {
            // Drop older table if existed
                db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
             // Creating tables again
                 onCreate(db);
              }
</code>```

`

答:
Try to add query like this:

```<code>String TABLE ="CREATE TABLE "+ TABLE_NAME + "("
                + CODE + " INTEGER AUTOINCREMENT,"
                + NAME + " TEXT PRIMARY KEY ,"
                + TYPE + " TEXT,"
                + ADD1 + " TEXT,"
                + ADD2 + " TEXT,"
                + CITY + " TEXT,"
                + COUNTRY + " TEXT,"
                + PHONENO + " TEXT,"
                + CONTACTPERSON + " TEXT,"
                + EMAILID + " VARCHAR(50),"
                + FAX + " REAL,"
                + TNO + " REAL,"
                + CSTNO + " REAL,"
                + GSTNO+ " REAL,"
                + SERVICENO +" REAL" +")";

        db.execSQL(TABLE);
</code>```

always care about white space and ending close bracts like above.
hope this will help you.

Body:
Getting Error as NO such table,Table is not creating,Please help me with your answers.I think error is database.java file.So I uploaded it.In inserting values I am not changing fields of phone number into long...As I taken it as TEXT datatype in Database file.
           '

               public class MyDatabase extends SQLiteOpenHelper {

          Context c;

         // Database Name
           public static final String DATABASE_NAME = "BIRLA_ACCOUNTS";
        //Table Name
        public static final String TABLE_NAME = "MASTERACCOUNTS";
        //  Table Columns names
        public static final String CODE = "CODE";
        public static final String NAME = "NAME";
        public static final String TYPE = "TYPE";
        public static final String ADD1 = "ADD1";
        public static final String ADD2 = "ADD2";
        public static final String CITY = "CITY";
        public static final String COUNTRY = "COUNTRY";
        public static final String PHONENO = "PHONENO";
        public static final String CONTACTPERSON = "CONTACTPERSON";
         public static final String EMAILID = "EMAILID";
        public static final String FAX = "FAX";
         public static final String TNO = "TNO";
        public static final String CSTNO = "CSTNO";
        public static final String GSTNO = "GSTNO";
        public static final String SERVICENO = "SERVICENO";

        public MyDatabase(Context context) {
        super(context, DATABASE_NAME, null, 1);
        c = context;

       }

         @Override
          public void onCreate(SQLiteDatabase db) {
          try {

            db.execSQL("CREATE TABLE "+TABLE_NAME+"("+CODE+" INTEGER
                     AUTOINCREMENT,"+NAME+" TEXT PRIMARY KEY ,"+TYPE+" TEXT,
                       "+ADD1+" TEXT,"+ADD2+" TEXT,"+CITY+" TEXT,"+COUNTRY+
                          " TEXT,"+PHONENO+" TEXT,"
                    +CONTACTPERSON+" TEXT,"+EMAILID +" VARCHAR(50),"+FAX+"
                        REAL,"+TNO+" REAL,"+CSTNO+" REAL,"+GSTNO+" REAL,"
            +SERVICENO +" REAL)");
              Toast.makeText(c, "Table Created", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                  Log.e("AccountsMaster creation", "" + e);
                       }

                  }

               @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion,
                   int  newVersion) {
            // Drop older table if existed
                db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
             // Creating tables again
                 onCreate(db);
              }

`

Body:
Try to add query like this:

String TABLE ="CREATE TABLE "+ TABLE_NAME + "("
                + CODE + " INTEGER AUTOINCREMENT,"
                + NAME + " TEXT PRIMARY KEY ,"
                + TYPE + " TEXT,"
                + ADD1 + " TEXT,"
                + ADD2 + " TEXT,"
                + CITY + " TEXT,"
                + COUNTRY + " TEXT,"
                + PHONENO + " TEXT,"
                + CONTACTPERSON + " TEXT,"
                + EMAILID + " VARCHAR(50),"
                + FAX + " REAL,"
                + TNO + " REAL,"
                + CSTNO + " REAL,"
                + GSTNO+ " REAL,"
                + SERVICENO +" REAL" +")";

        db.execSQL(TABLE);

always care about white space and ending close bracts like above.
hope this will help you.


问:
Which activity called the adapter
I am using an adapter to populate a listview ,
I am using same adapter in 2 activities but I need to hide an element of the layout in one case and not in another .
So is there a way to figure out which activity called the adapter (in the adapter class ) ?</p>

```<code>public class Db_adapter extends BaseAdapter {

private Context mContext;
private List<db_list> mDataList;
private LayoutInflater mLayoutInflater;
private String TAG = this.getClass().getSimpleName();

public Db_adapter(Context mContext, List<db_list> mDataList) {
    this.mContext = mContext;
    this.mDataList = mDataList;
    this.mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();
}

@Override
public int getViewTypeCount() {
    return super.getViewTypeCount();
}

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

@Override
public Object getItem(int position  ) {
    return mDataList.get(position);
}

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder = null;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = mLayoutInflater.inflate(R.layout.dblayout,parent,false);
        viewHolder.tv_db_name= (TextView) convertView.findViewById(R.id.tv_db_name);
        viewHolder.tv_db_number = (TextView) convertView.findViewById(R.id.tv_db_number);
        viewHolder.iv_delete = (ImageView)convertView.findViewById(R.id.iv_delete);
        convertView.setTag(viewHolder);
    }
    else{
        viewHolder = (ViewHolder) convertView.getTag();
    }

    db_list rowData = mDataList.get(position);
    viewHolder.tv_db_name.setText(rowData.getDb_name());
    viewHolder.tv_db_number.setText(rowData.getDn_number());
    viewHolder.iv_delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new DeleteDb_async().execute(Add_deliveryBoy.db_id_list.get(position), String.valueOf(position));

        }
    });

    return convertView;
}

public void onDataSetChanged(List<db_list> mDataList) {
    this.mDataList = mDataList;
    notifyDataSetChanged();
}

private class ViewHolder{
    private TextView tv_db_name,tv_db_number;
    private ImageView iv_delete;
}
</code>```

答:
As you said let us assume that I have two activities ActivityOne and ActivityTwo </p>

```<code>Context context;
List<db_list> mDataList;

public Db_adapter(Context context, List<db_list> mDataList) {
    this.context = context;
    this.mDataList = mDataList;
}
</code>```

<p>And in your method you can do it like this </p>

```<code>if(context instanceof ActivityOne) {
    // setVisibility
} else if(context instanceof ActivityTwo) {
    // setVisibility
}
</code>```

Title: Which activity called the adapter

Body:
I am using an adapter to populate a listview ,
I am using same adapter in 2 activities but I need to hide an element of the layout in one case and not in another .
So is there a way to figure out which activity called the adapter (in the adapter class ) ?

public class Db_adapter extends BaseAdapter {

private Context mContext;
private List<db_list> mDataList;
private LayoutInflater mLayoutInflater;
private String TAG = this.getClass().getSimpleName();

public Db_adapter(Context mContext, List<db_list> mDataList) {
    this.mContext = mContext;
    this.mDataList = mDataList;
    this.mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();
}

@Override
public int getViewTypeCount() {
    return super.getViewTypeCount();
}

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

@Override
public Object getItem(int position  ) {
    return mDataList.get(position);
}

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder = null;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = mLayoutInflater.inflate(R.layout.dblayout,parent,false);
        viewHolder.tv_db_name= (TextView) convertView.findViewById(R.id.tv_db_name);
        viewHolder.tv_db_number = (TextView) convertView.findViewById(R.id.tv_db_number);
        viewHolder.iv_delete = (ImageView)convertView.findViewById(R.id.iv_delete);
        convertView.setTag(viewHolder);
    }
    else{
        viewHolder = (ViewHolder) convertView.getTag();
    }

    db_list rowData = mDataList.get(position);
    viewHolder.tv_db_name.setText(rowData.getDb_name());
    viewHolder.tv_db_number.setText(rowData.getDn_number());
    viewHolder.iv_delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new DeleteDb_async().execute(Add_deliveryBoy.db_id_list.get(position), String.valueOf(position));

        }
    });

    return convertView;
}

public void onDataSetChanged(List<db_list> mDataList) {
    this.mDataList = mDataList;
    notifyDataSetChanged();
}

private class ViewHolder{
    private TextView tv_db_name,tv_db_number;
    private ImageView iv_delete;
}

Body:
As you said let us assume that I have two activities ActivityOne and ActivityTwo

Context context;
List<db_list> mDataList;

public Db_adapter(Context context, List<db_list> mDataList) {
    this.context = context;
    this.mDataList = mDataList;
}

And in your method you can do it like this

if(context instanceof ActivityOne) {
    // setVisibility
} else if(context instanceof ActivityTwo) {
    // setVisibility
}


问:
Dropzone.js - How to add new property to file object after uploading file
I'm using dropzone and PHP to upload and delete files. When I load my upload page I create some mockfiles with the following params: name, size, thumbnail and id. This mock is set using pre uploaded data.

So when someone click on remove file button, I call the php method that delete the image.

My problem is when the user uploads an file and tries to delete it without loading the page. When it happens, dropzone file object just can't be altered.

I'm trying:

```<code>var dropZone3 = new Dropzone("#file3",{
                    init: function() {
                        this.on('success', function (file) {
                            console.log(file);
                            file['test'] = 'test';
                            file.test = 'test';
                            console.log(file);
                        })
                    },
                    paramName: 'file3',
                    autoProcessQueue:true,
                    uploadMultiple: false,
                    parallelUploads: 1,
                    maxFiles: 3,
                    maxFilesize: 5,
                    addRemoveLinks: true
</code>```

My problem is that the first console.log and the second one inside init on success function shows me the same file.

Anyone knows how to fix it?

Thank you in advance.

答:
It's possible to add properties directly to file object (dropzone v4.3.0)

```<code>var dropZone = new Dropzone(document.querySelector('.js-dropzone'), {
  url: '/file/upload'
});

dropZone.on('success', function (file, response) {
  var res = JSON.parse(response);

  if (res.result == true) {
    file.test = 'test';
    file.id = res.id;
  }
});
</code>```

Body:
I'm using dropzone and PHP to upload and delete files. When I load my upload page I create some mockfiles with the following params: name, size, thumbnail and id. This mock is set using pre uploaded data.

So when someone click on remove file button, I call the php method that delete the image.

My problem is when the user uploads an file and tries to delete it without loading the page. When it happens, dropzone file object just can't be altered.

I'm trying:

var dropZone3 = new Dropzone("#file3",{
                    init: function() {
                        this.on('success', function (file) {
                            console.log(file);
                            file['test'] = 'test';
                            file.test = 'test';
                            console.log(file);
                        })
                    },
                    paramName: 'file3',
                    autoProcessQueue:true,
                    uploadMultiple: false,
                    parallelUploads: 1,
                    maxFiles: 3,
                    maxFilesize: 5,
                    addRemoveLinks: true

My problem is that the first console.log and the second one inside init on success function shows me the same file.

Anyone knows how to fix it?

Thank you in advance.

Body:
It's possible to add properties directly to file object (dropzone v4.3.0)

var dropZone = new Dropzone(document.querySelector('.js-dropzone'), {
  url: '/file/upload'
});

dropZone.on('success', function (file, response) {
  var res = JSON.parse(response);

  if (res.result == true) {
    file.test = 'test';
    file.id = res.id;
  }
});


问:
Restart shiny app from within app (reloading data)
I want to restart a shiny app from within the app, so that e.g. code in global.R will be executed again (to reload a csv file with data). Here is a minimal example showing what I want to do:

This shiny app loads some coordinates data and plots markers on a map. When a new marker is added to the map, the new coordinates should be appended to the old data and saved as a csv file. Then the app should restart, load data.csv again, so all markers are shown on the map. I tried adapting code from here: Restart Shiny Session but this doesn't work. The app restarts, but it doesn't reload the csv file.

```<code>library(shinyjs)
library(leaflet)
library(leaflet.extras)

jsResetCode <- "shinyjs.reset = function() {history.go(0)}"

# data <- data.frame(latitude = 49, longitude = 13)
data <- read.csv2("data.csv") # this should get executed whenever js$reset is called

ui <- fluidPage(
  useShinyjs(),
  extendShinyjs(text = jsResetCode),
    leafletOutput("map")
)

server <- function(input, output, session){
  output$map <- renderLeaflet({
    leaflet(data) %>% addTiles()  %>%
      setView(11.5, 48, 7) %>%
      addDrawToolbar() %>%
      addMarkers()
  })

  data_reactive <- reactiveValues(new_data = data)

  # add new point to existing data and save data as data.csv
  # after that the app should restart
  observeEvent(input$map_draw_new_feature, {
    data_reactive$new_data <- rbind(rep(NA, ncol(data)), data_reactive$new_data)
    data_reactive$new_data$longitude[1] <- input$map_draw_new_feature$geometry$coordinates[[1]]
    data_reactive$new_data$latitude[1] <- input$map_draw_new_feature$geometry$coordinates[[2]]
    write.csv2(data_reactive$new_data, "data.csv", row.names = FALSE)
    js$reset() # this should restart the app
  })
}

shinyApp(ui, server)
</code>```

答:
To reload the csv file you need to place reading of the file inside the server. </p>

```<code>server <- function(input, output, session){

    #Read the data inside the server!!!
    data <- read.csv2("data.csv")# this should get executed whenever js$reset is called

    output$map <- renderLeaflet({
      leaflet(data) %>% addTiles()  %>%
        setView(11.5, 48, 7) %>%
        addDrawToolbar() %>%
        addMarkers()
    })

    data_reactive <- reactiveValues(new_data = data)

    # add new point to existing data and save data as data.csv
    # after that the app should restart
    observeEvent(input$map_draw_new_feature, {
      # browser()
      data_reactive$new_data <- rbind(rep(NA, ncol(data)), data_reactive$new_data)
      data_reactive$new_data$longitude[1] <- input$map_draw_new_feature$geometry$coordinates[[1]]
      data_reactive$new_data$latitude[1] <- input$map_draw_new_feature$geometry$coordinates[[2]]
      write.csv2(data_reactive$new_data, "data.csv", row.names = FALSE)
      js$reset() # this should restart the app
    })
  }
</code>```

Body:
I want to restart a shiny app from within the app, so that e.g. code in global.R will be executed again (to reload a csv file with data). Here is a minimal example showing what I want to do:

This shiny app loads some coordinates data and plots markers on a map. When a new marker is added to the map, the new coordinates should be appended to the old data and saved as a csv file. Then the app should restart, load data.csv again, so all markers are shown on the map. I tried adapting code from here: Restart Shiny Session but this doesn't work. The app restarts, but it doesn't reload the csv file.

library(shinyjs)
library(leaflet)
library(leaflet.extras)

jsResetCode <- "shinyjs.reset = function() {history.go(0)}"

# data <- data.frame(latitude = 49, longitude = 13)
data <- read.csv2("data.csv") # this should get executed whenever js$reset is called

ui <- fluidPage(
  useShinyjs(),
  extendShinyjs(text = jsResetCode),
    leafletOutput("map")
)

server <- function(input, output, session){
  output$map <- renderLeaflet({
    leaflet(data) %>% addTiles()  %>%
      setView(11.5, 48, 7) %>%
      addDrawToolbar() %>%
      addMarkers()
  })

  data_reactive <- reactiveValues(new_data = data)

  # add new point to existing data and save data as data.csv
  # after that the app should restart
  observeEvent(input$map_draw_new_feature, {
    data_reactive$new_data <- rbind(rep(NA, ncol(data)), data_reactive$new_data)
    data_reactive$new_data$longitude[1] <- input$map_draw_new_feature$geometry$coordinates[[1]]
    data_reactive$new_data$latitude[1] <- input$map_draw_new_feature$geometry$coordinates[[2]]
    write.csv2(data_reactive$new_data, "data.csv", row.names = FALSE)
    js$reset() # this should restart the app
  })
}

shinyApp(ui, server)

Body:
To reload the csv file you need to place reading of the file inside the server.

server <- function(input, output, session){

    #Read the data inside the server!!!
    data <- read.csv2("data.csv")# this should get executed whenever js$reset is called

    output$map <- renderLeaflet({
      leaflet(data) %>% addTiles()  %>%
        setView(11.5, 48, 7) %>%
        addDrawToolbar() %>%
        addMarkers()
    })

    data_reactive <- reactiveValues(new_data = data)

    # add new point to existing data and save data as data.csv
    # after that the app should restart
    observeEvent(input$map_draw_new_feature, {
      # browser()
      data_reactive$new_data <- rbind(rep(NA, ncol(data)), data_reactive$new_data)
      data_reactive$new_data$longitude[1] <- input$map_draw_new_feature$geometry$coordinates[[1]]
      data_reactive$new_data$latitude[1] <- input$map_draw_new_feature$geometry$coordinates[[2]]
      write.csv2(data_reactive$new_data, "data.csv", row.names = FALSE)
      js$reset() # this should restart the app
    })
  }


问:
HTML required validation message style issue in Bootstrap from field
In my Bootstrap form field with the calendar icon and it's required. However when the error massage is showing it's going to be mess like below image.

HTML code is

```<code><div class="input-group">
     <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
     <input type="text" value="" class="form-control error" name="from" id="from" required">
 </div>
</code>```

Bootstrap CSS below

```<code> .input-group-addon, .input-group-btn, .input-group .form-control {
        display: table-cell;
    }
.input-group-addon, .input-group-btn {
    vertical-align: middle;
    white-space: nowrap;
    width: 1%;
}
.input-group-addon {
    background-color: #eeeeee;
    border: 1px solid #cacaca;
    border-radius: 3px;
    color: #333333;
    font-size: 14px;
    font-weight: normal;
    line-height: 1;
    padding: 6px 12px;
    text-align: center;
}
.input-group .form-control {
    float: left;
    margin-bottom: 0;
    position: relative;
    width: 100%;
    z-index: 2;
}
</code>```

HTML5 required error

```<code><label id="from-error" class="error" for="from">This field is required.</label>
</code>```

So HTML code is like below when error occur

```<code><div class="input-group">
     <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
     <input type="text" value="" class="form-control error" name="from" id="from" required">
<label id="from-error" class="error" for="from">This field is required.</label>
 </div>
</code>```

So How to fix this and set calendar Icon with in lining the field?

答:
try this may work

```<code> <div class="input-group">
 <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
 <input type="text" value="" class="form-control error" name="from" id="from" required">
 </div>
  <label id="from-error" class="error" for="from">This field is required.</label>
</code>```

Body:
In my Bootstrap form field with the calendar icon and it's required. However when the error massage is showing it's going to be mess like below image.

HTML code is

     <input type="text" value="" class="form-control error" name="from" id="from" required">

Bootstrap CSS below

 .input-group-addon, .input-group-btn, .input-group .form-control {
        display: table-cell;
    }
.input-group-addon, .input-group-btn {
    vertical-align: middle;
    white-space: nowrap;
    width: 1%;
}
.input-group-addon {
    background-color: #eeeeee;
    border: 1px solid #cacaca;
    border-radius: 3px;
    color: #333333;
    font-size: 14px;
    font-weight: normal;
    line-height: 1;
    padding: 6px 12px;
    text-align: center;
}
.input-group .form-control {
    float: left;
    margin-bottom: 0;
    position: relative;
    width: 100%;
    z-index: 2;
}

HTML5 required error

This field is required.

So HTML code is like below when error occur

     <input type="text" value="" class="form-control error" name="from" id="from" required">
This field is required.

So How to fix this and set calendar Icon with in lining the field?

Body:
try this may work

 <div class="input-group">
 <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
 <input type="text" value="" class="form-control error" name="from" id="from" required">
 </div>
  <label id="from-error" class="error" for="from">This field is required.</label>