问:
SceneKit custom shapes for complex ".DAE" objects
QUESTION 1:

Code to make collision with elementary object - tube works not correctly:

```<code>    let tubeGeometry = SCNTube(innerRadius: 2, outerRadius: 2.5, height: 2)
    let tubeMaterial = SCNMaterial()
    tubeMaterial.diffuse.contents = UIColor.green
    tubeGeometry.materials = [tubeMaterial]

    let tubeNode = SCNNode(geometry: tubeGeometry)
    tubeNode.position = SCNVector3(0, 0, 0)

    let tubeShape = SCNPhysicsShape(geometry: tubeGeometry, options: nil)
    let tubeBody = SCNPhysicsBody(type: .dynamic, shape: tubeShape)

    tubeNode.physicsBody?.categoryBitMask = collisionTube
    tubeNode.physicsBody?.collisionBitMask = collsionTarget
    tubeNode.physicsBody?.mass = 1
    tubeNode.physicsBody = tubeBody

    scene.rootNode.addChildNode(tubeNode)
</code>```

Screenshot:

Why balls is on the top of object ?

QUESTION 2:

I'm carefully read the manual to use the classes SCNPhysicsShape and SCNPhysicsBody

Researched all possible ways of imposing constraints to the DAE objects.
And came to the conclusion that all restrictions must be programmed complex bundles of SCNNodes in a single physical model of the object.

Found very interesting answer:

LINK

I really hope there is a way to made something like let DAEShape = SCNPhysicsShape(geometry: "*.DAE")..., otherwise the setting collisions to complex objects can take a month or more development.

For example, how to design collisions of the complex tube "DAE" object, as in the screenshot, any advices?

The question is not about performance rather the ability to implement complex constraints to complex 3D objects the most straightforward way, avoiding the chore of programming...

How to set physic constraints using the vertexes, edges and faces of the "DAE" object?

I really hope that the answer will be...
Thanks in advance!

答:
```<code>    let url = Bundle.main.url(forResource: "art.scnassets/half", withExtension: "dae")
    let sceneSource = SCNSceneSource(url: url!, options: nil)
    let tubeGeometry = (sceneSource?.entryWithIdentifier("Cube-mesh", withClass: SCNGeometry.self ))! as SCNGeometry

    tubeNode = SCNNode(geometry: tubeGeometry)
    tubeNode.position = SCNVector3(0, 1, 0)
    tubeNode.eulerAngles = SCNVector3Make(1.5, 2, 0)
    tubeNode.physicsBody = SCNPhysicsBody(type: .static, shape: SCNPhysicsShape(geometry: tubeGeometry, options: [SCNPhysicsShape.Option.type: SCNPhysicsShape.ShapeType.concavePolyhedron]))
    scene.rootNode.addChildNode(tubeNode)
</code>```

Body:
QUESTION 1:

Code to make collision with elementary object - tube works not correctly:

    let tubeGeometry = SCNTube(innerRadius: 2, outerRadius: 2.5, height: 2)
    let tubeMaterial = SCNMaterial()
    tubeMaterial.diffuse.contents = UIColor.green
    tubeGeometry.materials = [tubeMaterial]

    let tubeNode = SCNNode(geometry: tubeGeometry)
    tubeNode.position = SCNVector3(0, 0, 0)

    let tubeShape = SCNPhysicsShape(geometry: tubeGeometry, options: nil)
    let tubeBody = SCNPhysicsBody(type: .dynamic, shape: tubeShape)

    tubeNode.physicsBody?.categoryBitMask = collisionTube
    tubeNode.physicsBody?.collisionBitMask = collsionTarget
    tubeNode.physicsBody?.mass = 1
    tubeNode.physicsBody = tubeBody

    scene.rootNode.addChildNode(tubeNode)

Screenshot:

Why balls is on the top of object ?

QUESTION 2:

I'm carefully read the manual to use the classes SCNPhysicsShape and SCNPhysicsBody

Researched all possible ways of imposing constraints to the DAE objects.
And came to the conclusion that all restrictions must be programmed complex bundles of SCNNodes in a single physical model of the object.

Found very interesting answer:

LINK

I really hope there is a way to made something like let DAEShape = SCNPhysicsShape(geometry: "*.DAE")..., otherwise the setting collisions to complex objects can take a month or more development.

For example, how to design collisions of the complex tube "DAE" object, as in the screenshot, any advices?

The question is not about performance rather the ability to implement complex constraints to complex 3D objects the most straightforward way, avoiding the chore of programming...

How to set physic constraints using the vertexes, edges and faces of the "DAE" object?

I really hope that the answer will be...
Thanks in advance!


来源: stackexchange

问:
UITableView leaking?
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}
</code>```

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?

答:
Maybe you can try defining the uiBarButtonItem as a variable, then assign it to the navigation left bar button item and then release the button

Have you try build & analyze under the Build menu? With 2.0 Objective C sentences its pretty accurate

in addition, you have to be careful with property definition, you are using self.tableView, I assume you you have something like @property(nonatomic, retain)?, in that case, once you alloc, you should release the property in the next line..

Finally, this line is extremely weird: [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped]; you are trying to initialize a table thats already initialized, because if you don't, self.tableView.frame should be in error. In addition to that, the initWithFrame method returns something that is not being assigned.. I think that you can think a better way to do this

Sorry about the mess, I've been answering this question in the chat, but unfortunately you were disconnected.

Hope this helps.

ContentLicense: CC BY-SA 2.5

Title: UITableView leaking?

Body:
I have a UITableViewController and I set some properties in the viewDidLoadMethod like so:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self.parentViewController.parentViewController action:@selector(dismissSettings)] autorelease];
    [self setTitle:@"Gabbai Settings"];

    //Set up the table
    [self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];

    [self.tableView setRowHeight:65.0];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];

    [self.tableView.backgroundView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_settings", kTheme] ofType:@"png"]]]];

}

The app shows a UIScrollViewController and a UIButton. When the button is pressed, the app displays a modal UINavigationController and that UINavigationController contains a UITableViewController.

For some reason, Leaks reports some leakage when I show the UITableViewController. However, if I comment out the four lines after //Set up the table, everything is fine.

When the four lines are uncommented, the Leaks instrument shows the following:

I'm not sure what is going on here, but it's really annoying. I've used the same four lines of code before to customize my UITableViewController and this is a new behavior.

What could be wrong?


问:
Expression Must Be Modifiable Value (C)
Quick question:

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

int main(void) {
    int divisor, counter, binary, counter2;
    int digit0, digit1, digit2, digit3;
    float decimal;

    printf("Decimal\t\tBinary\n");

    for (counter = 0; counter <= 15; counter++) {
        printf("%d\t\n", counter);

        decimal = counter;

        for (counter2 = 0; counter2 <= 3; counter2++) {
            decimal % 2 == 1 ? digit0 = 1 : digit0 = 0);
        }
    }

    return 0;
}
</code>```

I keep getting the error that the "expression must be a modifiable value" on variable name "decimal" in the second for loop.

Why is this, and how can I fix it?

Thank you!

答: Because decimal is float,but % only for integers.If you really want to mod by using float, you can use function float fmod(float x, float y), it calculates x%y, and you should include #include <math.h> to use it.

ContentLicense: CC BY-SA 3.0

Title: Expression Must Be Modifiable Value (C)

Body:
Quick question:

#include <stdio.h>

int main(void) {
    int divisor, counter, binary, counter2;
    int digit0, digit1, digit2, digit3;
    float decimal;

    printf("Decimal\t\tBinary\n");

    for (counter = 0; counter <= 15; counter++) {
        printf("%d\t\n", counter);

        decimal = counter;

        for (counter2 = 0; counter2 <= 3; counter2++) {
            decimal % 2 == 1 ? digit0 = 1 : digit0 = 0);
        }
    }

    return 0;
}

I keep getting the error that the "expression must be a modifiable value" on variable name "decimal" in the second for loop.

Why is this, and how can I fix it?

Thank you!


问:
Spring Data Rest - can only create nested entities on one direction
I have an issue with Spring Boot / Spring Data whereby I can only create nested entities in one direction.

I have two entities, Parent and Child, and a Parent has a OnetoMany relationship with the Child entity.

If I create a Child, by doing this:

```<code>POST http://localhost:8080/children
{
    "name": "Tenzin"
}
</code>```

and then create a Parent by doing this:

```<code>POST http://localhost:8080/parents
{
    "name": "Fred and Alma",
    "children": [ "http://localhost:8080/children/1" ]
}
</code>```

it doesn't work.

However, if I create the parent first, and then create a new child by doing this, it does work:

```<code>POST http://localhost:8080/children
{
    "name": "Jacob",
    "parent": [ "http://localhost:8080/parents/1" ]
}
</code>```

Why is this the case, is this expected behaviour or am I doing something wrong?

Is it because the Parent entity (see below) has cascade=ALL on the children property?

Parent entity:

