问:
Get property from derived class in base class
base.php:

```<code><?php namespace MyQuestion\Base;

abstract class BaseSetting
{
    public function GetValue($setting)
    {
        return $this->$setting;
    }
}
</code>```

derived.php

```<code><?php namespace MyQuestion\Configs;

use MyQuestion\Base;

class Settings extends BaseSetting
{
    private $a = 'value 1';
    private $b = 'value 2';
    private $c = "value 3";
}
</code>```

index.php

```<code>$abc = new Settings();
$mySettings = $abc->GetValue('a');
</code>```

I try to debug code. Something is broken in $this->setting. How can I do that? I have some settings file and I need to get values from them using a function. I don't want to define the same function in every setting file.

答:
You could only access the private properties in the class in which the properties are declared. In you case, it's the class of Settings.

I don't know what you want exactly, but a work around might be

```<code>class Settings extends BaseSetting
{
    private $a = 'value 1';
    private $b = 'value 2';
    private $c = "value 3";

    public function __get($attr)
    {
        return $this->$attr;
    }
}
</code>```

Then you could access the property by $mySettings = $abc->a;

Body:
base.php:

<?php namespace MyQuestion\Base;

abstract class BaseSetting
{
    public function GetValue($setting)
    {
        return $this->$setting;
    }
}

derived.php

<?php namespace MyQuestion\Configs;

use MyQuestion\Base;

class Settings extends BaseSetting
{
    private $a = 'value 1';
    private $b = 'value 2';
    private $c = "value 3";
}

index.php

$abc = new Settings();
$mySettings = $abc->GetValue('a');

I try to debug code. Something is broken in $this->setting. How can I do that? I have some settings file and I need to get values from them using a function. I don't want to define the same function in every setting file.

Body:
You could only access the private properties in the class in which the properties are declared. In you case, it's the class of Settings.

I don't know what you want exactly, but a work around might be

class Settings extends BaseSetting
{
    private $a = 'value 1';
    private $b = 'value 2';
    private $c = "value 3";

    public function __get($attr)
    {
        return $this->$attr;
    }
}

Then you could access the property by $mySettings = $abc->a;


来源: stackexchange

问:
SCTP one-to-many in Java
I'm working in Java to create a one-to-many connection using Java and SCTP protocol.

I've gotten a SctpMultiChannel up and running and I can receive messages, but is there something special needed to be done to send a message to all connections?

```<code>The error message:

java.net.SocketException: Invalid argument
    at sun.nio.ch.SctpChannelImpl.send0(Native Method)
    at sun.nio.ch.SctpMultiChannelImpl.send0(SctpMultiChannelImpl.java:976)
    at sun.nio.ch.SctpMultiChannelImpl.sendFromNativeBuffer(SctpMultiChannelImpl.java:888)
    at sun.nio.ch.SctpMultiChannelImpl.send(SctpMultiChannelImpl.java:847)
    at sun.nio.ch.SctpMultiChannelImpl.send(SctpMultiChannelImpl.java:824)
    at org.test.MultiServer.run(MultiServer.java:56)
</code>```

And the complete code:

```<code>SocketAddress serverSocketAddress = new InetSocketAddress(SOCKET_PORT);
    SctpMultiChannel smc;
    try {
      Logger.info("Start");
      smc = SctpMultiChannel.open().bind(serverSocketAddress);

      ByteBuffer buf = ByteBuffer.allocateDirect(160);
      Charset charset = Charset.forName("ISO-8859-1");
      CharsetDecoder decoder = charset.newDecoder();

      AssociationHandler assocHandler = new AssociationHandler();

      MessageInfo messageInfo;
      while ((messageInfo = smc.receive(buf, System.out, assocHandler)) != null) {
        Logger.debug(messageInfo.toString());
        buf.flip();
        Logger.debug(decoder.decode(buf).toString());
        Logger.info(smc.associations().size() + "");

        ByteBuffer buf1 = ByteBuffer.allocateDirect(60);
        CharBuffer cbuf1 = CharBuffer.allocate(60);
        charset = Charset.forName("ISO-8859-1");
        CharsetEncoder encoder = charset.newEncoder();
        cbuf1.put("foo").flip();
        encoder.encode(cbuf1, buf1, true);
        buf1.flip();

        for (Association ass : smc.associations()) {
          MessageInfo mi = MessageInfo.createOutgoing(ass, null, 1);
          smc.send(buf, mi);
        }
        cbuf1.clear();
        buf1.clear();
        buf1.flip();
      }
      smc.close();
    } catch (IOException e) {
      Logger.error("Server error");
      e.printStackTrace();
    }
</code>```

This is what I've done so far, my client sends a message and is then going to wait to receive a new message.
What I'm aiming for is to have a non-blocking approach so I can send and receive messages on the same channel, and not blockint with the receive query.

Anyone got any experience in this?

best,
Henrik

答:
From the error I can say that the MessageInfo is not correct. Try sending only one message without looping. Set the address statically.

Also the first send establishes the connection in case of SctpMultiChannel - how are you able to loop over the associations since they are not established? Is this the whole code?

ContentLicense: CC BY-SA 3.0

Title: SCTP one-to-many in Java

Body:
I'm working in Java to create a one-to-many connection using Java and SCTP protocol.

I've gotten a SctpMultiChannel up and running and I can receive messages, but is there something special needed to be done to send a message to all connections?

The error message:

java.net.SocketException: Invalid argument
    at sun.nio.ch.SctpChannelImpl.send0(Native Method)
    at sun.nio.ch.SctpMultiChannelImpl.send0(SctpMultiChannelImpl.java:976)
    at sun.nio.ch.SctpMultiChannelImpl.sendFromNativeBuffer(SctpMultiChannelImpl.java:888)
    at sun.nio.ch.SctpMultiChannelImpl.send(SctpMultiChannelImpl.java:847)
    at sun.nio.ch.SctpMultiChannelImpl.send(SctpMultiChannelImpl.java:824)
    at org.test.MultiServer.run(MultiServer.java:56)

And the complete code:

SocketAddress serverSocketAddress = new InetSocketAddress(SOCKET_PORT);
    SctpMultiChannel smc;
    try {
      Logger.info("Start");
      smc = SctpMultiChannel.open().bind(serverSocketAddress);

      ByteBuffer buf = ByteBuffer.allocateDirect(160);
      Charset charset = Charset.forName("ISO-8859-1");
      CharsetDecoder decoder = charset.newDecoder();

      AssociationHandler assocHandler = new AssociationHandler();

      MessageInfo messageInfo;
      while ((messageInfo = smc.receive(buf, System.out, assocHandler)) != null) {
        Logger.debug(messageInfo.toString());
        buf.flip();
        Logger.debug(decoder.decode(buf).toString());
        Logger.info(smc.associations().size() + "");

        ByteBuffer buf1 = ByteBuffer.allocateDirect(60);
        CharBuffer cbuf1 = CharBuffer.allocate(60);
        charset = Charset.forName("ISO-8859-1");
        CharsetEncoder encoder = charset.newEncoder();
        cbuf1.put("foo").flip();
        encoder.encode(cbuf1, buf1, true);
        buf1.flip();

        for (Association ass : smc.associations()) {
          MessageInfo mi = MessageInfo.createOutgoing(ass, null, 1);
          smc.send(buf, mi);
        }
        cbuf1.clear();
        buf1.clear();
        buf1.flip();
      }
      smc.close();
    } catch (IOException e) {
      Logger.error("Server error");
      e.printStackTrace();
    }

This is what I've done so far, my client sends a message and is then going to wait to receive a new message.
What I'm aiming for is to have a non-blocking approach so I can send and receive messages on the same channel, and not blockint with the receive query.

Anyone got any experience in this?

best,
Henrik


答:
Something like this? (Taking table and column names from the query provided in the comments: select ignitionstatus,stringdatetime from processedrawdata) This uses a CTE and ROW_NUMBER to add a contiguous integer sequence to the rows:

```<code>WITH numbered_ignition_states AS
(
    SELECT   row_num = ROW_NUMBER() OVER ( ORDER BY stringdatetime ),
             ignitionstatus,
             stringdatetime
    FROM     processedrawdata
    ORDER BY stringdatetime
)
SELECT i1.ignitionstatus, i1.stringdatetime
FROM numbered_ignition_states i1, numbered_ignition_states i2
WHERE i1.row_num = 1 OR i1.row_num = i2.row_num + 1 AND i1.ignitionstatus != i2.ignitionstatus;
</code>```

<s>Original suggestion, before more information was provided, assuming the table is called ignition_states and it has a contiguous integer primary key column id.

```<code>SELECT i1.ignition_status, i1.date_time
FROM ignition_states i1, ignition_states i2
WHERE i1.id = 1 OR i1.id = i2.id + 1 AND i1.ignition_status != i2.ignition_status;
</code>```

</s>

Title: distinct binary number in sql server

Body:
I have ignition status 1 and 0 every 10 minutes of interval time.

How to get distinct value like I won't repeating 1 and 0 number