```<code>@Entity
public class Parent {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy="parent", cascade = CascadeType.ALL)
    private List<Child> children = new ArrayList<>();

    private String name;

    public Long getId() {
        return id;
    }

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

    public List<Child> getChildren() {
        return children;
    }

    public void setChildren(List<Child> children) {
        this.children = children;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

Child entity:

```<code>@Entity
public class Child {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToOne
    private Parent parent;

    public Long getId() {
        return id;
    }

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

    public Parent getParent() {
        return parent;
    }

    public void setParent(Parent parent) {
        this.parent = parent;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

答:
In you example the child is the owner of the relationchip (it's saved in the child table of database). I think there is the problem. Spring Data Rest loads the child object into the "children" field, but doesn't know that it also should change the "parent" field of the children object. (see also https://stackoverflow.com/a/1796501/7226417).

You can solve this with catching a Spring Data Rest Event (http://docs.spring.io/spring-data/rest/docs/current/reference/html/#events) and  manually set the "parent" field.

Body:
I have an issue with Spring Boot / Spring Data whereby I can only create nested entities in one direction.

I have two entities, Parent and Child, and a Parent has a OnetoMany relationship with the Child entity.

If I create a Child, by doing this:

POST http://localhost:8080/children
{
    "name": "Tenzin"
}

and then create a Parent by doing this:

POST http://localhost:8080/parents
{
    "name": "Fred and Alma",
    "children": [ "http://localhost:8080/children/1" ]
}

it doesn't work.

However, if I create the parent first, and then create a new child by doing this, it does work:

POST http://localhost:8080/children
{
    "name": "Jacob",
    "parent": [ "http://localhost:8080/parents/1" ]
}

Why is this the case, is this expected behaviour or am I doing something wrong?

Is it because the Parent entity (see below) has cascade=ALL on the children property?

Parent entity:

@Entity
public class Parent {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy="parent", cascade = CascadeType.ALL)
    private List<Child> children = new ArrayList<>();

    private String name;

    public Long getId() {
        return id;
    }

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

    public List<Child> getChildren() {
        return children;
    }

    public void setChildren(List<Child> children) {
        this.children = children;
    }

    public String getName() {
        return name;
    }

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

Child entity:

@Entity
public class Child {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToOne
    private Parent parent;

    public Long getId() {
        return id;
    }

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

    public Parent getParent() {
        return parent;
    }

    public void setParent(Parent parent) {
        this.parent = parent;
    }

    public String getName() {
        return name;
    }

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


问:
Get files from web directory
I wanted to just get random Images from http://random.cat/, so I wanted to index them using Directory.GetFiles or something like that, but this doesn't work. So what would be the best way to get the functionality of Directory.GetFiles but for http://random.cat/i (this is where the Images are stored, I think)?

Thanks in advance!

答:
Directory.GetFiles() is designed to be used on a filesystem, not on web addresses.

This link ought to be enough to get you started. Since you don't know the actual URL of the picture, you would have to parse the page to find it and then make a further request to download it.

Be aware that they might block you out if you download too many images in a certain time.

EDIT: I noticed just now that they have an API, which makes everything a bit simpler. But it's marked as temporary, so make of that what you will.

Title: Get files from web directory


问:
Does spring.xml file requires a internet connection?
I am currently working on spring and I am very much new to this framework. I have added all the required jars of spring and written the following spring-dispatcher-servlet.xml file.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:component-scan base-package="com.quiz_mcq.controller, com.quiz_mcq.service, com.quiz_mcq.dao"/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/" />
      <property name="suffix" value=".jsp" />
    </bean>

</beans>
</code>```

My code works fine when there is internet connection but breaks down when I am not connected to the internet. And gives the following error.

Line 12 in XML document from ServletContext resource [/WEB-INF/spring->dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 109; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'context:component-scan'.

What am I doing wrong here?

Can any tell me the solution what needs to be done to work the project even offline?

答:
for xsi schema Location put

xsi:schemaLocation=
"http://www.springframework.org/schema/beans
             classpath:org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
             classpath:org/springframework/beans/factory/xml/spring-context-3.0.xsd"

in your case code need  to check on springframework.com every time

the schema location i provided should work because the xsd is packaged inside the spring jar here

Body:
I am currently working on spring and I am very much new to this framework. I have added all the required jars of spring and written the following spring-dispatcher-servlet.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:component-scan base-package="com.quiz_mcq.controller, com.quiz_mcq.service, com.quiz_mcq.dao"/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/" />
      <property name="suffix" value=".jsp" />
    </bean>

</beans>

My code works fine when there is internet connection but breaks down when I am not connected to the internet. And gives the following error.

Line 12 in XML document from ServletContext resource [/WEB-INF/spring->dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 109; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'context:component-scan'.

What am I doing wrong here?

Can any tell me the solution what needs to be done to work the project even offline?


问:
Are all event handlers always called when unsubscribing other handlers within a handler?
I wrote a test that shows that when invoking an event, all handlers are called even though one of the handlers (not the last one) unsubscribe all the handlers.

The test is in this gist, repeated below.

My question is: Is this behavior expected and documented (I haven't found any mention of it), and can it be counted on? Or is it perhaps just due to some peculiarities of how I've written the test?

```<code>namespace EventUnsubscriptionTest
{
    using System;

    using NUnit.Framework;

    public class EventSource
    {
        public event Action Event;

        public void TriggerEvent()
        {
            this.Event?.Invoke();
        }
    }

    public class EventSourceTests
    {
        [Test]
        public void When_Unsubscribing_Should_InvokeAllBeforeUnsubscribing()
        {
            // Arrange
            var invokeCounter = 0;
            var listener1InvokedOrder = 0;
            var listener2InvokedOrder = 0;
            var listener3InvokedOrder = 0;

            var sut = new EventSource();

            Action listener1 = null;
            Action listener2 = null;
            Action listener3 = null;

            listener1 = () => listener1InvokedOrder = ++invokeCounter;
            listener2 = () =>
            {
                listener2InvokedOrder = ++invokeCounter;
                sut.Event -= listener1;
                sut.Event -= listener2;
                sut.Event -= listener3;
            };

            listener3 = () => listener3InvokedOrder = ++invokeCounter;

            sut.Event += listener1;
            sut.Event += listener2;
            sut.Event += listener3;

            // Act
            sut.TriggerEvent();

            // Assert
            Assert.That(listener1InvokedOrder, Is.EqualTo(1));
            Assert.That(listener2InvokedOrder, Is.EqualTo(2));
            Assert.That(listener3InvokedOrder, Is.EqualTo(3));

            // Ensure that we actually unsubscribed
            sut.TriggerEvent();
            Assert.That(invokeCounter, Is.EqualTo(3));
        }
    }
}
</code>```

答:
My my question is: Is this behavior expected and documented (I haven't found any mention of it), and can it be counted on?

Yes, because you are triggering all 3 listeners before unsubscribing them.

This first line

```<code>// Act
sut.TriggerEvent();
</code>```

is what is causing their execution and so they will be invoked before the second listener unsubscribes them

Body:
I wrote a test that shows that when invoking an event, all handlers are called even though one of the handlers (not the last one) unsubscribe all the handlers.

The test is in this gist, repeated below.

My question is: Is this behavior expected and documented (I haven't found any mention of it), and can it be counted on? Or is it perhaps just due to some peculiarities of how I've written the test?

namespace EventUnsubscriptionTest
{
    using System;

    using NUnit.Framework;

    public class EventSource
    {
        public event Action Event;

        public void TriggerEvent()
        {
            this.Event?.Invoke();
        }
    }

    public class EventSourceTests
    {
        [Test]
        public void When_Unsubscribing_Should_InvokeAllBeforeUnsubscribing()
        {
            // Arrange
            var invokeCounter = 0;
            var listener1InvokedOrder = 0;
            var listener2InvokedOrder = 0;
            var listener3InvokedOrder = 0;

            var sut = new EventSource();

            Action listener1 = null;
            Action listener2 = null;
            Action listener3 = null;

            listener1 = () => listener1InvokedOrder = ++invokeCounter;
            listener2 = () =>
            {
                listener2InvokedOrder = ++invokeCounter;
                sut.Event -= listener1;
                sut.Event -= listener2;
                sut.Event -= listener3;
            };

            listener3 = () => listener3InvokedOrder = ++invokeCounter;

            sut.Event += listener1;
            sut.Event += listener2;
            sut.Event += listener3;

            // Act
            sut.TriggerEvent();

            // Assert
            Assert.That(listener1InvokedOrder, Is.EqualTo(1));
            Assert.That(listener2InvokedOrder, Is.EqualTo(2));
            Assert.That(listener3InvokedOrder, Is.EqualTo(3));

            // Ensure that we actually unsubscribed
            sut.TriggerEvent();
            Assert.That(invokeCounter, Is.EqualTo(3));
        }
    }
}

Body:
My my question is: Is this behavior expected and documented (I haven't found any mention of it), and can it be counted on?

Yes, because you are triggering all 3 listeners before unsubscribing them.

This first line

// Act
sut.TriggerEvent();

is what is causing their execution and so they will be invoked before the second listener unsubscribes them


问:
C# add items to listview not working
```<code>private void showResultsList()
{
    IWebElement table = resultFinder.FindElementById("records");
    IList<IWebElement> trElements = table.FindElements(By.TagName("tr"));
    IList<IWebElement> tdElements;
    IList<IWebElement> aElements = table.FindElements(By.TagName("a"));

    mainWindow.Dispatcher.Invoke(() =>
    {
        ListView listView = (ListView)mainWindow.FindName("Search_ResultsList");
        ItemCollection resultsListItems = listView.Items;
        listView.Items.Clear();

        for (int i = 0; i < trElements.Count; i++)
        {
            IWebElement trElement = trElements[i];
            tdElements = trElement.FindElements(By.TagName("td"));
            aElements = trElement.FindElements(By.TagName("a"));
            string index = (i + 1).ToString();
            string text = tdElements[2].Text;
            // this line removes the last part of the content, which says "Aggiungi ai preferiti"
            string result = text.Substring(0, text.LastIndexOf('\n'));
            string hyperLink = aElements[0].GetAttribute("href");

            resultsListItems.Add(new ResultsListItem { Index = index, Result = result, HyperLink = hyperLink });
        }
    });
}
</code>```

XAML file

```<code><ListView Name="Search_ResultsList" HorizontalAlignment="Left" Height="886" Margin="10,10,0,0" VerticalAlignment="Top" Width="440" BorderBrush="#FF707070">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="N." Width="30" DisplayMemberBinding="{Binding Index}"/>
            <GridViewColumn Header="Result" Width="387" DisplayMemberBinding="{Binding Result}"/>
        </GridView>
    </ListView.View>
</ListView>
</code>```

ResultsListItem class

```<code>class ResultsListItem : ListViewItem
{
    public string Index { get; set; }
    public string Result { get; set; }
    public string HyperLink { get; set; }
}
</code>```

I'm trying to show this list into a ListView object by adding the ResultsListItem to the collection of items. When I run the program the list doesn't show the content of the listItems, just a list of empty items. What do I do wrong?
Thanks in advance.

答:
You can use DataGrid instead, if you want to show tabular data in the view -

Code Behind

```<code>private void showResultsListWithDataGrid()
  {
    List<ResultsListItem> listItem = new List<ResultsListItem>();
    for(int i=1; i<=10; i++)
    {
        listItem.Add(new ResultsListItem
        {
            Index = "index" + i,
            Result = "result" + i,
            HyperLink = "hyperlink" + i
        });
    }
    this.dataGrid.ItemsSource = listItem; //datagrid should be declared on the xaml file
}
</code>```

please see details on - DataGrid

Title: C# add items to listview not working

Body:
private void showResultsList()
{
    IWebElement table = resultFinder.FindElementById("records");
    IList<IWebElement> trElements = table.FindElements(By.TagName("tr"));
    IList<IWebElement> tdElements;
    IList<IWebElement> aElements = table.FindElements(By.TagName("a"));

    mainWindow.Dispatcher.Invoke(() =>
    {
        ListView listView = (ListView)mainWindow.FindName("Search_ResultsList");
        ItemCollection resultsListItems = listView.Items;
        listView.Items.Clear();

        for (int i = 0; i < trElements.Count; i++)
        {
            IWebElement trElement = trElements[i];
            tdElements = trElement.FindElements(By.TagName("td"));
            aElements = trElement.FindElements(By.TagName("a"));
            string index = (i + 1).ToString();
            string text = tdElements[2].Text;
            // this line removes the last part of the content, which says "Aggiungi ai preferiti"
            string result = text.Substring(0, text.LastIndexOf('\n'));
            string hyperLink = aElements[0].GetAttribute("href");

            resultsListItems.Add(new ResultsListItem { Index = index, Result = result, HyperLink = hyperLink });
        }
    });
}

XAML file

<ListView Name="Search_ResultsList" HorizontalAlignment="Left" Height="886" Margin="10,10,0,0" VerticalAlignment="Top" Width="440" BorderBrush="#FF707070">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="N." Width="30" DisplayMemberBinding="{Binding Index}"/>
            <GridViewColumn Header="Result" Width="387" DisplayMemberBinding="{Binding Result}"/>
        </GridView>
    </ListView.View>
</ListView>

ResultsListItem class

class ResultsListItem : ListViewItem
{
    public string Index { get; set; }
    public string Result { get; set; }
    public string HyperLink { get; set; }
}

I'm trying to show this list into a ListView object by adding the ResultsListItem to the collection of items. When I run the program the list doesn't show the content of the listItems, just a list of empty items. What do I do wrong?
Thanks in advance.

Body:
You can use DataGrid instead, if you want to show tabular data in the view -

Code Behind

private void showResultsListWithDataGrid()
  {
    List<ResultsListItem> listItem = new List<ResultsListItem>();
    for(int i=1; i<=10; i++)
    {
        listItem.Add(new ResultsListItem
        {
            Index = "index" + i,
            Result = "result" + i,
            HyperLink = "hyperlink" + i
        });
    }
    this.dataGrid.ItemsSource = listItem; //datagrid should be declared on the xaml file
}

please see details on - DataGrid


问:
Sort values from for loop
Hello im trying to sort values (NUMERIC) from for loop, my code:

```<code>$result_itemid_count = count($result_itemid);
for($x = 0; $x < $result_itemid_count; $x++) {
    echo $result_itemid[$x][0];
    echo "<br />";
}
</code>```

output:

172505254931 172505254931 172505254931 172505254931 172505254931
  172505254931 172295676941 172295676941 172195402570 172195402570
  172195402570 172295676941 172408848472 172195402570 172195402570
  172593285746 172593285746 172593285746 172593285746 172263227044
  172263227044 172195402570 172263227044 172408848472 172408848472

i have no idea how to sort it, i tried sort, usort, ksort
any ideas?

first loop:

```<code>if ($resp->ack == "Success") {
  $results = '';
  $result_itemid = array();
  // If the response was loaded, parse it and build links
  foreach($resp->searchResult->item as $item) {
    $pic   = $item->galleryURL;
    $link  = $item->viewItemURL;
    $title = $item->title;
    $location = $item->location;
    $itemid = $item->itemId;
    $multiv = $item->isMultiVariationListing;

    if($multiv == "true")
    {
    $result_itemid[] = [$itemid, $title];
    } else {
    // For each SearchResultItem node, build a link and append it to $results
    $results .= "<tr><td align = 'center'><img src=\"$pic\"></td><td><a href=\"$link\">$title - $location</a></td></tr>";
    }

  }
}
// If the response does not indicate 'Success,' print an error
else {
  $results  = "<h3>Oops! The request was not successful. Make sure you are using a valid ";
  $results .= "AppID for the Production environment.</h3>";
}
</code>```

second loop:

```<code>$result_itemid_count = count($result_itemid);
for($x = 0; $x < $result_itemid_count; $x++) {
    echo $result_itemid[$x][0];
    echo "<br />";
}
</code>```

答:
I hope you expected like below</p>

```<code>$result_itemid[0][0]=121223;
$result_itemid[1][0]=121883;
$result_itemid[2][0]=121203;
$result_itemid[3][0]=121213;
$result_itemid[4][0]=121235;
$new_array=[];
$result_itemid_count = count($result_itemid);
for($x = 0; $x < $result_itemid_count; $x++) {
 echo $result_itemid[$x][0];
 echo "<br />";
 array_push($new_array, $result_itemid[$x][0]);
}

echo "<hr/>";
sort($new_array);
$result_count = count($new_array);
for($x = 0; $x < $result_count; $x++) {
 echo $new_array[$x];
 echo "<br>";
}
</code>```

Title: Sort values from for loop

Body:
Hello im trying to sort values (NUMERIC) from for loop, my code:

$result_itemid_count = count($result_itemid);
for($x = 0; $x < $result_itemid_count; $x++) {
    echo $result_itemid[$x][0];
    echo "
";
}

output:

172505254931 172505254931 172505254931 172505254931 172505254931
  172505254931 172295676941 172295676941 172195402570 172195402570
  172195402570 172295676941 172408848472 172195402570 172195402570
  172593285746 172593285746 172593285746 172593285746 172263227044
  172263227044 172195402570 172263227044 172408848472 172408848472

i have no idea how to sort it, i tried sort, usort, ksort
any ideas?

first loop:

if ($resp->ack == "Success") {
  $results = '';
  $result_itemid = array();
  // If the response was loaded, parse it and build links
  foreach($resp->searchResult->item as $item) {
    $pic   = $item->galleryURL;
    $link  = $item->viewItemURL;
    $title = $item->title;
    $location = $item->location;
    $itemid = $item->itemId;
    $multiv = $item->isMultiVariationListing;

    if($multiv == "true")
    {
    $result_itemid[] = [$itemid, $title];
    } else {
    // For each SearchResultItem node, build a link and append it to $results
    $results .= "
	$title - $location
";
    }

  }
}
// If the response does not indicate 'Success,' print an error
else {
  $results  = "
Oops! The request was not successful. Make sure you are using a valid ";
  $results .= "AppID for the Production environment.
";
}

second loop:

$result_itemid_count = count($result_itemid);
for($x = 0; $x < $result_itemid_count; $x++) {
    echo $result_itemid[$x][0];
    echo "
";
}

Body:
I hope you expected like below

$result_itemid[0][0]=121223;
$result_itemid[1][0]=121883;
$result_itemid[2][0]=121203;
$result_itemid[3][0]=121213;
$result_itemid[4][0]=121235;
$new_array=[];
$result_itemid_count = count($result_itemid);
for($x = 0; $x < $result_itemid_count; $x++) {
 echo $result_itemid[$x][0];
 echo "<br />";
 array_push($new_array, $result_itemid[$x][0]);
}

echo "<hr/>";
sort($new_array);
$result_count = count($new_array);
for($x = 0; $x < $result_count; $x++) {
 echo $new_array[$x];
 echo "<br>";
}


问:
Form data sent with AJAX request not updating sql table
Im having an issue getting a sql table to update with the form data sent from a Jquery AJAX POST.

I've tried mysql_error() and it returns no errors.

I added an additional line to my textarea "-Test Test"

this is being recognised on the Form data

At the bottom you see test text, this is part of the text being entered into notetext1 which is then made notetext2 in this submitNoteText.php:

```<code><?php include 'connectionDetails.php'; ?>

<?php

if (isset($_POST['noteid1'], $_POST['notetext1']))
{

    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];

    $query = "UPDATE Notes SET Note = " . $notetext2 . " WHERE NoteID = ".$noteid2;
    $stmt = sqlsrv_query($conn, $query) or die(mysql_error());
}

sqlsrv_close($conn);

?>
</code>```

However i refresh my table in my database and the text has not been added despite the successful post?

The JQuery:

```<code>function submitNoteText()
{
    var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
    var notetext = $("#ta1").val();

    var dataString = 'noteid1=' + noteid + '&notetext1=' + notetext;

    console.log("NoteID: " + noteid);

    if(noteid == ''||notetext == '')
    {
        alert("NoteID or Text is blank");
    }
    else
    {
        $.ajax({
            type: "POST",
            url: "submitNoteText.php",
            dataType: 'json',
            data: dataString,
            cache: false,
            success: function(result){
                alert("Successfully saved!");
            }
        });
    }
    return false;
};
</code>```

答:
Try sending the data as an object instead of a string.
So change this line:

```<code>var dataString = 'noteid1=' + noteid + '&notetext1=' + notetext;
</code>```

to

```<code>var data = {noteid1: noteid, notetext1: notetext};
</code>```

And then you should change the request to use this data so it becomes:

```<code>    $.ajax({
        type: "POST",
        url: "submitNoteText.php",
        dataType: 'json',
        data: data,
        cache: false,
        success: function(result){
            alert("Successfully saved!");
        }
    });
</code>```

Body:
Im having an issue getting a sql table to update with the form data sent from a Jquery AJAX POST.

I've tried mysql_error() and it returns no errors.

I added an additional line to my textarea "-Test Test"

this is being recognised on the Form data

At the bottom you see test text, this is part of the text being entered into notetext1 which is then made notetext2 in this submitNoteText.php:

<?php include 'connectionDetails.php'; ?>

<?php

if (isset($_POST['noteid1'], $_POST['notetext1']))
{

    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];

    $query = "UPDATE Notes SET Note = " . $notetext2 . " WHERE NoteID = ".$noteid2;
    $stmt = sqlsrv_query($conn, $query) or die(mysql_error());
}

sqlsrv_close($conn);

?>

However i refresh my table in my database and the text has not been added despite the successful post?

The JQuery:

function submitNoteText()
{
    var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
    var notetext = $("#ta1").val();

    var dataString = 'noteid1=' + noteid + '&notetext1=' + notetext;

    console.log("NoteID: " + noteid);

    if(noteid == ''||notetext == '')
    {
        alert("NoteID or Text is blank");
    }
    else
    {
        $.ajax({
            type: "POST",
            url: "submitNoteText.php",
            dataType: 'json',
            data: dataString,
            cache: false,
            success: function(result){
                alert("Successfully saved!");
            }
        });
    }
    return false;
};

Body:
Try sending the data as an object instead of a string.
So change this line:

var dataString = 'noteid1=' + noteid + '&notetext1=' + notetext;

to

var data = {noteid1: noteid, notetext1: notetext};

And then you should change the request to use this data so it becomes:

    $.ajax({
        type: "POST",
        url: "submitNoteText.php",
        dataType: 'json',
        data: data,
        cache: false,
        success: function(result){
            alert("Successfully saved!");
        }
    });


问:
Sails socket authorization (using passport)
I am using passport for authentication/authorization along with local strategy and a JWT.

Following some research (intensive googling ;) I understand that the best place for the authorization is to use a policy as it applies both for a regular HTTP requests and a socket request (through SailsSocket object that can send 'virtual' HTTP-like requests).

I am now trying to figure out how to use sockets properly and I've seen that there's a beforeConnect handler that allows to reject a connection. While it is not a big deal (as I have a policy that will prevent it from getting data), I want to be able to reject connections - I think its healthier and what reason is there to allow a non-authorized socket connection.

I only want to socket to connect after initial authentication so that in my socket initialization I can set the headers to include the JWT:

```<code>io.sails.url = connections.http.baseURL;

io.sails.headers = {
    'Authorization': 'Bearer ' + token
};

io.sails.useCORSRouteToGetCookie = false;

io.socket = io.sails.connect();
io.socket.on('...', someHandler);
</code>```

This seems to work fine - the socket request hits the JWT policy and I get a req.user in my controller methods for socket requests.

My question is - how do I go about rejecting the user without a token from connecting (and should I even do that?)

When I break inside the beforeConnect I don't see the Authorization header in handshake object.

Update: furthermore, I am now trying to send the token in the query when connecting:

```<code>io.socket = io.sails.connect({token: token});
</code>```

With that, I am able to see the token in the handshake. I'd expect it to be in handshake.query which does not exists. Instead, it is available in handshake._query while the sails docs (here) is claims that is should be under socket.handshake.query (but socket doesn't even exists in beforeConnect and the default function footprint is beforeConnect: function(handshake, cb))

Are these bugs?? Am I missing something?

答:
Following discussion with one of the sails developer (here, thanks sgress454):

Headers are not sent with the initial request for connection. It is part of the socket.io specifications and not an issue with sails itself. It maybe possible with newest versions of socket.io to set transportOptions but this isn't integrated into sails yet (2017-04-02).

Any query parameter appears as _query property of the handshake argument. This is not (currently) documented correctly. The documentation will be updated in the near future.

As for the underlying issue - I've implemented the token verification using my own code as I could not find a way to have passport.js integrated in the beforeConnect method. In config/sockets.js I have something like:

```<code>beforeConnect: function(handshake, cb) {
    // `true` allows the connection
    // (`false` would reject the connection)

    var token = handshake._query ? handshake._query.token : null;

    CipherService.verifyToken(token, function verifyTokenResults(err, decoded, info) {
        if (err || !decoded) {
            if (err.name === "TokenExpiredError") {
                // token expired - user can't connect...
                return cb(null, false);
            } else {
                // some other error...
                return cb(err, false);
            }
        }

        // here you may want to do other verification, e.g. the user is active
        return cb(null, true);
    });

},
</code>```

I now have automatic reconnection issues :-( see here )-:

Body:
I am using passport for authentication/authorization along with local strategy and a JWT.

Following some research (intensive googling ;) I understand that the best place for the authorization is to use a policy as it applies both for a regular HTTP requests and a socket request (through SailsSocket object that can send 'virtual' HTTP-like requests).

I am now trying to figure out how to use sockets properly and I've seen that there's a beforeConnect handler that allows to reject a connection. While it is not a big deal (as I have a policy that will prevent it from getting data), I want to be able to reject connections - I think its healthier and what reason is there to allow a non-authorized socket connection.

I only want to socket to connect after initial authentication so that in my socket initialization I can set the headers to include the JWT:

io.sails.url = connections.http.baseURL;

io.sails.headers = {
    'Authorization': 'Bearer ' + token
};

io.sails.useCORSRouteToGetCookie = false;

io.socket = io.sails.connect();
io.socket.on('...', someHandler);

This seems to work fine - the socket request hits the JWT policy and I get a req.user in my controller methods for socket requests.

My question is - how do I go about rejecting the user without a token from connecting (and should I even do that?)

When I break inside the beforeConnect I don't see the Authorization header in handshake object.

Update: furthermore, I am now trying to send the token in the query when connecting:

io.socket = io.sails.connect({token: token});

With that, I am able to see the token in the handshake. I'd expect it to be in handshake.query which does not exists. Instead, it is available in handshake._query while the sails docs (here) is claims that is should be under socket.handshake.query (but socket doesn't even exists in beforeConnect and the default function footprint is beforeConnect: function(handshake, cb))

Are these bugs?? Am I missing something?

Body:
Following discussion with one of the sails developer (here, thanks sgress454):

Headers are not sent with the initial request for connection. It is part of the socket.io specifications and not an issue with sails itself. It maybe possible with newest versions of socket.io to set transportOptions but this isn't integrated into sails yet (2017-04-02).

Any query parameter appears as _query property of the handshake argument. This is not (currently) documented correctly. The documentation will be updated in the near future.

As for the underlying issue - I've implemented the token verification using my own code as I could not find a way to have passport.js integrated in the beforeConnect method. In config/sockets.js I have something like:

beforeConnect: function(handshake, cb) {
    // `true` allows the connection
    // (`false` would reject the connection)

    var token = handshake._query ? handshake._query.token : null;

    CipherService.verifyToken(token, function verifyTokenResults(err, decoded, info) {
        if (err || !decoded) {
            if (err.name === "TokenExpiredError") {
                // token expired - user can't connect...
                return cb(null, false);
            } else {
                // some other error...
                return cb(err, false);
            }
        }

        // here you may want to do other verification, e.g. the user is active
        return cb(null, true);
    });

},

I now have automatic reconnection issues :-( see here )-:


问:
Firebase Cloud Messaging Notification not received by my device
I'm using Firebase Auth stuff in project. Today I decided to integrate FCM into my project. But I couldn't ANY notification from my Firebase console. I also tried re-download .json file but it didn't work out. Do you guys have any idea about my problem?

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yunus.ototakip">

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permisson.INTERNET" />

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Cihazdan Google Servislerine erişmek için izin -->
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!-- İndirilenlerin tutulması için izinler -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- OpenGL ES 2.0 Google Maps Android API v2 için gerekiyor -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"></uses-permission>
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/oto_takip"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MyIntro"
        android:theme="@style/FullscreenTheme" />
    <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".AracEkle"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".InternetCon"
        android:theme="@style/FullscreenTheme" />
    <activity
        android:name=".IpuclariSayfasi"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".TrafficActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".EngineActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".AidActivity"
        android:theme="@style/AppTheme.NoActionBar" />

    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" />

    <activity
        android:name=".AyarlarActivity"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <activity android:name=".Hesabim"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <activity android:name=".Giris"
        android:theme="@style/AppTheme.NoActionBar"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" /> <!-- Check this one -->
        </intent-filter>
    </activity>

    <activity android:name=".KayitOl"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <service
        android:name=".FirebaseMessageService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

    <service
        android:name=".FirebaseIDService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

</application>
</code>```

FirebaseMessageService.java

```<code>public void onMessageReceived(RemoteMessage remoteMessage){
    sendNotification(remoteMessage.getNotification().getBody());
}

private void sendNotification(String messageBody){
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.oto_takip)
            .setContentText(messageBody)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}
</code>```

FirebaseIDService.java

```<code> public class FirebaseIDService extends FirebaseInstanceIdService
 {
private static final String TAG ="FirebaseIDService";
@Override
public void onTokenRefresh() {
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Token: " + refreshedToken);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String refreshedToken)
{
}
   }
</code>```

I think the problem is not up to my MainActiviy.java but I'm gonna show it to you just in case.

MainActivity.java

```<code> public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener{

private Fragment fragment;
private FragmentManager fragmentManager;
public TextView tarih;
final String PREFS_NAME = "MyPrefsFile";
final String SHAREDPREF_DATE = "SharedPrefDate";
private FirebaseAuth firebaseAuth;
private TextView textViewUserEmail;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    firebaseAuth = FirebaseAuth.getInstance();
    if(firebaseAuth.getCurrentUser()==null)
    {
        startActivity(new Intent(this,Giris.class));
        finish();
    }
    setContentView(R.layout.activity_main);

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Navigation itemlerinin click olaylarını burada yapıyoruz.
    int id = item.getItemId();
    if (id == R.id.nav_kullanici)
    {
        startActivity(new Intent(MainActivity.this,Hesabim.class));

    }
    else if (id == R.id.nav_hatirlatma)
    {
        startActivity(new Intent(MainActivity.this,AyarlarActivity.class));
    }
    else if (id == R.id.nav_ipucu)
    {
        startActivity(new Intent(MainActivity.this,IpuclariSayfasi.class));
    }

    else if (id == R.id.nav_oyla)
    {

    }
    else if (id == R.id.nav_cikis)
    {

        firebaseAuth.signOut();
        finish();
        startActivity(new Intent(MainActivity.this, Giris.class));

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;

}
}
</code>```

答:
You may want to check if you have properly configured your application to use Firebase. Add google-services plugin in the build.gradle file in the app directory of your project.

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

See this tutorial for more information.

In addition to that, add FCM dependency. Confirm if you have this dependency in your app/build.gradle file.

```<code>compile 'com.google.firebase:firebase-messaging:10.2.0'
</code>```

Suggested solutions in this SO post might also help.

Body:
I'm using Firebase Auth stuff in project. Today I decided to integrate FCM into my project. But I couldn't ANY notification from my Firebase console. I also tried re-download .json file but it didn't work out. Do you guys have any idea about my problem?

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yunus.ototakip">

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permisson.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"></uses-permission>
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/oto_takip"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MyIntro"
        android:theme="@style/FullscreenTheme" />
    <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".AracEkle"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".InternetCon"
        android:theme="@style/FullscreenTheme" />
    <activity
        android:name=".IpuclariSayfasi"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".TrafficActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".EngineActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".AidActivity"
        android:theme="@style/AppTheme.NoActionBar" />

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" />

    <activity
        android:name=".AyarlarActivity"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <activity android:name=".Hesabim"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <activity android:name=".Giris"
        android:theme="@style/AppTheme.NoActionBar"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".KayitOl"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <service
        android:name=".FirebaseMessageService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

    <service
        android:name=".FirebaseIDService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

</application>

FirebaseMessageService.java

public void onMessageReceived(RemoteMessage remoteMessage){
    sendNotification(remoteMessage.getNotification().getBody());
}

private void sendNotification(String messageBody){
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.oto_takip)
            .setContentText(messageBody)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}

FirebaseIDService.java

 public class FirebaseIDService extends FirebaseInstanceIdService
 {
private static final String TAG ="FirebaseIDService";
@Override
public void onTokenRefresh() {
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Token: " + refreshedToken);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String refreshedToken)
{
}
   }

I think the problem is not up to my MainActiviy.java but I'm gonna show it to you just in case.

MainActivity.java

 public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener{

private Fragment fragment;
private FragmentManager fragmentManager;
public TextView tarih;
final String PREFS_NAME = "MyPrefsFile";
final String SHAREDPREF_DATE = "SharedPrefDate";
private FirebaseAuth firebaseAuth;
private TextView textViewUserEmail;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    firebaseAuth = FirebaseAuth.getInstance();
    if(firebaseAuth.getCurrentUser()==null)
    {
        startActivity(new Intent(this,Giris.class));
        finish();
    }
    setContentView(R.layout.activity_main);

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Navigation itemlerinin click olaylarını burada yapıyoruz.
    int id = item.getItemId();
    if (id == R.id.nav_kullanici)
    {
        startActivity(new Intent(MainActivity.this,Hesabim.class));

    }
    else if (id == R.id.nav_hatirlatma)
    {
        startActivity(new Intent(MainActivity.this,AyarlarActivity.class));
    }
    else if (id == R.id.nav_ipucu)
    {
        startActivity(new Intent(MainActivity.this,IpuclariSayfasi.class));
    }

    else if (id == R.id.nav_oyla)
    {

    }
    else if (id == R.id.nav_cikis)
    {

        firebaseAuth.signOut();
        finish();
        startActivity(new Intent(MainActivity.this, Giris.class));

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;

}
}

Body:
You may want to check if you have properly configured your application to use Firebase. Add google-services plugin in the build.gradle file in the app directory of your project.

apply plugin: 'com.google.gms.google-services'

See this tutorial for more information.

In addition to that, add FCM dependency. Confirm if you have this dependency in your app/build.gradle file.

compile 'com.google.firebase:firebase-messaging:10.2.0'

Suggested solutions in this SO post might also help.


问:
save state of togglebutton android
Can anyone tell me why this doesn't work please? I am trying to save the state of the togglebutton, but everytime I close the app and start again, it goes back to off. I want the state to be remembered, so when someone adds something to their favourites, to remember it as being added to favourite.

private String state = "State";

```<code>public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recipe_menu, menu);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setChecked(readState());
    toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                // The toggle is enabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_black_24dp));
            else
                // The toggle is disabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));

            saveState(isChecked);
        }
    });
    return super.onCreateOptionsMenu(menu);
}

private void saveState(boolean isFavourite) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putBoolean(state, isFavourite).apply();
}
private boolean readState() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    return sharedPreferences.getBoolean(state, true);
}
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));
    toggleButton.setChecked(readState());
}
</code>```

答:
you're reading from one SharedPreferences file, but writing into a different one.

change the init line of sharedPreferences in saveState to:

```<code>SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
</code>```

Also, instead of using setOnClickListener, you should instead use setOnCheckedChangeListener, see the docs, and the example code:

```<code>toggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
    }
});
</code>```

UPDATE

Full code with fixes:

```<code>public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recipe_menu, menu);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setChecked(readState());
    toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // The toggle is enabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_black_24dp));
            } else {
                // The toggle is disabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));
            }
            saveState(isChecked);
        }
    });
    return super.onCreateOptionsMenu(menu);
}

private void saveState(boolean isFavourite) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putBoolean("State", isFavourite).apply();
}
private boolean readState() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    return sharedPreferences.getBoolean("State", true);
}
</code>```

Title: save state of togglebutton android

Body:
Can anyone tell me why this doesn't work please? I am trying to save the state of the togglebutton, but everytime I close the app and start again, it goes back to off. I want the state to be remembered, so when someone adds something to their favourites, to remember it as being added to favourite.

private String state = "State";

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recipe_menu, menu);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setChecked(readState());
    toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                // The toggle is enabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_black_24dp));
            else
                // The toggle is disabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));

            saveState(isChecked);
        }
    });
    return super.onCreateOptionsMenu(menu);
}

private void saveState(boolean isFavourite) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putBoolean(state, isFavourite).apply();
}
private boolean readState() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    return sharedPreferences.getBoolean(state, true);
}
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));
    toggleButton.setChecked(readState());
}

Body:
you're reading from one SharedPreferences file, but writing into a different one.

change the init line of sharedPreferences in saveState to:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Also, instead of using setOnClickListener, you should instead use setOnCheckedChangeListener, see the docs, and the example code:

toggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
    }
});

UPDATE

Full code with fixes:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recipe_menu, menu);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setChecked(readState());
    toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // The toggle is enabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_black_24dp));
            } else {
                // The toggle is disabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));
            }
            saveState(isChecked);
        }
    });
    return super.onCreateOptionsMenu(menu);
}

private void saveState(boolean isFavourite) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putBoolean("State", isFavourite).apply();
}
private boolean readState() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    return sharedPreferences.getBoolean("State", true);
}


问:
Are multiple gcm_sender_ids mandatory for multiple site web push?
We are a company that operates about 500 large and small sites.
(Self, outsourcing ...)

We are trying to attach a notification to these sites.
I know that when I sign in with my Google Developer Center account and get the gcm service, I get one gcm_sender_id.

Is there anything wrong with using this as a 'web push' on 500 large and small sites with one sender_id issued?
If you send a web push to each member at 500 sites at the same time, it could be hundreds of thousands to millions.
(Of course the maximum amount you can request at a time is 1000 times.)
I would like to know if there are any problems with the addition of such restrictions.