When it's 1 with date time then next 0 will show and then next 1 will show

    ignition status   date time
    1                 2017-06-04  00:00:13.000
    0                 2017-06-04  02:36:29.000
    1                 2017-06-04  07:43:52.000
    0                 2017-06-04  23:56:18.000

query
select top 100 ignitionstatus,datetime from rawdata
actual output
ignitionstatus  stringdatetime
1              2017-05-26 17:17:50.000
1              2017-05-26 17:18:10.000
0              2017-05-26 17:18:30.000
1              2017-05-26 17:18:50.000
0              2017-05-26 17:19:30.000
1              2017-05-26 17:19:10.000
1              2017-05-26 17:20:10.000
we required
1              2017-05-26 17:17:50.000
0              2017-05-26 17:18:30.000
1              2017-05-26 17:18:50.000
1              2017-05-26 17:19:10.000

Body:
Something like this? (Taking table and column names from the query provided in the comments: select ignitionstatus,stringdatetime from processedrawdata) This uses a CTE and ROW_NUMBER to add a contiguous integer sequence to the rows:

WITH numbered_ignition_states AS
(
    SELECT   row_num = ROW_NUMBER() OVER ( ORDER BY stringdatetime ),
             ignitionstatus,
             stringdatetime
    FROM     processedrawdata
    ORDER BY stringdatetime
)
SELECT i1.ignitionstatus, i1.stringdatetime
FROM numbered_ignition_states i1, numbered_ignition_states i2
WHERE i1.row_num = 1 OR i1.row_num = i2.row_num + 1 AND i1.ignitionstatus != i2.ignitionstatus;

<s>Original suggestion, before more information was provided, assuming the table is called ignition_states and it has a contiguous integer primary key column id.

SELECT i1.ignition_status, i1.date_time
FROM ignition_states i1, ignition_states i2
WHERE i1.id = 1 OR i1.id = i2.id + 1 AND i1.ignition_status != i2.ignition_status;

</s>


问:
Spacing between currency symbol and value: iOS swift 3
I am having an app with IAP. I need to show the prices with values based on location. I have made till this. Now I am able to display the prices based on location.

However, I need some spacing between currency symbol and the value.
i.e, I need $ 9.99 (currently it shows $9.99).

FYI: I am getting the price from itunes (used a variable to get the price got from itunes and displaying it in a textview).

I have followed this without success: NSNumberFormatter paddingPosition doesn't work

I have also referred this, but it does not work as well:
Swift 3 and NumberFormatter (.currency) == ¤?

Any suggestions?

I am doing this:

```<code>var index: Int = 0 {
    didSet {

        var monthlyValue = String()

        if prefs.value(forKey: "monthly") != nil {

            monthlyValue = prefs.value(forKey: "monthly") as! String

        }

        let subcharges : Array<String>   = ["Free but limited just to get started","or \(monthlyValue) Billed Monthly",""]

        let yearlypermonth = Int()

        var mycurrency1 = String()

        if prefs.value(forKey: "yearly") != nil {

            let yearlyvalue = prefs.value(forKey: "yearly") as! String

            print("wallet view yearlyvalue: \(yearlyvalue)")

            let firstProduct  = StoreManager.shared.productsFromStore[0]

            if let mycurrency = firstProduct.priceLocale.currencySymbol {

                print("mycurrency: \(mycurrency)")

                mycurrency1 = mycurrency
                prefs.set(mycurrency, forKey: "mycurrency")

            }

            let formatter = NumberFormatter()
            formatter.numberStyle = .currency
//                formatter.paddingPosition = .afterPrefix
//
//                //formatter.locale = Locale(identifier: "en_US")
//                formatter.paddingCharacter = " "
//                formatter.formatWidth = 7

            let number1 = formatter.number(from: yearlyvalue)

            print("wallet view number1: \(number1)")

            let secondProd = StoreManager.shared.productsFromStore[1]

            let numberFormatter = NumberFormatter()
//                numberFormatter.paddingPosition = .afterPrefix
//                numberFormatter.paddingCharacter = " "
//                numberFormatter.formatWidth = 7
            // Get its price from iTunes Connect
            numberFormatter.locale = secondProd.priceLocale
            let price2Str = numberFormatter.string(from: secondProd.price)

            let currencynumbers2 =  secondProd.price.doubleValue / 12

            monthonValueforaYear = String(format: "%.2f", currencynumbers2)

            print("walletview VC monthonValueforaYear: \(monthonValueforaYear)")

            //prefs.set(price2Str, forKey: "yearly")
            prefs.set(monthonValueforaYear, forKey: "monthonValueforaYear")

        }
        var charges : Array<String> = ["\(mycurrency1) 0/m","\(mycurrency1 + monthonValueforaYear)/m","Coming Soon"]

        print("wallet view charges: \(charges)")

        self.Headingtitle.text    = Headingarray[index]
        self.planchargelabel.text  = charges[index]
        self.subchargelabel.text = subcharges[index]
</code>```

Interestingly, for subchargelabel value, I get a little spacing

The commented section was uncommented while I tried running the app. Just so you know it

Thanks for your help!

答:
Try to format your required string as below.</p>

```<code>let priceWithSpace: String? = firstProduct.priceLocale.currencySymbol + " " +   product.price
</code>```

Body:
I am having an app with IAP. I need to show the prices with values based on location. I have made till this. Now I am able to display the prices based on location.

However, I need some spacing between currency symbol and the value.
i.e, I need $ 9.99 (currently it shows $9.99).

FYI: I am getting the price from itunes (used a variable to get the price got from itunes and displaying it in a textview).

I have followed this without success: NSNumberFormatter paddingPosition doesn't work

I have also referred this, but it does not work as well:
Swift 3 and NumberFormatter (.currency) == ¤?

Any suggestions?

I am doing this:

var index: Int = 0 {
    didSet {

        var monthlyValue = String()

        if prefs.value(forKey: "monthly") != nil {

            monthlyValue = prefs.value(forKey: "monthly") as! String

        }

        let subcharges : Array<String>   = ["Free but limited just to get started","or \(monthlyValue) Billed Monthly",""]

        let yearlypermonth = Int()

        var mycurrency1 = String()

        if prefs.value(forKey: "yearly") != nil {

            let yearlyvalue = prefs.value(forKey: "yearly") as! String

            print("wallet view yearlyvalue: \(yearlyvalue)")

            let firstProduct  = StoreManager.shared.productsFromStore[0]

            if let mycurrency = firstProduct.priceLocale.currencySymbol {

                print("mycurrency: \(mycurrency)")

                mycurrency1 = mycurrency
                prefs.set(mycurrency, forKey: "mycurrency")

            }

            let formatter = NumberFormatter()
            formatter.numberStyle = .currency
//                formatter.paddingPosition = .afterPrefix
//
//                //formatter.locale = Locale(identifier: "en_US")
//                formatter.paddingCharacter = " "
//                formatter.formatWidth = 7

            let number1 = formatter.number(from: yearlyvalue)

            print("wallet view number1: \(number1)")

            let secondProd = StoreManager.shared.productsFromStore[1]

            let numberFormatter = NumberFormatter()
//                numberFormatter.paddingPosition = .afterPrefix
//                numberFormatter.paddingCharacter = " "
//                numberFormatter.formatWidth = 7
            // Get its price from iTunes Connect
            numberFormatter.locale = secondProd.priceLocale
            let price2Str = numberFormatter.string(from: secondProd.price)

            let currencynumbers2 =  secondProd.price.doubleValue / 12

            monthonValueforaYear = String(format: "%.2f", currencynumbers2)

            print("walletview VC monthonValueforaYear: \(monthonValueforaYear)")

            //prefs.set(price2Str, forKey: "yearly")
            prefs.set(monthonValueforaYear, forKey: "monthonValueforaYear")

        }
        var charges : Array<String> = ["\(mycurrency1) 0/m","\(mycurrency1 + monthonValueforaYear)/m","Coming Soon"]

        print("wallet view charges: \(charges)")

        self.Headingtitle.text    = Headingarray[index]
        self.planchargelabel.text  = charges[index]
        self.subchargelabel.text = subcharges[index]

Interestingly, for subchargelabel value, I get a little spacing

The commented section was uncommented while I tried running the app. Just so you know it

Thanks for your help!

Body:
Try to format your required string as below.

let priceWithSpace: String? = firstProduct.priceLocale.currencySymbol + " " +   product.price


问:
Asp.Net Core EF Core many to many relation update command
I followed this link enter link description here to create many to many relationship. But, I do not know how to create and update Tag value to Post Object.

Any help would be appreciated.

Update, related code

```<code>class MyContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PostTag>()
            .HasKey(t => new { t.PostId, t.TagId });

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Post)
            .WithMany(p => p.PostTags)
            .HasForeignKey(pt => pt.PostId);

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Tag)
            .WithMany(t => t.PostTags)
            .HasForeignKey(pt => pt.TagId);
    }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public int PostId { get; set; }
    public Post Post { get; set; }

    public string TagId { get; set; }
    public Tag Tag { get; set; }
}
</code>```

Update2: Code for Update record
With below code, it will create records in both three tables.

```<code>    var p = new Post { Content = "C1" };
    var t = new Tag { TagId = "T1" };
    var pt = new PostTag { Post = p, Tag = t };
    _context.PostTag.Add(pt);
    _context.SaveChanges();
</code>```

But, with below code, it will insert new records in middle table PostTag instead of update the previous records.

```<code>    var t1 = new Tag { TagId = "T3" };
    var t2 = new Tag { TagId = "T4" };

    var p =_context.Posts.Find(1);
    p.PostTags = new List<PostTag>() {
        new PostTag{ Post=p, Tag=t1},
        new PostTag{ Post=p, Tag=t2}
    };
    _context.Posts.Update(p);
    _context.SaveChanges();
</code>```

答:
Let's create some sample data

```<code>var p = new Post { ... };
var t = new Tag { ... };
var pt = new PostTag { Post = p, Tag = t };
</code>```

This is still in-memory so we have to add it to the context, starting with:

```<code>db.Posts.Add(p);
db.Tags.Add(t);
</code>```

Note that at this stage neither p nor t has any knowledge of pt. There are two ways to insert the third entity into your database.

1) The easiest way is to add the DbSet<PostTag> property and then the line

```<code>db.PostTags.Add(pt);
</code>```

2) Without that extra DbSet you will need to ensure the linking from the other 2 sides. You also need to set up the List properties:

```<code>p.PostTags = new List<PostTag> { pt };
t.PostTags = new List<PostTag> { pt };
</code>```

EF will now fill out any missing link fields.

Body:
I followed this link enter link description here to create many to many relationship. But, I do not know how to create and update Tag value to Post Object.

Any help would be appreciated.

Update, related code

class MyContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PostTag>()
            .HasKey(t => new { t.PostId, t.TagId });

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Post)
            .WithMany(p => p.PostTags)
            .HasForeignKey(pt => pt.PostId);

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Tag)
            .WithMany(t => t.PostTags)
            .HasForeignKey(pt => pt.TagId);
    }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public int PostId { get; set; }
    public Post Post { get; set; }

    public string TagId { get; set; }
    public Tag Tag { get; set; }
}

Update2: Code for Update record
With below code, it will create records in both three tables.

    var p = new Post { Content = "C1" };
    var t = new Tag { TagId = "T1" };
    var pt = new PostTag { Post = p, Tag = t };
    _context.PostTag.Add(pt);
    _context.SaveChanges();

But, with below code, it will insert new records in middle table PostTag instead of update the previous records.

    var t1 = new Tag { TagId = "T3" };
    var t2 = new Tag { TagId = "T4" };

    var p =_context.Posts.Find(1);
    p.PostTags = new List<PostTag>() {
        new PostTag{ Post=p, Tag=t1},
        new PostTag{ Post=p, Tag=t2}
    };
    _context.Posts.Update(p);
    _context.SaveChanges();

Body:
Let's create some sample data

var p = new Post { ... };
var t = new Tag { ... };
var pt = new PostTag { Post = p, Tag = t };

This is still in-memory so we have to add it to the context, starting with:

db.Posts.Add(p);
db.Tags.Add(t);

Note that at this stage neither p nor t has any knowledge of pt. There are two ways to insert the third entity into your database.

1) The easiest way is to add the DbSet<PostTag> property and then the line

db.PostTags.Add(pt);

2) Without that extra DbSet you will need to ensure the linking from the other 2 sides. You also need to set up the List properties:

p.PostTags = new List<PostTag> { pt };
t.PostTags = new List<PostTag> { pt };

EF will now fill out any missing link fields.


问:
Apple Mach-O Linker & Ditto Error - Xcode 8
I have just updated my Xcode to Xcode 8 and am now trying to convert my project's code to Swift 2.3. I was able to build a couple times using Xcode 8 without any errors. Now, the following errors came up:

Error #1: Apple Mach-O Linker Error: Linker command failed with exit code 1

ld: file not found: /Users/Linus/Library/Developer/Xcode/DerivedData/MyApp-asdjeshhsetnfxbegcsbcipdreneewgr/Build/Intermediates/MyApp.build/Debug-iphonesimulator/MyApp.build/Objects-normal/x86_64/DownloadsViewController.o

  clang: error: linker command failed with exit code 1 (use -v to see invocation)

I don't even know what a .o file is. The swift file of DownloadsViewController is there, though.

Error #2: Ditto Error: Command /usr/cin/ditto failed with exit code 1

ditto: can't get real path for source '/Users/Linus/Library/Developer/Xcode/DerivedData/MyApp-asdjeshhsetnfxbbciegrfdpdreneewgr/Build/Intermediates/MyApp.build/Debug-iphonesimulator/MyApp.build/Objects-normal/x86_64/MyApp-Swift.h'

  Command /usr/bin/ditto failed with exit code 1

The ditto error occurs 3 times: for MyApp.swiftdoc, MyApp.swiftmodule, and MyApp-Swift.h.

Thanks in advance!

答: Don't wory ,just go to your project targat and then build setting and search enable bitcode change it to YES to NO.</p>


问:
Camel-Blueprint Unable to convert value org.springframework.orm.hibernate4.LocalSessionFactoryBean to type org.hibernate.SessionFactory
I am using camel-blueprint and facing issues with hibernate component.
This example works fine in Spring but not in blueprint JBoss Fuse 6.3 V

The provided example is in spring and works fine but any example in blueprint will be helpful
http://camel.apache.org/hibernate-example.html

Error:
org.osgi.service.blueprint.container.ComponentDefinitionException: Error setting property: PropertyDescriptor Caused by: java.lang.Exception: Unable to convert value org.springframework.orm.hibernate4.LocalSessionFactoryBean@46797063 to type org.hibernate.SessionFactory
    at org.apache.aries.blueprint.container.AggregateConverter.convert(AggregateConverter.java:184)

```<code><blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd                            http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
    <bean class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" id="dataSource">
        <property name="url"
            value="jdbc:sqlserver://x:1433;DatabaseName=x" />
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
        <property name="username" value="" />
        <property name="password" value="" />
        <property name="removeAbandoned" value="true" />
        <property name="initialSize" value="20" />
        <property name="maxActive" value="30" />
    </bean>
    <bean class="com.x.dto.ReferenceTable" id="refBean" />
    <!-- <bean class="com.x.dao.ReferenceDAOImpl" id="MyBean">
        <property name="sessionFactory" ref="mysessionFactory" />
    </bean> -->

    <!-- setup the Camel hibernate component -->
    <bean class="org.apacheextras.camel.component.hibernate.HibernateComponent"
        id="hibernate">
        <property name="sessionFactory" ref="mysessionFactory" />
    </bean>

    <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        id="mysessionFactory">
        <property name="dataSource" ref="dataSource" />
        <!-- here we define the hibernate mapping files we use -->
        <property name="packagesToScan">
            <list>
                <value>com.x.dto</value>
            </list>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.x.dto.ReferenceTable</value>
            </list>
        </property>
        <!-- and here we have additional hibernate options -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <camelContext id="_context1"
        xmlns="http://camel.apache.org/schema/blueprint">
        <route id="_route1">
            <from id="from" uri="hibernate://com.x.dto.ReferenceTable?consumer.query=select x.data from com.x.dto.ReferenceTable x where x.id='id3'"/>
          <!--   <bean id="_bean1" method="save(com.x.dto.ReferenceTable)" ref="MyBean"/>
            <bean id="_bean2" method="getByID('id2')" ref="MyBean"/>
            <convertBodyTo id="_convertBodyTo1" type="com.x.dto.ReferenceTable"/> -->
            <to id="_to1" uri="log: ${body}"/>
        </route>
    </camelContext>
</blueprint>
</code>```