We see similar administration agencies, and they seem to be issuing different gcm_sender_id to each new site.
Can this issue multiple gcm_sender_id in one Developer Center account?
I asked him a little bit, and he said it was automated.

If you are a member of a management agency site, you can create a site by simply registering the site, and gcm_sender_id is automatically issued in real time.

In that short amount of time, I would like to sign up for a Google Developer Center account and give me one gcm_sender_id right away, and wonder if gcm_sender_id will be issued right away.
(The company I mentioned is not affiliated with Google.)

Also, if you want to create a web push for 500 sites, why do you have to issue gcm_sender_id differently or why?

答:
You can use the same sender ID for multiple domains.

The problem is that in case of abuses it might be difficult to identify the actual sender among the various customers (if each website belongs to a different company). So I would say that the best approach is to create a different sender ID for each customer (as the agency has suggested).
On the other hand, if the same customer has a domain with many subdomains, for example, you can use a single sender ID, since the sender / customer is actually the same.

However, I recommend that you use VAPID (standard) to automate the registration process of the sender with Firebase Cloud Messaging (previously GCM). The use of a sender ID is a legacy proprietary method and might get deprecated in the future.

Read this article to get started with VAPID, or use a web push service  that supports VAPID automatically and saves you a lot of time and trouble.

ContentLicense: CC BY-SA 4.0


问:
File(s) and InputStream/OutputStream
Hello Stack Overflow community,

I am doing multistep processing on some data I am receiving with a java Servlet.  The current process I have is that I input the files to a server using Apache File Upload and convert them to a File. Then once input1 is populated with data, I run through a flow similar to this (where the process functions are xsl transforms):

```<code>File input1 = new File(FILE_NAME);  // <---this is populated with data
File output1 = new File(TEMP_FILE); // <---this is the temporary file

InputStream read = new FileInputStream(input1);
OuputStream out = new FileOutputStream(output1);

process1ThatReadsProcessesOutputs( read, out);

out.close();
read.close();

//this is basically a repeat of the above process!
File output2 = new File(RESULT_FILE);  // <--- This is the result file
InputStream read1 = new FileInputStream(output1);
OutputStream out1 = new FileOutputStream(output2);
Process2ThatReadsProcessesOutputs( read1, out1);
read1.close();
out1.close();
…
</code>```

So my question is if there is a better way to do this so I do not have to create those temporary Files and recreate streams to those Files? (I am assuming I am incurring a decent performace penatly)

I saw this Most Efficient Way to create InputStream from OutputStream but I am not sure if this is the best route to go...

答:
Java 9 brings a new answer to the question:</p>

```<code>// All bytes from an InputStream at once
byte[] result = new ByteArrayInputStream(buf)
    .readAllBytes();

// Directly redirect an InputStream to an OutputStream
new ByteArrayInputStream(buf)
    .transferTo(System.out);
</code>```