Pom.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany</groupId>
    <artifactId>camel-blueprint</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>bundle</packaging>
    <name>Camel Blueprint Quickstart</name>
    <description>Empty Camel Blueprint Example</description>
    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
            <distribution>repo</distribution>
        </license>
    </licenses>
    <properties>
        <camel.version>2.17.0.redhat-630187</camel.version>
        <version.maven-bundle-plugin>3.2.0</version.maven-bundle-plugin>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <jboss.fuse.bom.version>6.3.0.redhat-187</jboss.fuse.bom.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jboss.fuse.bom</groupId>
                <artifactId>jboss-fuse-parent</artifactId>
                <version>${jboss.fuse.bom.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-blueprint</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test-blueprint</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>6.1.0.jre8</version>
        </dependency>
        <dependency>
      <groupId>org.apache-extras.camel-extra</groupId>
      <artifactId>camel-hibernate</artifactId>
        <version>2.15.0</version>
    </dependency>

     <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
    </dependency>

    </dependencies>
    <repositories>
        <repository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>fuse-public-repository</id>
            <name>FuseSource Community Release Repository</name>
            <url>https://repo.fusesource.com/nexus/content/groups/public</url>
        </repository>
        <repository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>red-hat-ga-repository</id>
            <name>Red Hat GA Repository</name>
            <url>https://maven.repository.redhat.com/ga</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>fuse-public-repository</id>
            <name>FuseSource Community Release Repository</name>
            <url>https://repo.fusesource.com/nexus/content/groups/public</url>
        </pluginRepository>
        <pluginRepository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>red-hat-ga-repository</id>
            <name>Red Hat GA Repository</name>
            <url>https://maven.repository.redhat.com/ga</url>
        </pluginRepository>
    </pluginRepositories>
    <build>
        <defaultGoal>install</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>${version.maven-bundle-plugin}</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>keyvalue</Bundle-SymbolicName>
                        <Bundle-Name>Empty Camel Blueprint Example [keyvalue]</Bundle-Name>
                    </instructions>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.1</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-maven-plugin</artifactId>
                <version>${camel.version}</version>
                <configuration>
                    <useBlueprint>true</useBlueprint>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
Remember one thing. org.springframework.orm.hibernate4.LocalSessionFactoryBean is Spring's factory bean which, when used as <bean> gives you a kind of indirection - instead of using the class as bean directly, getObject() is called and the returned object is your <bean>.

Another thing is that Spring automatically calls afterPropertiesSet() for all beans (or factory beans) that implement InitializingBean.

So instead of:

```<code><bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        id="mysessionFactory">
</code>```

use:

```<code><bean id="mysessionFactory" factory-ref="mysessionFactoryFactory"
      factory-method="getObject" />

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        id="mysessionFactoryFactory" init-method="afterPropertiesSet">
...
</code>```

Body:
I am using camel-blueprint and facing issues with hibernate component.
This example works fine in Spring but not in blueprint JBoss Fuse 6.3 V

The provided example is in spring and works fine but any example in blueprint will be helpful
http://camel.apache.org/hibernate-example.html

Error:
org.osgi.service.blueprint.container.ComponentDefinitionException: Error setting property: PropertyDescriptor Caused by: java.lang.Exception: Unable to convert value org.springframework.orm.hibernate4.LocalSessionFactoryBean@46797063 to type org.hibernate.SessionFactory
    at org.apache.aries.blueprint.container.AggregateConverter.convert(AggregateConverter.java:184)

<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd                            http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
    <bean class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" id="dataSource">
        <property name="url"
            value="jdbc:sqlserver://x:1433;DatabaseName=x" />
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
        <property name="username" value="" />
        <property name="password" value="" />
        <property name="removeAbandoned" value="true" />
        <property name="initialSize" value="20" />
        <property name="maxActive" value="30" />
    </bean>
    <bean class="com.x.dto.ReferenceTable" id="refBean" />

    <bean class="org.apacheextras.camel.component.hibernate.HibernateComponent"
        id="hibernate">
        <property name="sessionFactory" ref="mysessionFactory" />
    </bean>

    <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        id="mysessionFactory">
        <property name="dataSource" ref="dataSource" />

        <property name="packagesToScan">
            <list>
                <value>com.x.dto</value>
            </list>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.x.dto.ReferenceTable</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <camelContext id="_context1"
        xmlns="http://camel.apache.org/schema/blueprint">
        <route id="_route1">
            <from id="from" uri="hibernate://com.x.dto.ReferenceTable?consumer.query=select x.data from com.x.dto.ReferenceTable x where x.id='id3'"/>

            <to id="_to1" uri="log: ${body}"/>
        </route>
    </camelContext>
</blueprint>

Pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany</groupId>
    <artifactId>camel-blueprint</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>bundle</packaging>
    <name>Camel Blueprint Quickstart</name>
    <description>Empty Camel Blueprint Example</description>
    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
            <distribution>repo</distribution>
        </license>
    </licenses>
    <properties>
        <camel.version>2.17.0.redhat-630187</camel.version>
        <version.maven-bundle-plugin>3.2.0</version.maven-bundle-plugin>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <jboss.fuse.bom.version>6.3.0.redhat-187</jboss.fuse.bom.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jboss.fuse.bom</groupId>
                <artifactId>jboss-fuse-parent</artifactId>
                <version>${jboss.fuse.bom.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-blueprint</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test-blueprint</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>6.1.0.jre8</version>
        </dependency>
        <dependency>
      <groupId>org.apache-extras.camel-extra</groupId>
      <artifactId>camel-hibernate</artifactId>
        <version>2.15.0</version>
    </dependency>

     <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
    </dependency>

    </dependencies>
    <repositories>
        <repository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>fuse-public-repository</id>
            <name>FuseSource Community Release Repository</name>
            <url>https://repo.fusesource.com/nexus/content/groups/public</url>
        </repository>
        <repository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>red-hat-ga-repository</id>
            <name>Red Hat GA Repository</name>
            <url>https://maven.repository.redhat.com/ga</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>fuse-public-repository</id>
            <name>FuseSource Community Release Repository</name>
            <url>https://repo.fusesource.com/nexus/content/groups/public</url>
        </pluginRepository>
        <pluginRepository>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>red-hat-ga-repository</id>
            <name>Red Hat GA Repository</name>
            <url>https://maven.repository.redhat.com/ga</url>
        </pluginRepository>
    </pluginRepositories>
    <build>
        <defaultGoal>install</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>${version.maven-bundle-plugin}</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>keyvalue</Bundle-SymbolicName>
                        <Bundle-Name>Empty Camel Blueprint Example [keyvalue]</Bundle-Name>
                    </instructions>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.1</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-maven-plugin</artifactId>
                <version>${camel.version}</version>
                <configuration>
                    <useBlueprint>true</useBlueprint>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Body:
Remember one thing. org.springframework.orm.hibernate4.LocalSessionFactoryBean is Spring's factory bean which, when used as <bean> gives you a kind of indirection - instead of using the class as bean directly, getObject() is called and the returned object is your <bean>.

Another thing is that Spring automatically calls afterPropertiesSet() for all beans (or factory beans) that implement InitializingBean.

So instead of:

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        id="mysessionFactory">

use:

<bean id="mysessionFactory" factory-ref="mysessionFactoryFactory"
      factory-method="getObject" />

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        id="mysessionFactoryFactory" init-method="afterPropertiesSet">
...


问:
Password Hashing: PBKDF2 (using sha512 x 1000) vs Bcrypt
I've been reading about the Gawker incident and several articles have cropped up regarding only using bcrypt to hash passwords and I want to make sure my hashing mechanism is secure enough to avoid switching to another method. In my current application I have opted for a PBKDF2 implementation utilising sha2-512 and a minimum of 1000 iterations.

Can I ask for opinions on using PBKDF2 vs Bcrypt and whether or not I should implement a change?

答:
Comment (re: the title):

Don't use encryption (reversible) to store passwords unless you MUST.

Since you presented a hashing (non-reversible) option as an alternative, I assume you don't need reversibility.

opinions on using PBKDF2 vs Bcrypt and
  whether or not I should implement a
  change?

My opinion:

Use PBKDF2 over Bcrypt.  (I just have more faith in SHA than Blofish, for no reason)

As for whether you should 'implement a change', I don't know what you are asking.

Edited to more clearly separate the encryption / hashing discussion from stating my preferences w/r/t algorithm.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
While using MKMapview causing MBs of memory usage and using ARC it not releasing memory when View Disappears
using Xcode 6.0 and iOS 8.4 and what i have tried is:

```<code>-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    mapView.mapType = MKMapTypeHybrid;
    mapView.mapType = MKMapTypeStandard;
    mapView.showsUserLocation = NO;
    mapView.delegate = nil;
    [mapView removeFromSuperview];
    mapView = nil;
}
</code>```

I am using ARC, it not releasing memory when View Disappears.

答:
Have you tired making MapView or the view controller to be a weak reference?

e.g.: If you're pushing to a view controller with a Map view. Assign it to a weak property.

@property (weak,nonatomic) UIViewController *mapViewController;

Body:
using Xcode 6.0 and iOS 8.4 and what i have tried is:

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    mapView.mapType = MKMapTypeHybrid;
    mapView.mapType = MKMapTypeStandard;
    mapView.showsUserLocation = NO;
    mapView.delegate = nil;
    [mapView removeFromSuperview];
    mapView = nil;
}

I am using ARC, it not releasing memory when View Disappears.


问:
instagram api: getting user information and rate limits
I'm a little confused if what I am trying to do is even possible given the expressed limits to the API.

My app should do this:

user logs in, app gets auth token

user gets list of their followers

https://api.instagram.com/v1/users/self/follows?access_token=ACCESS-TOKEN

this point is easy to get to, but the next step (3) seems potentially problematic

user gets the number of followers each of those followers has

https://api.instagram.com/v1/users/{user-id}/?access_token=ACCESS-TOKEN

If the user has 5000+ (limit is 5000 requests per hour) followers, do I really need to request each users information one by one? If so, it looks like I will definitely hit the rate limit.

user is able to delete followers having under a certain amount of followers (limit 60 / hour)

https://api.instagram.com/v1/users/{user-id}/relationship?access_token=ACCESS-TOKEN

So, it seems, given the limits, that such an app would be impossible to create. Is there some channel where I can request a limit increase? This tool would be used sparingly and infrequently.

答:
There is a section "Relationship Endpoints" where you can use request

GET/users/self/followed-by

```<code>https://api.instagram.com/v1/users/self/follows?access_token=ACCESS-TOKEN
</code>```

to Get the list of users this user is followed by, so this is only one request.

Body:
There is a section "Relationship Endpoints" where you can use request

GET/users/self/followed-by

https://api.instagram.com/v1/users/self/follows?access_token=ACCESS-TOKEN

to Get the list of users this user is followed by, so this is only one request.


问:
Unity add Text by C# but don't show
My unity version is 5.5.2f. I try to use C# to create a text and add it to a parent GameObject A, but it doesn't show. I have add a texture to the parent GameObject A, and I can see the texture.

When I run the program, I found  Preferred Width and Preferred Height is zero for the text, so I guess it may cause the problem.

Here is my code, Obj is the parent GameObject A.

```<code>public void setText(string value)
{

    if (text == null)
    {

        GameObject targetObj = new GameObject();

        Canvas canvas = Obj.AddComponent<Canvas>();
        canvas.transform.SetParent(Obj.transform ,false);

        targetObj.name = "displayTextObject";
        targetObj.transform.SetParent(canvas.transform, false);

        text = targetObj.AddComponent<Text>();

        text.name = "displayText";

        Color color = new Color(0, 0, 0);

        text.color = color;

        Font font = new Font("Arial");

        text.font = font;

        gridBgObject.SetActive(false);
    }

    text.text = value;
}
</code>```

答:
try with instanciate

make a prefab contains

Canvas

Text

TextDisplay

or

RectTransform

Text

TextDisplay
(if you choose this you must set parent to canvas)

in
TextDisplay.cs

```<code>[RequireComponent (typeof (Text))]
public class TextDisplay : MonoBehaviour{
    public Text targetText;

    void Awake(){
        targetText = GetComponent<Text> ();
    }

    public void SetText(string messageToDisplay){
        targetText.text = messageToDisplay;
    }

}
</code>```

in your controller script.

```<code>public GameObject textDisplayPrefab;
public Transform rootTransform;

public TextDisplay CreateNewTextDisplay(){
    GameObject newTextDisplayObject = Instanciate(textDisplayPrefab) as GameObject;
    newTextDisplayObject.transform.SetParent(rootTransform, false);
    TextDisplay newTextDisplay = newTextDisplayObject.GetComponent<TextDisplay>();
return newTextDisplay;

}
</code>```

and you can do something like this.

```<code>if(textDisplay == null){
    textDisplay = CreateNewTextDisplay();
    textDisplay.SetText("your string here!!");

}
</code>```

Title: Unity add Text by C# but don't show

Body:
My unity version is 5.5.2f. I try to use C# to create a text and add it to a parent GameObject A, but it doesn't show. I have add a texture to the parent GameObject A, and I can see the texture.

When I run the program, I found  Preferred Width and Preferred Height is zero for the text, so I guess it may cause the problem.

Here is my code, Obj is the parent GameObject A.

public void setText(string value)
{

    if (text == null)
    {

        GameObject targetObj = new GameObject();

        Canvas canvas = Obj.AddComponent<Canvas>();
        canvas.transform.SetParent(Obj.transform ,false);

        targetObj.name = "displayTextObject";
        targetObj.transform.SetParent(canvas.transform, false);

        text = targetObj.AddComponent<Text>();

        text.name = "displayText";

        Color color = new Color(0, 0, 0);

        text.color = color;

        Font font = new Font("Arial");

        text.font = font;

        gridBgObject.SetActive(false);
    }

    text.text = value;
}

Body:
try with instanciate

make a prefab contains

Canvas

Text

TextDisplay

or

RectTransform

Text

TextDisplay
(if you choose this you must set parent to canvas)

in
TextDisplay.cs

[RequireComponent (typeof (Text))]
public class TextDisplay : MonoBehaviour{
    public Text targetText;

    void Awake(){
        targetText = GetComponent<Text> ();
    }

    public void SetText(string messageToDisplay){
        targetText.text = messageToDisplay;
    }

}

in your controller script.

public GameObject textDisplayPrefab;
public Transform rootTransform;

public TextDisplay CreateNewTextDisplay(){
    GameObject newTextDisplayObject = Instanciate(textDisplayPrefab) as GameObject;
    newTextDisplayObject.transform.SetParent(rootTransform, false);
    TextDisplay newTextDisplay = newTextDisplayObject.GetComponent<TextDisplay>();
return newTextDisplay;

}

and you can do something like this.

if(textDisplay == null){
    textDisplay = CreateNewTextDisplay();
    textDisplay.SetText("your string here!!");

}


问:
Removing content from Liferay database
CONTEXT: We are working on a portal project using Liferay6.1 and SQL Server 12 database. Every time a release happens to production, we refresh our Integration and Dev databases with production db. As the size of the Production database is very large, we would like to strip down the database (may be by removing content) and have a smaller sized database.
Also We want developers to set their development environment on local systems which requires a smaller db.

QUESTION: How to strip down the liferay database without compromising on the portal functionalities? Any sugestions? feedback?

答:
You should separate your portal schema / database and application schema / database. Then connect one of you non-production servers with both the databases. Follow the below steps

Create minimal portal configuration like sites, users. layouts and portlets. This will reduce the size of the portal data.

Export the portal schema / database.

Save the exported databases file and liferay-home\data\document_library directory as your baseline copy of the configuration.

You can update the baseline files as and when required.

Now to replicate you should import the portal schema \ database and place the document_library directory in liferay-home\data. Connect to the application schema \ databases and start the server.

The solution also demands a process orientation and I suggest you should craft a process around the solution.

Title: Removing content from Liferay database


问:
How do i get "sed" to delete everything else but email address.
how do i get "sed" to delete everything else but email address. </p>

```<code>db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com
</code>```

答:
This requires GNU sed:

```<code>sed -r 's/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/\n&\n/ig;s/(^|\n)[^@]*(\n|$)/\n/g;s/^\n|\n$//g;/^$/d' inputfile
</code>```

split input lines so email addresses and other strings are separated by newlines

erase sequences that consist of only non-@ characters delimited by newlines or the beginning or end of the input line

erase extra newlines and blank lines

Body:
how do i get "sed" to delete everything else but email address.

db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com

Body:
This requires GNU sed:

sed -r 's/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/\n&\n/ig;s/(^|\n)[^@]*(\n|$)/\n/g;s/^\n|\n$//g;/^$/d' inputfile

split input lines so email addresses and other strings are separated by newlines

erase sequences that consist of only non-@ characters delimited by newlines or the beginning or end of the input line

erase extra newlines and blank lines


问:
java.lang.RuntimeException: Camera.setParameters
i know that the question was asked before, and i did read all the solutions, but my case is kinda strange, i keep getting on Crash report on developer account the following:

java.lang.RuntimeException:    at
  android.hardware.Camera.native_setParameters(Native Method:0)   at
  android.hardware.Camera.setParameters(Camera.java:2080)   at
  com.xxxxxxxxxx.core.xxxxxxxx.xxxxxxx.surfaceCreated(BackgroundVideoRecorder.java:119)
  at android.view.SurfaceView.updateWindow(SurfaceView.java:675)   at
  android.view.SurfaceView$3.onPreDraw(SurfaceView.java:185)   at
  android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2050)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1117)   at
  android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6175)
  at
  android.view.Choreographer$CallbackRecord.run(Choreographer.java:773)
  at android.view.Choreographer.doCallbacks(Choreographer.java:586)   at
  android.view.Choreographer.doFrame(Choreographer.java:556)   at
  android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:759)
  at android.os.Handler.handleCallback(Handler.java:739)   at
  android.os.Handler.dispatchMessage(Handler.java:95)   at
  android.os.Looper.loop(Looper.java:135)   at
  android.app.ActivityThread.main(ActivityThread.java:5421)   at
  java.lang.reflect.Method.invoke(Native Method:0)   at
  java.lang.reflect.Method.invoke(Method.java:372)   at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)

Removed the application name for the sake of advertising, i tried the application on multiple devices and i cannot arrive to reproduce the error, even tho the devices that i tried it are available in the crash report, and in my parameter generation process i made sure to check if every parameter is supported, by checking the camera params here the code bellow:

```<code>   if (front) {
            params = camera.getParameters();
            params.setRotation(90);
            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                Log.w("VideoTakerFront","Continuous Video Supported");
            }
        } else {
            params = camera.getParameters();
            params.setRotation(270);
            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                Log.w("VideoTakerBack","Continuous Video Supported");
            }
        }
        camera.setParameters(params);
                if (android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.JELLY_BEAN_MR1){
                    camera.enableShutterSound(false);
                }
                else{
                    AudioManager audio= (AudioManager)this.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    audio.setStreamVolume(AudioManager.STREAM_SYSTEM, 0,   AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                }
        Log.w("VideoTaker", "Open Camera");
</code>```

Thank you for the help!

答: i found the problem... The users that reported the issue was using an older version of the application, i did not pay attention for the version, this problem used to happen in an older version, before I didn't use to get supported focus mode and check if it is available, thank you! </p>

Body:
i know that the question was asked before, and i did read all the solutions, but my case is kinda strange, i keep getting on Crash report on developer account the following:

java.lang.RuntimeException:    at
  android.hardware.Camera.native_setParameters(Native Method:0)   at
  android.hardware.Camera.setParameters(Camera.java:2080)   at
  com.xxxxxxxxxx.core.xxxxxxxx.xxxxxxx.surfaceCreated(BackgroundVideoRecorder.java:119)
  at android.view.SurfaceView.updateWindow(SurfaceView.java:675)   at
  android.view.SurfaceView$3.onPreDraw(SurfaceView.java:185)   at
  android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2050)
  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1117)   at
  android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6175)
  at
  android.view.Choreographer$CallbackRecord.run(Choreographer.java:773)
  at android.view.Choreographer.doCallbacks(Choreographer.java:586)   at
  android.view.Choreographer.doFrame(Choreographer.java:556)   at
  android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:759)
  at android.os.Handler.handleCallback(Handler.java:739)   at
  android.os.Handler.dispatchMessage(Handler.java:95)   at
  android.os.Looper.loop(Looper.java:135)   at
  android.app.ActivityThread.main(ActivityThread.java:5421)   at
  java.lang.reflect.Method.invoke(Native Method:0)   at
  java.lang.reflect.Method.invoke(Method.java:372)   at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)