Title: File(s) and InputStream/OutputStream

Body:
Hello Stack Overflow community,

I am doing multistep processing on some data I am receiving with a java Servlet.  The current process I have is that I input the files to a server using Apache File Upload and convert them to a File. Then once input1 is populated with data, I run through a flow similar to this (where the process functions are xsl transforms):

File input1 = new File(FILE_NAME);  // <---this is populated with data
File output1 = new File(TEMP_FILE); // <---this is the temporary file

InputStream read = new FileInputStream(input1);
OuputStream out = new FileOutputStream(output1);

process1ThatReadsProcessesOutputs( read, out);

out.close();
read.close();

//this is basically a repeat of the above process!
File output2 = new File(RESULT_FILE);  // <--- This is the result file
InputStream read1 = new FileInputStream(output1);
OutputStream out1 = new FileOutputStream(output2);
Process2ThatReadsProcessesOutputs( read1, out1);
read1.close();
out1.close();
…

So my question is if there is a better way to do this so I do not have to create those temporary Files and recreate streams to those Files? (I am assuming I am incurring a decent performace penatly)

I saw this Most Efficient Way to create InputStream from OutputStream but I am not sure if this is the best route to go...

Body:
Java 9 brings a new answer to the question:

// All bytes from an InputStream at once
byte[] result = new ByteArrayInputStream(buf)
    .readAllBytes();

// Directly redirect an InputStream to an OutputStream
new ByteArrayInputStream(buf)
    .transferTo(System.out);


问:
Using toCharArray to check if String has any non-digits
So I'm new to java and trying to write some code for a project. I'm trying to use toCharArray to check if String has any non-digits. This is my code I've written so far:

```<code>public void setMobile(String mobile)
{
   boolean ok = true;
   char[] mob = mobile.toCharArray();
   for(int index = 0; Character.isDigit(mob) == true; index++)
   {

   }

   if(ok == true)
   {
       this.mobile = mobile;
   }
}
</code>```

I'm trying to check if mobile has any letter, and if so, do not assign mobile to this.mobile.

答:
Try using regular expressions. \\d matches digits from 0 to 9 and + means that there must be at least 1 digit.

```<code>public void setMobile(String mobile) {
    this.mobile = (mobile.matches("\\d+")) ? mobile : this.mobile;
}
</code>```

The code above uses ternary operator, but this also works:

```<code>public void setMobile(String mobile) {
    if (mobile.matches("\\d+"))
        this.mobile = mobile;
}
</code>```

Body:
So I'm new to java and trying to write some code for a project. I'm trying to use toCharArray to check if String has any non-digits. This is my code I've written so far:

public void setMobile(String mobile)
{
   boolean ok = true;
   char[] mob = mobile.toCharArray();
   for(int index = 0; Character.isDigit(mob) == true; index++)
   {

   }

   if(ok == true)
   {
       this.mobile = mobile;
   }
}

I'm trying to check if mobile has any letter, and if so, do not assign mobile to this.mobile.

Body:
Try using regular expressions. \\d matches digits from 0 to 9 and + means that there must be at least 1 digit.

public void setMobile(String mobile) {
    this.mobile = (mobile.matches("\\d+")) ? mobile : this.mobile;
}