Removed the application name for the sake of advertising, i tried the application on multiple devices and i cannot arrive to reproduce the error, even tho the devices that i tried it are available in the crash report, and in my parameter generation process i made sure to check if every parameter is supported, by checking the camera params here the code bellow:

   if (front) {
            params = camera.getParameters();
            params.setRotation(90);
            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                Log.w("VideoTakerFront","Continuous Video Supported");
            }
        } else {
            params = camera.getParameters();
            params.setRotation(270);
            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                Log.w("VideoTakerBack","Continuous Video Supported");
            }
        }
        camera.setParameters(params);
                if (android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.JELLY_BEAN_MR1){
                    camera.enableShutterSound(false);
                }
                else{
                    AudioManager audio= (AudioManager)this.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    audio.setStreamVolume(AudioManager.STREAM_SYSTEM, 0,   AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                }
        Log.w("VideoTaker", "Open Camera");

Thank you for the help!


问:
ERR: Could not extract response: no suitable HttpMessageConverter
Im getting the above mentioned error:

Controller:

```<code>@Component
public class NiftyController {

@Autowired
private RestProxyTemplate restTemplate;

@Autowired
private NiftyDAO niftyDAO;

int count=1;

@Scheduled(fixedDelay=5000)
//@Scheduled(cron="*/5 * * * * ?")
public void loadNiftyData() throws URISyntaxException {

    System.out.println("Method executed at every 5 seconds. Current time is : "+ new Date() );
    System.out.println("Executed  " +count++ +"  Times");

    URI uri = new URI("https://www.nseindia.com/live_market/dynaContent/live_watch/stock_watch/niftyStockWatch.json");
    ResponseEntity<NiftyDTO> niftyResponse = restTemplate.getRestTemplate().exchange(uri, HttpMethod.GET, null, NiftyDTO.class);

    NiftyDTO nifties = niftyResponse.getBody();
    System.out.println(nifties.getTrdVolumesum());
    //List<Nifty> saveNifty = niftyDAO.save(nifties);
    //return (Nifty) nifties;
}
}
</code>```

I want to fetch the data from the above link and save in the database

DTO Class

```<code>@JsonIgnoreProperties({"latestData","data"})
public class NiftyDTO {

private float trdVolumesumMil;

private String time;

private int declines;

private float trdValueSum;

private float trdValueSumMil;

private int unchanged;

private float trdVolumesum;

private int advances;

public float getTrdVolumesumMil() {
    return trdVolumesumMil;
}

public void setTrdVolumesumMil(float trdVolumesumMil) {
    this.trdVolumesumMil = trdVolumesumMil;
}

public String getTime() {
    return time;
}

public void setTime(String time) {
    this.time = time;
}

public int getDeclines() {
    return declines;
}

public void setDeclines(int declines) {
    this.declines = declines;
}

public float getTrdValueSum() {
    return trdValueSum;
}

public void setTrdValueSum(float trdValueSum) {
    this.trdValueSum = trdValueSum;
}

public float getTrdValueSumMil() {
    return trdValueSumMil;
}

public void setTrdValueSumMil(float trdValueSumMil) {
    this.trdValueSumMil = trdValueSumMil;
}

public int getUnchanged() {
    return unchanged;
}

public void setUnchanged(int unchanged) {
    this.unchanged = unchanged;
}

public float getTrdVolumesum() {
    return trdVolumesum;
}

public void setTrdVolumesum(float trdVolumesum) {
    this.trdVolumesum = trdVolumesum;
}

public int getAdvances() {
    return advances;
}

public void setAdvances(int advances) {
    this.advances = advances;
}
}
</code>```

RestProxyTemplate:

```<code>@Component
public final class RestProxyTemplate {

RestTemplate restTemplate;

@PostConstruct
public void init(){
    restTemplate = new RestTemplate();
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    InetSocketAddress address = new InetSocketAddress("MY PROXY GOES HERE",8080);
    Proxy proxy = new Proxy(Proxy.Type.HTTP,address);
    factory.setProxy(proxy);

    restTemplate.setRequestFactory(factory);
}

public RestTemplate getRestTemplate() {
    return restTemplate;
}
}
</code>```

Error Log:

```<code>Method executed at every 5 seconds. Current time is : Mon Jun 05 10:45:38 IST 2017
Executed  1  Times
2017-06-05 10:45:38.141  INFO 108988 --- [           main]
s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8090 (http)
2017-06-05 10:45:38.153  INFO 108988 --- [           main]
com.MyApplication.portfolio.PMSApplication      : Started PMSApplication in 5.041 seconds (JVM running for 5.573)
2017-06-05 10:45:39.028 ERROR 108988 --- [pool-2-thread-1] o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task.

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.MyApplication.portfolio.controller.NiftyDTO] and content type [text/plain]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:109) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:835) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:819) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:599) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:572) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:493) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at com.MyApplication.portfolio.controller.NiftyController.loadNiftyData(NiftyController.java:44) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65) ~[spring-context-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_92]
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) [na:1.8.0_92]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_92]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) [na:1.8.0_92]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_92]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_92]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_92]
</code>```

Im getting the No Sutiable HttpMessageConverter Found for the response type, can some one suggest the possible solution for this??

答:
You need to process application/json rather than text/plain.

```<code>private static void temp() {
        HttpHeaders requestHeaders = new HttpHeaders();
//        requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
        requestHeaders.setAccept(Collections.singletonList(new MediaType("text","plain")));
        HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders);

// Create a new RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

// Add the Jackson message converter
        MappingJackson2HttpMessageConverter mc = new MappingJackson2HttpMessageConverter() ;
        mc.setSupportedMediaTypes(Collections.singletonList(new MediaType("text","plain")));
        restTemplate.getMessageConverters().add(mc);

        String url = "https://www.nseindia.com/live_market/dynaContent/live_watch/stock_watch/niftyStockWatch.json";
        ResponseEntity<NiftyDTO> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, NiftyDTO.class);
        NiftyDTO res = responseEntity.getBody();
        System.out.println(res);
    }
</code>```

Code got from the docs and modified a bit

UPDATE: After the change code works fine but there is another error Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type float from String "4,092.10": not a valid Float value

You will need to fix deserializing of data with , delimiter.

Body:
Im getting the above mentioned error:

Controller:

@Component
public class NiftyController {

@Autowired
private RestProxyTemplate restTemplate;

@Autowired
private NiftyDAO niftyDAO;

int count=1;

@Scheduled(fixedDelay=5000)
//@Scheduled(cron="*/5 * * * * ?")
public void loadNiftyData() throws URISyntaxException {

    System.out.println("Method executed at every 5 seconds. Current time is : "+ new Date() );
    System.out.println("Executed  " +count++ +"  Times");

    URI uri = new URI("https://www.nseindia.com/live_market/dynaContent/live_watch/stock_watch/niftyStockWatch.json");
    ResponseEntity<NiftyDTO> niftyResponse = restTemplate.getRestTemplate().exchange(uri, HttpMethod.GET, null, NiftyDTO.class);

    NiftyDTO nifties = niftyResponse.getBody();
    System.out.println(nifties.getTrdVolumesum());
    //List<Nifty> saveNifty = niftyDAO.save(nifties);
    //return (Nifty) nifties;
}
}

I want to fetch the data from the above link and save in the database

DTO Class

@JsonIgnoreProperties({"latestData","data"})
public class NiftyDTO {

private float trdVolumesumMil;

private String time;

private int declines;

private float trdValueSum;

private float trdValueSumMil;

private int unchanged;

private float trdVolumesum;

private int advances;

public float getTrdVolumesumMil() {
    return trdVolumesumMil;
}

public void setTrdVolumesumMil(float trdVolumesumMil) {
    this.trdVolumesumMil = trdVolumesumMil;
}

public String getTime() {
    return time;
}

public void setTime(String time) {
    this.time = time;
}

public int getDeclines() {
    return declines;
}

public void setDeclines(int declines) {
    this.declines = declines;
}

public float getTrdValueSum() {
    return trdValueSum;
}

public void setTrdValueSum(float trdValueSum) {
    this.trdValueSum = trdValueSum;
}

public float getTrdValueSumMil() {
    return trdValueSumMil;
}

public void setTrdValueSumMil(float trdValueSumMil) {
    this.trdValueSumMil = trdValueSumMil;
}

public int getUnchanged() {
    return unchanged;
}

public void setUnchanged(int unchanged) {
    this.unchanged = unchanged;
}

public float getTrdVolumesum() {
    return trdVolumesum;
}

public void setTrdVolumesum(float trdVolumesum) {
    this.trdVolumesum = trdVolumesum;
}

public int getAdvances() {
    return advances;
}

public void setAdvances(int advances) {
    this.advances = advances;
}
}

RestProxyTemplate:

@Component
public final class RestProxyTemplate {

RestTemplate restTemplate;

@PostConstruct
public void init(){
    restTemplate = new RestTemplate();
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    InetSocketAddress address = new InetSocketAddress("MY PROXY GOES HERE",8080);
    Proxy proxy = new Proxy(Proxy.Type.HTTP,address);
    factory.setProxy(proxy);

    restTemplate.setRequestFactory(factory);
}

public RestTemplate getRestTemplate() {
    return restTemplate;
}
}

Error Log:

Method executed at every 5 seconds. Current time is : Mon Jun 05 10:45:38 IST 2017
Executed  1  Times
2017-06-05 10:45:38.141  INFO 108988 --- [           main]
s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8090 (http)
2017-06-05 10:45:38.153  INFO 108988 --- [           main]
com.MyApplication.portfolio.PMSApplication      : Started PMSApplication in 5.041 seconds (JVM running for 5.573)
2017-06-05 10:45:39.028 ERROR 108988 --- [pool-2-thread-1] o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task.

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.MyApplication.portfolio.controller.NiftyDTO] and content type [text/plain]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:109) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:835) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:819) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:599) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:572) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:493) ~[spring-web-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at com.MyApplication.portfolio.controller.NiftyController.loadNiftyData(NiftyController.java:44) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65) ~[spring-context-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-4.2.8.RELEASE.jar:4.2.8.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_92]
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) [na:1.8.0_92]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_92]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) [na:1.8.0_92]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_92]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_92]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_92]

Im getting the No Sutiable HttpMessageConverter Found for the response type, can some one suggest the possible solution for this??

Body:
You need to process application/json rather than text/plain.

private static void temp() {
        HttpHeaders requestHeaders = new HttpHeaders();
//        requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
        requestHeaders.setAccept(Collections.singletonList(new MediaType("text","plain")));
        HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders);

// Create a new RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

// Add the Jackson message converter
        MappingJackson2HttpMessageConverter mc = new MappingJackson2HttpMessageConverter() ;
        mc.setSupportedMediaTypes(Collections.singletonList(new MediaType("text","plain")));
        restTemplate.getMessageConverters().add(mc);

        String url = "https://www.nseindia.com/live_market/dynaContent/live_watch/stock_watch/niftyStockWatch.json";
        ResponseEntity<NiftyDTO> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, NiftyDTO.class);
        NiftyDTO res = responseEntity.getBody();
        System.out.println(res);
    }

Code got from the docs and modified a bit

UPDATE: After the change code works fine but there is another error Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type float from String "4,092.10": not a valid Float value

You will need to fix deserializing of data with , delimiter.


问:
Java- how to ignore quotes inside quotes
I have some unescaped quotes in the value part of my json file,

```<code>"key":"value"
</code>```

it is like

```<code>"text":"a personal persona as a street-smart "tough girl", which when
combined with raw talent","birthday":"19871108"
</code>```

I am wondering how use regex to make the escape the quote inside my value part?
Make it looks like

```<code>"text":"a personal persona as a street-smart \"tough girl\", which when
combined with raw talent","birthday":"19871108"
</code>```

答:
The tricky part is not finding quotes using regular expression, but finding unescaped quotes using regular expression.

The definition of an unescaped quote is one that is preceded by an even number of backslashes (zero backslashes being the most common case).

The expression for that is this ugly thing:

```<code>(?<!(?:[^\\]|$)(?:\\{2})?\\)"
</code>```

If you think that's bad, check out the escaped version in Java:

```<code>(?<!(?:[^\\\\]|$)(?:\\\\{2})?\\\\)\"
</code>```

What this essentially does is find all quotes that haven't been escaped already.  The test string I used was: Testing "unescaped".  \"escaped\".  \\"unescaped again\\"  The regex matches only the first and third sets of quotation marks, not the escaped second set.

It should be replaced by \" or in java, \\\".

Try it and let me know!

Body:
I have some unescaped quotes in the value part of my json file,

"key":"value"

it is like

"text":"a personal persona as a street-smart "tough girl", which when
combined with raw talent","birthday":"19871108"

I am wondering how use regex to make the escape the quote inside my value part?
Make it looks like

"text":"a personal persona as a street-smart \"tough girl\", which when
combined with raw talent","birthday":"19871108"

Body:
The tricky part is not finding quotes using regular expression, but finding unescaped quotes using regular expression.

The definition of an unescaped quote is one that is preceded by an even number of backslashes (zero backslashes being the most common case).

The expression for that is this ugly thing:

(?<!(?:[^\\]|$)(?:\\{2})?\\)"

If you think that's bad, check out the escaped version in Java:

(?<!(?:[^\\\\]|$)(?:\\\\{2})?\\\\)\"

What this essentially does is find all quotes that haven't been escaped already.  The test string I used was: Testing "unescaped".  \"escaped\".  \\"unescaped again\\"  The regex matches only the first and third sets of quotation marks, not the escaped second set.

It should be replaced by \" or in java, \\\".

Try it and let me know!


问:
Why can't I see ngOnChanges logged in my application
I am new to Angular and am trying to get a hold of life cycle hooks. However, I am confused because what I see in my code doesn't go along with the documentation.

I have following code in my component class:

```<code>ngOnInit() {
    console.log("ngOnInit", this.personList);
    this.person = this.pService.getName();
}

ngOnChanges() {
    console.log("ngOnChanges", this.personList, arguments);
}

ngDoCheck() {
    console.log("ngDoCheck", this.personList, arguments);
}

ngAfterContentInit() {
    console.log("ngAfterContentInit", this.personList, arguments);
}

ngAfterViewInit() {
    console.log("ngAfterViewInit", this.personList, arguments);
}

ngAfterViewChecked() {
    console.log("ngAfterViewChecked", this.personList, arguments);
}

ngAfterContentChecked() {
    console.log("ngAfterContentChecked", this.personList, arguments);
}

ngOnDestroy() {
    console.log("ngOnDestroy", this.personList, arguments);
}

changeclr() {
        this.person = this.name === 'Saurabh' ? 'Navanshu' : 'Saurabh';
}
</code>```

The docs here says ngOnchanges gets triggered before ngonInit but I can't see any logs for ngOnChanges while application loads.

The docs also says ngOnChnages runs while data-bound property changes. Is it specific to properties set using @Input, because I can't see any logs while I change this.person using my changclr method.

Am I getting something wrong here ?

答:
ngOnChanges will fire only when you have @Input() parameter in your class/component, it will executed when any input parameter value is updated.

In your code you haven't mension any thing about input parameter and hence your ngOnChanges not logged.

may be you have to define like : @Input() person :any;

Body:
I am new to Angular and am trying to get a hold of life cycle hooks. However, I am confused because what I see in my code doesn't go along with the documentation.

I have following code in my component class:

ngOnInit() {
    console.log("ngOnInit", this.personList);
    this.person = this.pService.getName();
}

ngOnChanges() {
    console.log("ngOnChanges", this.personList, arguments);
}

ngDoCheck() {
    console.log("ngDoCheck", this.personList, arguments);
}

ngAfterContentInit() {
    console.log("ngAfterContentInit", this.personList, arguments);
}

ngAfterViewInit() {
    console.log("ngAfterViewInit", this.personList, arguments);
}

ngAfterViewChecked() {
    console.log("ngAfterViewChecked", this.personList, arguments);
}

ngAfterContentChecked() {
    console.log("ngAfterContentChecked", this.personList, arguments);
}

ngOnDestroy() {
    console.log("ngOnDestroy", this.personList, arguments);
}

changeclr() {
        this.person = this.name === 'Saurabh' ? 'Navanshu' : 'Saurabh';
}

The docs here says ngOnchanges gets triggered before ngonInit but I can't see any logs for ngOnChanges while application loads.

The docs also says ngOnChnages runs while data-bound property changes. Is it specific to properties set using @Input, because I can't see any logs while I change this.person using my changclr method.

Am I getting something wrong here ?


问:
How to split a pandas dataframe or series by day (possibly using an iterator)
I have a long time series, eg.

```<code>import pandas as pd
index=pd.date_range(start='2012-11-05', end='2012-11-10', freq='1S').tz_localize('Europe/Berlin')
df=pd.DataFrame(range(len(index)), index=index, columns=['Number'])
</code>```