The code above uses ternary operator, but this also works:

public void setMobile(String mobile) {
    if (mobile.matches("\\d+"))
        this.mobile = mobile;
}


问:
Implement Google Play account settings button
I have implemented signing-in functionnalities in my Android game (which uses libgdx) via the BaseGameUtils class, but I saw a neat feature in a game (Jetpack Joyride) that I'd like to reproduce. On their homescreen, if the user is logged in, the "sign in google" button opens the Google Play account's settings (where the user can change his image, sign out and see his Google Play Services version).

I would like to have something similar, but have no idea how to call and open this page. I browsed the whole Google Play documentation but couldn't find anything about it.

What should I use to open this specific page ?

答:
Note that you must follow the branding guidelines if you want to implement that. See Building a custom Google Sign-In button for more information.

Also, you may want to use the following approaches discussed in providing a sign-in button:

Include a com.google.android.gms.common.SignInButton on the main activity layout as described in the previous section; or

Design a custom sign-in button according to the Google Sign-In branding guidelines.


问:
PreferenceFragmentCompat requires preferenceTheme to be set
With the new PreferenceFragmentCompat from the v7 Preference Support Library: http://developer.android.com/tools/support-library/features.html#v7-preference, I get this error

```<code>E  java.lang.IllegalStateException: Must specify preferenceTheme in theme
E      at android.support.v7.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:202)
</code>```

What theme should be set?

Update: I have tried using

<item name="preferenceTheme">@style/PreferenceThemeOverlay</item>

as suggested by @Bogato but it doesn't look right and looks very Holo even on Lollipop.

Support library:

Native preferences:

答:
Add this code to your styles.xml and modify it according. It should work fine.

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
</style>

<style name="PreferenceThemeOverlay">
    <item name="preferenceScreenStyle">@style/Preference.PreferenceScreen</item>
    <item name="preferenceFragmentStyle">@style/PreferenceFragment</item>
    <item name="preferenceCategoryStyle">@style/Preference.Category</item>
    <item name="preferenceStyle">@style/Preference</item>
    <item name="preferenceInformationStyle">@style/Preference.Information</item>
    <item name="checkBoxPreferenceStyle">@style/Preference.CheckBoxPreference</item>
    <item name="switchPreferenceCompatStyle">@style/Preference.SwitchPreferenceCompat</item>
    <item name="dialogPreferenceStyle">@style/Preference.DialogPreference</item>
    <item name="editTextPreferenceStyle">@style/Preference.DialogPreference.EditTextPreference</item>
    <item name="preferenceFragmentListStyle">@style/PreferenceFragmentList</item>
</style>
</code>```

Body:
With the new PreferenceFragmentCompat from the v7 Preference Support Library: http://developer.android.com/tools/support-library/features.html#v7-preference, I get this error

E  java.lang.IllegalStateException: Must specify preferenceTheme in theme
E      at android.support.v7.preference.PreferenceFragmentCompat.onCreate(PreferenceFragmentCompat.java:202)

What theme should be set?

Update: I have tried using

<item name="preferenceTheme">@style/PreferenceThemeOverlay</item>

as suggested by @Bogato but it doesn't look right and looks very Holo even on Lollipop.

Support library:

Native preferences:

Body:
Add this code to your styles.xml and modify it according. It should work fine.

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
</style>

<style name="PreferenceThemeOverlay">
    <item name="preferenceScreenStyle">@style/Preference.PreferenceScreen</item>
    <item name="preferenceFragmentStyle">@style/PreferenceFragment</item>
    <item name="preferenceCategoryStyle">@style/Preference.Category</item>
    <item name="preferenceStyle">@style/Preference</item>
    <item name="preferenceInformationStyle">@style/Preference.Information</item>
    <item name="checkBoxPreferenceStyle">@style/Preference.CheckBoxPreference</item>
    <item name="switchPreferenceCompatStyle">@style/Preference.SwitchPreferenceCompat</item>
    <item name="dialogPreferenceStyle">@style/Preference.DialogPreference</item>
    <item name="editTextPreferenceStyle">@style/Preference.DialogPreference.EditTextPreference</item>
    <item name="preferenceFragmentListStyle">@style/PreferenceFragmentList</item>
</style>


问:
Need to solve this Rate with FloatingDecimal
I try to display the content of csv file into different textboxes but it keeps on saying

java.lang.NumberFormatException:
For input string: "Rate" (in sun.misc.FloatingDecimal)

Do anyone have any idea how to solve this?

答: I am not sure what the contents are for Rate. Try using double instead of Float to store and display rate. </p>


问:
Not able to execute remotely placed ssh script with parameter using paramiko ssh client
My code read like this-

```<code>import paramiko
import time
import sys

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def runScripts():
    parameter1 = 1000
    client.connect('mysite.com', username='user', password='pass')
    print ("Logged in into Site server")
    stdin, stdout, stderr = client.exec_command("cd parent_folder/Sub_folder/script_folder; ./script1.sh %s" % parameter1)
    print ("Script executed perfectly")
    client.close()

runScripts()
</code>```

And i got output on console as below-

```<code>Logged in into Site server
Script executed perfectly
</code>```

But checked the file which was going to get affected due to the script.sh 1000 has no changes. the problem is not with script.sh because i can run the same manually and it behaves as expected.

Is client not able to detect end of the command?

答:
I found out answer to my own query on a video over youtube for interactive commands.

Some how it was problem with command termination and client was unable to find end of it as it is not unix/system defined command ("system commands like ls -lrt, cd, grep works perfectly fine with client")

So i tried channel like below code to execute the shell script located on server which needs parameter-

def runScripts():

```<code>parameter1 = 1000
client.connect('mysite.com', username='user', password='pass')
channel = client.invoke_shell()
print ("Logged in into Site server")
channel.send("cd parent_folder/Sub_folder/script_folder; ./script1.sh %s" % parameter1)
print ("Script executed perfectly")
client.close()
</code>```

runScripts()

In above runScripts function i have introduced new channel which invokes shell, and then we can send any command or data over this channel once send command gets completed the execution happens andchannel closes.

Accept the answer if its useful to you guys too.Thank you.

Body:
My code read like this-

import paramiko
import time
import sys

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def runScripts():
    parameter1 = 1000
    client.connect('mysite.com', username='user', password='pass')
    print ("Logged in into Site server")
    stdin, stdout, stderr = client.exec_command("cd parent_folder/Sub_folder/script_folder; ./script1.sh %s" % parameter1)
    print ("Script executed perfectly")
    client.close()

runScripts()

And i got output on console as below-

Logged in into Site server
Script executed perfectly

But checked the file which was going to get affected due to the script.sh 1000 has no changes. the problem is not with script.sh because i can run the same manually and it behaves as expected.

Is client not able to detect end of the command?

Body:
I found out answer to my own query on a video over youtube for interactive commands.

Some how it was problem with command termination and client was unable to find end of it as it is not unix/system defined command ("system commands like ls -lrt, cd, grep works perfectly fine with client")

So i tried channel like below code to execute the shell script located on server which needs parameter-

def runScripts():

parameter1 = 1000
client.connect('mysite.com', username='user', password='pass')
channel = client.invoke_shell()
print ("Logged in into Site server")
channel.send("cd parent_folder/Sub_folder/script_folder; ./script1.sh %s" % parameter1)
print ("Script executed perfectly")
client.close()

runScripts()

In above runScripts function i have introduced new channel which invokes shell, and then we can send any command or data over this channel once send command gets completed the execution happens andchannel closes.

Accept the answer if its useful to you guys too.Thank you.


问:
Enterprise Design Pattern Question
Something on my mind about structuring a system at a high level.

Let's say you have a system with the following layers:

UI

Service Layer

Domain Model

Data Access

The service layer is used to populate a graph of objects in the domain model. In an attempt to avoid coupling, the domain model will be not be persistence aware and will not have any dependencies on any data access layer.

However, using this approach how would one object in the domain model be able to call other objects without being able to load them with persistence, thus coupling everything together - which I'd be trying to avoid.

e.g. an Order Object would need to check an Inventory object and would obviously need to tell the Inventory object to load in some way, or populate it somehow.

Any thoughts?

答:
I felt this was different enough from my previous answer, so here's a new one.

Another approach is to leverage the concept of Inversion of Control (IoC).  Build an Interface that your Data Access layer implements.  Each of the DAL methods should take a list of parameters and return a Data Table.

The service layer would instantiate the DAL through the interface and pass that reference to your Domain Model.  The domain model would then make it's own calls into the DAL, using the interface methods, and decide when it needs to load child objects or whatever.

Something like:

```<code>interface IDBModel {
  DataTable LoadUser(Int32 userId);
}

class MyDbModel : IDBModel {
  DataTable LoadUser(Int32 userId) {
    // make the appropriate DB calls here, return a data table
  }
}

class User {
  public User(IDBModel dbModel, Int32 userId) {
    DataTable data = dbModel.LoadUser(userId);
    // assign properties.. load any additional data as necessary
  }
// You can do cool things like call User.Save()
// and have the object validate and save itself to the passed in
// datamodel.  Makes for simpler coding.
}

class MyServiceLayer {
  public User GetUser(Int32 userId) {
    IDBModel model = new MyDbModel();

    return new User(model, userId);
  }
}
</code>```

With this mechanism, you can actually swap out your db models on demand.  For example, if you decide to support multiple databases then you can have code that is specific to a particular database vendors way of doing things and just have the service layer pick which one to use.

The domain objects themselves are responsible for loading their own data and you can keep any necessary business logic within the domain model.  Another point is that the Domain Model doesn't have a direct dependency on the data layer, which preserves your mocking ability for independent testing of business logic.

Further, the DAL has no knowledge of the domain objects, so you can swap those out as necessary or even just test the DAL independently.

Title: Enterprise Design Pattern Question

Body:
I felt this was different enough from my previous answer, so here's a new one.

Another approach is to leverage the concept of Inversion of Control (IoC).  Build an Interface that your Data Access layer implements.  Each of the DAL methods should take a list of parameters and return a Data Table.

The service layer would instantiate the DAL through the interface and pass that reference to your Domain Model.  The domain model would then make it's own calls into the DAL, using the interface methods, and decide when it needs to load child objects or whatever.

Something like:

interface IDBModel {
  DataTable LoadUser(Int32 userId);
}

class MyDbModel : IDBModel {
  DataTable LoadUser(Int32 userId) {
    // make the appropriate DB calls here, return a data table
  }
}

class User {
  public User(IDBModel dbModel, Int32 userId) {
    DataTable data = dbModel.LoadUser(userId);
    // assign properties.. load any additional data as necessary
  }
// You can do cool things like call User.Save()
// and have the object validate and save itself to the passed in
// datamodel.  Makes for simpler coding.
}

class MyServiceLayer {
  public User GetUser(Int32 userId) {
    IDBModel model = new MyDbModel();

    return new User(model, userId);
  }
}

With this mechanism, you can actually swap out your db models on demand.  For example, if you decide to support multiple databases then you can have code that is specific to a particular database vendors way of doing things and just have the service layer pick which one to use.

The domain objects themselves are responsible for loading their own data and you can keep any necessary business logic within the domain model.  Another point is that the Domain Model doesn't have a direct dependency on the data layer, which preserves your mocking ability for independent testing of business logic.

Further, the DAL has no knowledge of the domain objects, so you can swap those out as necessary or even just test the DAL independently.


问:
How to fetch mysql data into html table with vertical header?
I'm trying to fetch mySQL data into html table with vertical header. My html table code is in the following code :

```<code><table border="1" align="center">
<thead>
    <tr>
        <th>No.</th>
        <?php
            while ($row1 = mysqli_fetch_assoc($q)) {
                echo "<td>$no</td>";
                $no++;
            }
        ?>
    </tr>
    <tr>
        <th>Term</th>
        <?php
            while ($row2 = mysqli_fetch_assoc($q)) {
                echo "<td>".$row2['term']."</td>";
            }
        ?>
    </tr>
    <tr>
        <th>Normalisasi TF.IDF</th>
        <?php
            while ($row3 = mysqli_fetch_assoc($q)) {
                echo "<td>".$row3['tf_idf_normalisasi']."</td>";
            }
        ?>
    </tr>
</thead>
</code>```

Here's screenshot of my table :

But mySQL data are not displayed on 2nd and 3rd
. What is wrong with my code ? Can someone tell me how to make it work ? Thank you.

答:
Generate td elements HTML with a single loop otherwise mysqli_fetch_assoc method returns NULL in second and third loop since you are already fetched all rows.

```<code><?php
    $td1 = '';
    $td2 = '';
    $td3 = '';
    while ($row = mysqli_fetch_assoc($q)) {
        $td1 .= "<td>$no</td>";
        $td2 .= "<td>" . $row['term'] . "</td>";
        $td3 .= "<td>" . $row['tf_idf_normalisasi'] . "</td>";
        $no++;
    }
?>

<table border="1" align="center">
<thead>
    <tr>
        <th>No.</th>
        <?php echo $td1; ?>
    </tr>
    <tr>
        <th>Term</th>
        <?php echo $td2; ?>
    </tr>
    <tr>
        <th>Normalisasi TF.IDF</th>
        <?php echo $td3; ?>
    </tr>
</thead>
</code>```

Body:
I'm trying to fetch mySQL data into html table with vertical header. My html table code is in the following code :

        No.
        <?php
            while ($row1 = mysqli_fetch_assoc($q)) {
                echo "$no	";
                $no++;
            }
        ?>

        Term
        <?php
            while ($row2 = mysqli_fetch_assoc($q)) {
                echo "".$row2['term']."	";
            }
        ?>

        Normalisasi TF.IDF
        <?php
            while ($row3 = mysqli_fetch_assoc($q)) {
                echo "".$row3['tf_idf_normalisasi']."	";
            }
        ?>

Here's screenshot of my table :

But mySQL data are not displayed on 2nd and 3rd
. What is wrong with my code ? Can someone tell me how to make it work ? Thank you.

Body:
Generate td elements HTML with a single loop otherwise mysqli_fetch_assoc method returns NULL in second and third loop since you are already fetched all rows.

<?php
    $td1 = '';
    $td2 = '';
    $td3 = '';
    while ($row = mysqli_fetch_assoc($q)) {
        $td1 .= "<td>$no</td>";
        $td2 .= "<td>" . $row['term'] . "</td>";
        $td3 .= "<td>" . $row['tf_idf_normalisasi'] . "</td>";
        $no++;
    }
?>

<table border="1" align="center">
<thead>
    <tr>
        <th>No.</th>
        <?php echo $td1; ?>
    </tr>
    <tr>
        <th>Term</th>
        <?php echo $td2; ?>
    </tr>
    <tr>
        <th>Normalisasi TF.IDF</th>
        <?php echo $td3; ?>
    </tr>
</thead>


问:
How to convert HTML formatting inside google sheets rows to their correct formatted equivalent
I have been looking for a solution to convert a database I have with HTML formatting in one of the columns to its "normal" text equivalency in google sheets. A lot of the solutions I've found dealt with writing programs to do this or using Excel, so they unfortunately didn't pertain well enough.

For example in one of my columns I have;

Fast ( This character deals damage before non-Fast characters in combat.)

But I would like to be able to have a somewhat streamlined solution to convert the above to:

Fast (This character deals damage before non-Fast characters in combat.)

答:
AFAIK, with Google Sheet API, you can only format text within a cell. As mentioned in documentation, conditional formatting lets you format cells so that their appearance changes dynamically according to the value they contain, or to values in other cells.

You may want to request new feature here.


问:
How to install mysql-server in Ubuntu
I have mariadb  in my ubuntu system but it is not working properly , so i want to again install mysql in my system .

For Remove mariadb i have run these commands .

sudo apt-get --purge remove "mysql*"

sudo mv /etc/mysql/ /tmp/mysql_configs/

nano /etc/apt/sources.list

sudo apt-get update

sudo apt-get install mysql-server-5.6

but after step 5 it's give me these errors :

Reading package lists... Done
Building dependency tree

Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 libmysqlclient18 : Depends: mysql-common (= 5.6.30-1ubuntu14.04)
 mariadb-server-5.5 : Breaks: mysql-server-5.6
                      Breaks: virtual-mysql-server
 mariadb-server-core-5.5 : Conflicts: mysql-server-5.6
 mysql-server-5.6 : Depends: mysql-client-5.6 (>= 5.6.30-0ubuntu0.14.04.1)
                    Depends: mysql-server-core-5.6 (= 5.6.30-0ubuntu0.14.04.1)
                    Recommends: mysql-common-5.6 but it is not going to be installed
                    Breaks: virtual-mysql-server
W: Duplicate sources.list entry http://debian.datastax.com/community/ stable/main amd64 Packages (/var/lib/apt/lists/debian.datastax.com_community_dists_stable_main_binary-amd64_Packages)
W: Duplicate sources.list entry http://debian.datastax.com/community/ stable/main i386 Packages (/var/lib/apt/lists/debian.datastax.com_community_dists_stable_main_binary-i386_Packages)
W: You may want to run apt-get update to correct these problems
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

Can anyone give me suggestion how can i install mysql in my system . Thanks in advance .

答:
It's quite easy to install mysql on Ubuntu.

```<code>sudo apt-get update
sudo apt-get install mysql-server
</code>```

You'll be asked to create a new password for root user. Set a good password and you're ready to go.

You can also follow  this youtube videos for installation and basic understanding for Mysql

Title: How to install mysql-server in Ubuntu

Body:
It's quite easy to install mysql on Ubuntu.

sudo apt-get update
sudo apt-get install mysql-server

You'll be asked to create a new password for root user. Set a good password and you're ready to go.

You can also follow  this youtube videos for installation and basic understanding for Mysql