Now I want to extract all sub-DataFrames for each day, to get the following output:

```<code>df_2012-11-05: data frame with all data referring to day 2012-11-05
df_2012-11-06: etc.
df_2012-11-07
df_2012-11-08
df_2012-11-09
df_2012-11-10
</code>```

What is the most effective way to do this avoiding to check if the index.date==give_date which is very slow. Also, the user does not know a priory the range of days in the frame.

Any hint do do this with an iterator?

My current solution is this, but it is not so elegant and has two issues defined below:

```<code>time_zone='Europe/Berlin'
# find all days
a=np.unique(df.index.date) # this can take a lot of time
a.sort()
results=[]
for i in range(len(a)-1):
    day_now=pd.Timestamp(a[i]).tz_localize(time_zone)
    day_next=pd.Timestamp(a[i+1]).tz_localize(time_zone)
    results.append(df[day_now:day_next]) # how to select if I do not want day_next included?

# last day
results.append(df[day_next:])
</code>```

This approach has the following problems:

a=np.unique(df.index.date) can take a lot of time

df[day_now:day_next] includes the day_next, but I need to exclude it in the range

答:
If you want to group by date (AKA: year+month+day), then use df.index.date:

```<code>result = [group[1] for group in df.groupby(df.index.date)]
</code>```

As df.index.day will use the day of the month (i.e.: from 1 to 31) for grouping, which could result in undesirable behavior if the input dataframe dates extend to multiple months.

Body:
I have a long time series, eg.

import pandas as pd
index=pd.date_range(start='2012-11-05', end='2012-11-10', freq='1S').tz_localize('Europe/Berlin')
df=pd.DataFrame(range(len(index)), index=index, columns=['Number'])

Now I want to extract all sub-DataFrames for each day, to get the following output:

df_2012-11-05: data frame with all data referring to day 2012-11-05
df_2012-11-06: etc.
df_2012-11-07
df_2012-11-08
df_2012-11-09
df_2012-11-10

What is the most effective way to do this avoiding to check if the index.date==give_date which is very slow. Also, the user does not know a priory the range of days in the frame.

Any hint do do this with an iterator?

My current solution is this, but it is not so elegant and has two issues defined below:

time_zone='Europe/Berlin'
# find all days
a=np.unique(df.index.date) # this can take a lot of time
a.sort()
results=[]
for i in range(len(a)-1):
    day_now=pd.Timestamp(a[i]).tz_localize(time_zone)
    day_next=pd.Timestamp(a[i+1]).tz_localize(time_zone)
    results.append(df[day_now:day_next]) # how to select if I do not want day_next included?

# last day
results.append(df[day_next:])

This approach has the following problems:

a=np.unique(df.index.date) can take a lot of time

df[day_now:day_next] includes the day_next, but I need to exclude it in the range

Body:
If you want to group by date (AKA: year+month+day), then use df.index.date:

result = [group[1] for group in df.groupby(df.index.date)]

As df.index.day will use the day of the month (i.e.: from 1 to 31) for grouping, which could result in undesirable behavior if the input dataframe dates extend to multiple months.


问:
How to detect if URL() constructor is supported by browsers?
I want to detect if a browser support the URL() constructor.

I want to use it like this:

```<code>const url = new URL(urlString, [baseURLstring])
</code>```

I can't find a proper method to check if it's supported by browser?

答:
If const is supported, URL is likely also supported - except

URL is not supported by IE at all it seems

https://developer.mozilla.org/en-US/docs/Web/API/URL/URL

http://caniuse.com/#feat=url

if (window.URL) ...

Body:
I want to detect if a browser support the URL() constructor.

I want to use it like this:

const url = new URL(urlString, [baseURLstring])

I can't find a proper method to check if it's supported by browser?


问:
nested delete/sql statements
the following statement returns this:

```<code>select rowid,name,compound,COUNT(*) from qvalues where rowid in (select rowid from batchinfo where instrument='tf1')
group by rowid,name,compound
having COUNT(*)>1

rowid   name    compound    (No column name)
19300   QC1 ETG 2
20379   QC4 ETS 2
20686   QC2 ETG 2
19402   QC1 ETG 2
23605   QC1 ETG 2
21705   QC3 ETS 2
23678   QC1 ETG 2
18480   QC2 ETG 2
</code>```

.....
......
.....

i have another table called qvalues:

```<code>rid name    compound    rt  response    finalConc   qvalue  rowid
229263  QC3 Hydromorphone   0.69    6228.00 82.53   98  4695
229264  QC3 Morphine    0.51    3168.00 119.89  99  4695
229265  QC3 Oxymorphone 0.57    2472.00 83.89   99  4695
229266  QC3 Benzoylecgonine 2.17    20439.25    85.99   95  4695
229267  QC3 Codeine 1.34    4829.00 82.85   96  4695
229268  QC3 Hydrocodone 1.58    12416.00    84.99   94  4695
229269  QC3 Oxycodone   1.47    5430.00 78.44   94  4695
229270  QC3 Buprenorphine   2.54    366.13  10.41   98  4695
229271  QC3 Mepbrobamate    2.50    1330.34 95.56   92  4695
229272  QC3 Methadone   2.68    85897.27    86.77   92  4695
</code>```

what i need to do is take the combination of the ROWID,NAME,COMPOUND from the first set and keep only the first occurrence of it in the second set. i need to delete all other rows that have the combination of ROWID, NAME, and COMPOUND from the compound. i need to keep this combination where the RID is the smallest.

please let me know if i need to clarify anything

答:
So you want to delete everything that is in batchinfo except the record with the smallest rid ...

```<code>delete qvalues where rid in
    (select rid
    from qvalues
    where rowid in (select rowid from batchinfo where instrument='tf1')
    except
    select rid
    from (select rid=min(rid)
        from qvalues
        where rowid in (select rowid from batchinfo where instrument='tf1')
        group by rowid,name,compound) x);
</code>```

count>2 isn't necessary because with count=1 it is always the record with the smalles rid.

Title: nested delete/sql statements

Body:
the following statement returns this:

select rowid,name,compound,COUNT(*) from qvalues where rowid in (select rowid from batchinfo where instrument='tf1')
group by rowid,name,compound
having COUNT(*)>1

rowid   name    compound    (No column name)
19300   QC1 ETG 2
20379   QC4 ETS 2
20686   QC2 ETG 2
19402   QC1 ETG 2
23605   QC1 ETG 2
21705   QC3 ETS 2
23678   QC1 ETG 2
18480   QC2 ETG 2

.....
......
.....

i have another table called qvalues:

rid name    compound    rt  response    finalConc   qvalue  rowid
229263  QC3 Hydromorphone   0.69    6228.00 82.53   98  4695
229264  QC3 Morphine    0.51    3168.00 119.89  99  4695
229265  QC3 Oxymorphone 0.57    2472.00 83.89   99  4695
229266  QC3 Benzoylecgonine 2.17    20439.25    85.99   95  4695
229267  QC3 Codeine 1.34    4829.00 82.85   96  4695
229268  QC3 Hydrocodone 1.58    12416.00    84.99   94  4695
229269  QC3 Oxycodone   1.47    5430.00 78.44   94  4695
229270  QC3 Buprenorphine   2.54    366.13  10.41   98  4695
229271  QC3 Mepbrobamate    2.50    1330.34 95.56   92  4695
229272  QC3 Methadone   2.68    85897.27    86.77   92  4695

what i need to do is take the combination of the ROWID,NAME,COMPOUND from the first set and keep only the first occurrence of it in the second set. i need to delete all other rows that have the combination of ROWID, NAME, and COMPOUND from the compound. i need to keep this combination where the RID is the smallest.

please let me know if i need to clarify anything

Body:
So you want to delete everything that is in batchinfo except the record with the smallest rid ...

delete qvalues where rid in
    (select rid
    from qvalues
    where rowid in (select rowid from batchinfo where instrument='tf1')
    except
    select rid
    from (select rid=min(rid)
        from qvalues
        where rowid in (select rowid from batchinfo where instrument='tf1')
        group by rowid,name,compound) x);

count>2 isn't necessary because with count=1 it is always the record with the smalles rid.


问:
MySQL Workbench High DPI
So I'm using MySQL workbench in a new high DPI, high resolution setting.  If I allow MySQL Workbench to use Window's DPI settings, the font becomes blurry everywhere but the editor.

If I disable the DPI settings (in Compatibility) and raise the font size in the Workbench Preferences, it looks fine except for the left menu (schema list, table list, object info) which is very small font.  Does anyone know of any workaround or an alternative to Workbench?  It's going to be hard to continue using Workbench with a high resolution display otherwise.  HeidiSQL suffered the same DPI blurry font problem.  So it's either headache or squinting.

答: I am using Windows 10 Pro, after the Creators upgrade, and a 4K 27" monitor. Right-click on the MySQL Workbench program icon, choose "Compatibility", then tick "Override high DPI scaling behavior. Scaling performed by:", then choose "System (Enhanced)". That makes it look reasonable, although the table names are still pixel-doubled so they look fuzzy, and the Output windows still uses a small font.</p>

Title: MySQL Workbench High DPI