问:
Serializng and deserializing empty arrays to Dictionary/object
I'm working on a Silverlight 3 application that has to communicate with a PHP 5.2.13 server app.
We're using JSON.NET to finish the job, but I'm having some problems with Dictionaries.

I'm doing some experiments and trying to deserialize an object that contains a Dictionary:

```<code>public Dictionary<string, Block> Table
{
  get { return m_table; }
  set { m_table = value; }
}
</code>```

C# serializes properly and I'm happy with it, but on the PHP side, when serializing an equivalent object that has an empty Table, it won't work.

```<code>$this->Table = array();
</code>```

The problem is that empty arrays, obviously, aren't considered an assoc array and so they are exported as [] instead of {}.

I thought of adding something like 'null' => null to the array (force assoc) and then do some clean-up in the client, but I don't control the client C# objects neither I can constraint them to be nullable so... I'm stuck on this one ;)

Do you know of any solution?

Thanks for your time, very much appreciated :)

EDIT: To clarify, I can't control the structure of both, the C# and PHP objects.
On my test I've created an object which contains a dictionary but the hole object gets encoded at once.
Here's an over simplified version of it:

```<code>class Block
{
  public $X = 0;
  public $Y = 0;
  public $Name = '';
  public $Children = array();
  public $Table = array();
  public $Nested = null;
}
</code>```

Where Table should be a dictionary and encoded as

```<code>echo json_encode( new Block() );
</code>```

答:
I prefer the 2nd method by simplecode, which works in this case</p>

```<code><?php
$b = array(
    "a" => array(),
    "b" => (object)array()
);

echo "Empty array output as array: " . json_encode($b) . "\n";
?>
</code>```

Body:
I'm working on a Silverlight 3 application that has to communicate with a PHP 5.2.13 server app.
We're using JSON.NET to finish the job, but I'm having some problems with Dictionaries.

I'm doing some experiments and trying to deserialize an object that contains a Dictionary:

public Dictionary<string, Block> Table
{
  get { return m_table; }
  set { m_table = value; }
}

C# serializes properly and I'm happy with it, but on the PHP side, when serializing an equivalent object that has an empty Table, it won't work.

$this->Table = array();

The problem is that empty arrays, obviously, aren't considered an assoc array and so they are exported as [] instead of {}.

I thought of adding something like 'null' => null to the array (force assoc) and then do some clean-up in the client, but I don't control the client C# objects neither I can constraint them to be nullable so... I'm stuck on this one ;)

Do you know of any solution?

Thanks for your time, very much appreciated :)

EDIT: To clarify, I can't control the structure of both, the C# and PHP objects.
On my test I've created an object which contains a dictionary but the hole object gets encoded at once.
Here's an over simplified version of it:

class Block
{
  public $X = 0;
  public $Y = 0;
  public $Name = '';
  public $Children = array();
  public $Table = array();
  public $Nested = null;
}

Where Table should be a dictionary and encoded as

echo json_encode( new Block() );

Body:
I prefer the 2nd method by simplecode, which works in this case

<?php
$b = array(
    "a" => array(),
    "b" => (object)array()
);

echo "Empty array output as array: " . json_encode($b) . "\n";
?>


来源: stackexchange

问:
How to handle rowspan while scraping a wikitable using python?
I am trying to scrape the data stored in the table of this wikipedia page https://en.wikipedia.org/wiki/Minister_of_Agriculture_(India). However i am unable to scrape the full data stored in rowspan Hers's what i wrote so far:</p>

```<code>from bs4 import BeautifulSoup
from urllib.request import urlopen

wiki = urlopen("https://en.wikipedia.org/wiki/Minister_of_Agriculture_(India)")

soup = BeautifulSoup(wiki, "html.parser")

table = soup.find("table", { "class" : "wikitable" })
for row in table.findAll("tr"):
    cells = row.findAll("td")

    if cells:
        name = cells[0].find(text=True)
        pic = cells[1].find("img")
        strt = cells[2].find(text=True)
        end = cells[3].find(text=True)
        pri = cells[6].find(text=True)

        z=name+'\n'+pic+'\n'+strt+'\n'+end+'\n'+pri
        print z
</code>```

答:
This is the only one solution of this question. Here I will change rowspan, colspan table to simple table.
I wasted many days in this problem but easy & good solution is not found. In many stackoverflow solution, developer was scraping only text. But in my case, I need url links also. So, I wrote this code.
This is working for me </p>

```<code># this code written in beautifulsoup python3.5
# fetch one wikitable in html format with links from wikipedia
from bs4 import BeautifulSoup
import requests
import codecs
import os

url = "https://en.wikipedia.org/wiki/Ministry_of_Agriculture_%26_Farmers_Welfare"

fullTable = '<table class="wikitable">'

rPage = requests.get(url)
soup = BeautifulSoup(rPage.content, "lxml")

table = soup.find("table", {"class": "wikitable"})

rows = table.findAll("tr")
row_lengths = [len(r.findAll(['th', 'td'])) for r in rows]
ncols = max(row_lengths)
nrows = len(rows)

# rows and cols convert list of list
for i in range(len(rows)):
    rows[i]=rows[i].findAll(['th', 'td'])

# Header - colspan check in Header
for i in range(len(rows[0])):
    col = rows[0][i]
    if (col.get('colspan')):
        cSpanLen = int(col.get('colspan'))
        del col['colspan']
        for k in range(1, cSpanLen):
            rows[0].insert(i,col)

# rowspan check in full table
for i in range(len(rows)):
    row = rows[i]
    for j in range(len(row)):
        col = row[j]
        del col['style']
        if (col.get('rowspan')):
            rSpanLen = int(col.get('rowspan'))
            del col['rowspan']
            for k in range(1, rSpanLen):
                rows[i+k].insert(j,col)

# create table again
for i in range(len(rows)):
    row = rows[i]
    fullTable += '<tr>'
    for j in range(len(row)):
        col = row[j]
        rowStr=str(col)
        fullTable += rowStr
    fullTable += '</tr>'

fullTable += '</table>'

# table links changed
fullTable = fullTable.replace('/wiki/', 'https://en.wikipedia.org/wiki/')
fullTable = fullTable.replace('\n', '')
fullTable = fullTable.replace('<br/>', '')

# save file as a name of url
page=os.path.split(url)[1]
fname='outuput_{}.html'.format(page)
singleTable = codecs.open(fname, 'w', 'utf-8')
singleTable.write(fullTable)

# here we can start scraping in this table there rowspan and colspan table changed to simple table
soupTable = BeautifulSoup(fullTable, "lxml")
urlLinks = soupTable.findAll('a');
print(urlLinks)

# and so on .............
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to scrape the data stored in the table of this wikipedia page https://en.wikipedia.org/wiki/Minister_of_Agriculture_(India). However i am unable to scrape the full data stored in rowspan Hers's what i wrote so far:

from bs4 import BeautifulSoup
from urllib.request import urlopen

wiki = urlopen("https://en.wikipedia.org/wiki/Minister_of_Agriculture_(India)")

soup = BeautifulSoup(wiki, "html.parser")

table = soup.find("table", { "class" : "wikitable" })
for row in table.findAll("tr"):
    cells = row.findAll("td")

    if cells:
        name = cells[0].find(text=True)
        pic = cells[1].find("img")
        strt = cells[2].find(text=True)
        end = cells[3].find(text=True)
        pri = cells[6].find(text=True)

        z=name+'\n'+pic+'\n'+strt+'\n'+end+'\n'+pri
        print z

Body:
This is the only one solution of this question. Here I will change rowspan, colspan table to simple table.
I wasted many days in this problem but easy & good solution is not found. In many stackoverflow solution, developer was scraping only text. But in my case, I need url links also. So, I wrote this code.
This is working for me

# this code written in beautifulsoup python3.5
# fetch one wikitable in html format with links from wikipedia
from bs4 import BeautifulSoup
import requests
import codecs
import os

url = "https://en.wikipedia.org/wiki/Ministry_of_Agriculture_%26_Farmers_Welfare"

fullTable = '<table class="wikitable">'

rPage = requests.get(url)
soup = BeautifulSoup(rPage.content, "lxml")

table = soup.find("table", {"class": "wikitable"})

rows = table.findAll("tr")
row_lengths = [len(r.findAll(['th', 'td'])) for r in rows]
ncols = max(row_lengths)
nrows = len(rows)

# rows and cols convert list of list
for i in range(len(rows)):
    rows[i]=rows[i].findAll(['th', 'td'])

# Header - colspan check in Header
for i in range(len(rows[0])):
    col = rows[0][i]
    if (col.get('colspan')):
        cSpanLen = int(col.get('colspan'))
        del col['colspan']
        for k in range(1, cSpanLen):
            rows[0].insert(i,col)

# rowspan check in full table
for i in range(len(rows)):
    row = rows[i]
    for j in range(len(row)):
        col = row[j]
        del col['style']
        if (col.get('rowspan')):
            rSpanLen = int(col.get('rowspan'))
            del col['rowspan']
            for k in range(1, rSpanLen):
                rows[i+k].insert(j,col)

# create table again
for i in range(len(rows)):
    row = rows[i]
    fullTable += '<tr>'
    for j in range(len(row)):
        col = row[j]
        rowStr=str(col)
        fullTable += rowStr
    fullTable += '</tr>'

fullTable += '</table>'

# table links changed
fullTable = fullTable.replace('/wiki/', 'https://en.wikipedia.org/wiki/')
fullTable = fullTable.replace('\n', '')
fullTable = fullTable.replace('<br/>', '')

# save file as a name of url
page=os.path.split(url)[1]
fname='outuput_{}.html'.format(page)
singleTable = codecs.open(fname, 'w', 'utf-8')
singleTable.write(fullTable)

# here we can start scraping in this table there rowspan and colspan table changed to simple table
soupTable = BeautifulSoup(fullTable, "lxml")
urlLinks = soupTable.findAll('a');
print(urlLinks)

# and so on .............

ContentLicense: CC BY-SA 3.0


问:
Exactly one of whitelist/blacklist/topic is required
I am trying to start Kafka consumer but it is showing below error:</p>

```<code>$ bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic Hello-Kafka
Exactly one of whitelist/blacklist/topic is required.
Option                                  Description
------                                  -----------
--blacklist <blacklist>                 Blacklist of topics to exclude from
                                          consumption.
--bootstrap-server <server to connect
  to>
--consumer.config <config file>         Consumer config properties file.
--csv-reporter-enabled                  If set, the CSV metrics reporter will
                                          be enabled
--delete-consumer-offsets               If specified, the consumer path in
                                          zookeeper is deleted when starting up

............
............
</code>```

答:
You can use as below:

bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --from-beginning --topic Hello-Kafka

Body:
I am trying to start Kafka consumer but it is showing below error:

$ bin/kafka-console-consumer.sh --zookeeper localhost:2181 —topic Hello-Kafka
Exactly one of whitelist/blacklist/topic is required.
Option                                  Description
------                                  -----------
--blacklist <blacklist>                 Blacklist of topics to exclude from
                                          consumption.
--bootstrap-server <server to connect
  to>
--consumer.config <config file>         Consumer config properties file.
--csv-reporter-enabled                  If set, the CSV metrics reporter will
                                          be enabled
--delete-consumer-offsets               If specified, the consumer path in
                                          zookeeper is deleted when starting up

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


问:
What is similar to coordinate layout (like android) in swift?
I just want to give animation in my app like tinder to show profile description page. In android its default functionality in material design by using coordinate layout class. Any one know that how can I give the same animation in my application?</p>

答:
The main appeal of the CoordinatorLayout is its ability to coordinate
  the animations and transitions of the views within it through coordinates

There is no layout type like this in iOS

iOS layout is much simpler and give you more control, what you need to do is working with some UIView and manipulate them through constraints since constraints layout work perfectly with animation

or if you want to make a separate things you can just add UIContainer and then add to it your UIViewController's

there is a simple tutorial for animating autolayout constraints:
https://useyourloaf.com/blog/animating-autolayout-constraints/


问:
Accessing localhost on Android devices in different network, company server is not public
I am using cordova in visual studio for app development. I need to test app on other devices like Android. Also debug.

But i am not able to access my localhost on Android or any other device. Problems are:
1. Development servers are in different country and are not public.
2. VPN access is not allowed on Android device due to company policy
3. Can not connect Android device to same company wifi due to company policies

I searched and found VirtualBox and some other solutions. But haven't found any post which address this kind of issue.

Sorry if this question is duplicated and if it is then please redirect me to the solution.

It is a big impediment for my team, is there any way to solve this issue as ?

答: use a computer which can access your localhost build hot spots</p>


问:
How to write a like query in Zend Framework 2
I have created a select query that functioning well. But now I need to change this to a like query. Can anyone tell me the correct way?

This is my select query structure ->

```<code>public function getSelectedHotel($id)
{
    $selectedHotel = $this->tableGateway->select(['hotel_id' => $id]);

        return $selectedHotel;
}
</code>```

When I code like this it gives me this error.

Code ->

```<code>$hotelsByYear = $this->tableGateway->select()->where('date_added like ?',$year.'%');
</code>```

Error ->

Fatal error: Uncaught Error: Call to undefined method
  Zend\Db\ResultSet\ResultSet::where() in

Body:
I have created a select query that functioning well. But now I need to change this to a like query. Can anyone tell me the correct way?

This is my select query structure ->

public function getSelectedHotel($id)
{
    $selectedHotel = $this->tableGateway->select(['hotel_id' => $id]);

        return $selectedHotel;
}

When I code like this it gives me this error.

Code ->

$hotelsByYear = $this->tableGateway->select()->where('date_added like ?',$year.'%');

Error ->

Fatal error: Uncaught Error: Call to undefined method
  Zend\Db\ResultSet\ResultSet::where() in

Body: $table->select()->where('Field_Name', '%'.$ParamVal.'%');


问:
How do you insert a file (PDF) into a varbinary SQL Server column and later retrieve it?
I'm looking to take the results of a report run (a PDF file from Crystal Reports), serialize it, stick it into a varbinary field, and then later be able to deserialize it and present it back to the user.

For now I have to just plain old ADO .NET (SqlClient, SqlCommand, etc.)

Are there any pitfalls to this? What is the basic syntax to accomplish this given the fact that I would know the path on the local machine where the PDF file was currently saved?

答:
EDIT: Just seen in the MSDN documentation that Image is going to be removed. Better use use VARBINARY(MAX). (Hey I did not know that).

MY OLD ANSWER: VARBINARY has a limit of 8 KB. Can be too small to store PDF's. You'd better use the IMAGE datatype.

Use parameters to insert/select your data via the SqlCommand, and you can use just plain SQL like any ordinary field.

The data you pass into the image field is an array of bytes.

Edit 2: Since you are using C#, you should retrieve the data using a DataReader. To create the DataReader use the SequentialAccess flag on the SqlCommand.ExecuteReader, to prevent the data being read into memory too early.

OwnerDisplayName: Jesse

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: peSHIr

OwnerDisplayName: GvS

LastEditorDisplayName: GvS


问:
How to create image and labels using location data stored in NSArray
i have to create an 2images and 3 labels by using code (cgrectmake)and i am having X location, y location, width and height all are stored in arrays(which i have retrieved from the web services)how can i create the image and labels can any one help me</p>

答:
Most objects have a -description method which returns a string representation of the object:

```<code>- (NSString *)description;
</code>```

For example:

```<code>NSArray *array = [NSArray arrayWithObjects:@"The", @"quick", @"brown", @"fox", nil];
NSLog(@"%@", array); // prints the contents of the array out to the console.
NSString *arrayDescription = [array description]; // a string
</code>```

It would help to know what you want to do with the string (how will you use the string). Also, what kind of objects do you have in the array?

In that case, Matthew's answer is one possibility. Another might be to use an NSMutableString and append the individual items, if you need control over how the string is created:

```<code>NSMutableString *string = [NSMutableString string];
if ([array count] >= 3) {
    [string appendString:[array objectAtIndex:0]];
    [string appendFormat:@"blah some filler text %@", [array objectAtIndex:1]];
    [string appendString:[array objectAtIndex:2]];
}
</code>```

Body:
Most objects have a -description method which returns a string representation of the object:

- (NSString *)description;

For example:

NSArray *array = [NSArray arrayWithObjects:@"The", @"quick", @"brown", @"fox", nil];
NSLog(@"%@", array); // prints the contents of the array out to the console.
NSString *arrayDescription = [array description]; // a string

It would help to know what you want to do with the string (how will you use the string). Also, what kind of objects do you have in the array?

In that case, Matthew's answer is one possibility. Another might be to use an NSMutableString and append the individual items, if you need control over how the string is created:

NSMutableString *string = [NSMutableString string];
if ([array count] >= 3) {
    [string appendString:[array objectAtIndex:0]];
    [string appendFormat:@"blah some filler text %@", [array objectAtIndex:1]];
    [string appendString:[array objectAtIndex:2]];
}


问:
Restrict login if user is disabled in Laravel not working quite well
I'm trying to make simple admin function to disable/enable users rather than delete them.

So far I have admin function which successfully update table users and change the status to 0(enabled) and 1(disabled).

Now I have problems when user trying to log and checking his status.

This is my function for login in UserController.php

```<code>public function loginSubmit() {

    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user = User::where('is_disabled', 0)->first();
    if ($user->is_disabled == 1) {
        $validator->messages()->add('username', 'User not found.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);

    return Redirect::to('/');
}
</code>```

The problem is that when the condition is true ($user->is_disabled == 1) it is logged me in with the next user from table e.g. first user which is is_disabled = 0.

How can I make this in proper way?

答:
The code $user = User::where('is_disabled', 0)->first(); is unnecessary and fetches the wrong user.

```<code>public function redirectWithError($errors)
{
    return Redirect::to('/users/login')
        ->withErrors($errors)
        ->withInput(Input::except(['captcha']));
}

public function loginSubmit()
{

    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return $this->redirectWithError($validator->errors());
    }

    if ($user->is_disabled == 1) {
        $validator->messages()->add('username', 'User not found.');
        return $this->redirectWithError($validator->errors());
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);

    return Redirect::to('/');
}
</code>```

Body:
I'm trying to make simple admin function to disable/enable users rather than delete them.

So far I have admin function which successfully update table users and change the status to 0(enabled) and 1(disabled).

Now I have problems when user trying to log and checking his status.

This is my function for login in UserController.php

public function loginSubmit() {

    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user = User::where('is_disabled', 0)->first();
    if ($user->is_disabled == 1) {
        $validator->messages()->add('username', 'User not found.');
        return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);

    return Redirect::to('/');
}

The problem is that when the condition is true ($user->is_disabled == 1) it is logged me in with the next user from table e.g. first user which is is_disabled = 0.

How can I make this in proper way?

Body:
The code $user = User::where('is_disabled', 0)->first(); is unnecessary and fetches the wrong user.

public function redirectWithError($errors)
{
    return Redirect::to('/users/login')
        ->withErrors($errors)
        ->withInput(Input::except(['captcha']));
}

public function loginSubmit()
{

    $user = User::where('username', Input::get('username'))->first();
    if (!$user) {
        $validator->messages()->add('username', 'Invalid login or password.');
        return $this->redirectWithError($validator->errors());
    }

    if ($user->is_disabled == 1) {
        $validator->messages()->add('username', 'User not found.');
        return $this->redirectWithError($validator->errors());
    }

    $user->last_login = \Carbon\Carbon::now();
    $user->save();
    Session::put('user', ['user_id' => $user->user_id]);

    return Redirect::to('/');
}


问:
Displaying custom error page at startup
Is there a way to display a custom error page when an exception occurs during the startup phase of an ASP.NET Core application? For example, if an exception occurs (db is down etc.) in any of the methods of the Startup class i.e. Configure, ConfigureServices, Startup.Ctor etc.?

I think that using the following code isn't going to help me

```<code>if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseBrowserLink();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}
</code>```

as the middleware pipline isn't constructed yet. So the line

```<code>app.UseExceptionHandler("/Home/Error");
</code>```

isn't executed as a consequence.

Is there a way to display a custom error page if an error occurs at this stage?

thanks

ashilon

答: For a simple approach, you can have a script block that contains alert("your error message"). If you want the popup to be styled as the rest of your website then you could render your error message into a div element and use a jQuery dialog to display it as a modal dialog within your page, then you just need to put it in your code :D , hope this helps!</p>

Title: Displaying custom error page at startup

Body:
Is there a way to display a custom error page when an exception occurs during the startup phase of an ASP.NET Core application? For example, if an exception occurs (db is down etc.) in any of the methods of the Startup class i.e. Configure, ConfigureServices, Startup.Ctor etc.?

I think that using the following code isn't going to help me

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseBrowserLink();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}

as the middleware pipline isn't constructed yet. So the line

app.UseExceptionHandler("/Home/Error");

isn't executed as a consequence.

Is there a way to display a custom error page if an error occurs at this stage?

thanks

ashilon


问:
Remove text line in XML file C# .NET
i need to write app to remove specific text line in very large XML file (about 3,5 GB).

I wrote this code:

```<code>    string directoryPath;

    OpenFileDialog ofd = new OpenFileDialog();

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "XML|*.xml";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            directoryPath = Path.GetDirectoryName(ofd.FileName);
            textBox2.Text = directoryPath;
            textBox1.Text = ofd.SafeFileName;
        }
    }

    private void Replace()
    {
        StreamReader readerFile = new StreamReader(ofd.FileName, System.Text.Encoding.UTF8);

        while (!readerFile.EndOfStream)
        {
            string stringReplaced;
            string replaceResult = textBox2.Text + "\\" + "replace_results";
            Directory.CreateDirectory(replaceResult);
            StreamWriter writerFile = new StreamWriter(replaceResult + "\\" + textBox1.Text, true);
            StringBuilder sb = new StringBuilder();
            char[] buff = new char[10 * 1024 * 1024];
            int xx = readerFile.ReadBlock(buff, 0, buff.Length);
            sb.Append(buff);
            stringReplaced = sb.ToString();
            stringReplaced = stringReplaced.Replace("line to remove", string.Empty);
            writerFile.WriteLine(stringReplaced);
            writerFile.Close();
            writerFile.Dispose();
            stringReplaced = null;
            sb = null;
        }

        readerFile.Close();
        readerFile.Dispose();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (!backgroundWorker1.IsBusy)
        {
            backgroundWorker1.RunWorkerAsync();
            toolStripStatusLabel1.Text = "Replacing in progress...";
        }
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            Replace();
            toolStripStatusLabel1.Text = "Replacing complete!";
        }
        catch
        {
            toolStripStatusLabel1.Text = "Error! Replacing aborted!";
        }
    }
}
</code>```

it works, but not as well because new file (after remove lines) is bigger than original file and at the end of new file are added some junk (lots of dots), screenshot:

https://images81.fotosik.pl/615/873833aa0e23b36f.jpg

How i can fix my code to make new file the same as old file, only without specific lines?

答:
For a start why keep opening and closing the output file? Keep it open.

Secondly reading blocks – which could lead to "line to remove" being split across blocks – and writing lines is an odd mix.

But I expect your issue is three fold:

You do not set the encoding of the output file.

When you read the buffer (10MB) you may get fewer characters read – the return from ReadBlock. But you always write the complete block. Limit the write to match the amount read (as updated but the replace).

ReadBlock will include end of lines, but WriteLine will add them: either work on blocks or on lines. Mixing will only create problems (and avoid the second issue above).

This leads to code something like:

```<code>using (var rdr = OpenReadFile(...))
using (var wtr = OpenWriteFile(...)) {
  string line;
  while ((line = rdr.ReadLine()) != null) {
    line = line.Replace(x, y);
     str.WriteLine(line);
  }
}
</code>```

NB Processing XML as text could lead to corrupting the XML (there is no such thing as "invalid XML": either the document is valid XML or it isn't XML, just something that looks a bit like it might be XML). Therefore any such approach needs to be handled with caution. The "proper" answer is to process as XML with the streaming APIs (XmlReader and XmlWriter) to avoid parsing the whole document as one.

Title: Remove text line in XML file C# .NET

Body:
i need to write app to remove specific text line in very large XML file (about 3,5 GB).

I wrote this code:

    string directoryPath;

    OpenFileDialog ofd = new OpenFileDialog();

    private void button1_Click(object sender, EventArgs e)
    {
        ofd.Filter = "XML|*.xml";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            directoryPath = Path.GetDirectoryName(ofd.FileName);
            textBox2.Text = directoryPath;
            textBox1.Text = ofd.SafeFileName;
        }
    }

    private void Replace()
    {
        StreamReader readerFile = new StreamReader(ofd.FileName, System.Text.Encoding.UTF8);

        while (!readerFile.EndOfStream)
        {
            string stringReplaced;
            string replaceResult = textBox2.Text + "\\" + "replace_results";
            Directory.CreateDirectory(replaceResult);
            StreamWriter writerFile = new StreamWriter(replaceResult + "\\" + textBox1.Text, true);
            StringBuilder sb = new StringBuilder();
            char[] buff = new char[10 * 1024 * 1024];
            int xx = readerFile.ReadBlock(buff, 0, buff.Length);
            sb.Append(buff);
            stringReplaced = sb.ToString();
            stringReplaced = stringReplaced.Replace("line to remove", string.Empty);
            writerFile.WriteLine(stringReplaced);
            writerFile.Close();
            writerFile.Dispose();
            stringReplaced = null;
            sb = null;
        }

        readerFile.Close();
        readerFile.Dispose();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (!backgroundWorker1.IsBusy)
        {
            backgroundWorker1.RunWorkerAsync();
            toolStripStatusLabel1.Text = "Replacing in progress...";
        }
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            Replace();
            toolStripStatusLabel1.Text = "Replacing complete!";
        }
        catch
        {
            toolStripStatusLabel1.Text = "Error! Replacing aborted!";
        }
    }
}

it works, but not as well because new file (after remove lines) is bigger than original file and at the end of new file are added some junk (lots of dots), screenshot:

https://images81.fotosik.pl/615/873833aa0e23b36f.jpg

How i can fix my code to make new file the same as old file, only without specific lines?

Body:
For a start why keep opening and closing the output file? Keep it open.

Secondly reading blocks – which could lead to "line to remove" being split across blocks – and writing lines is an odd mix.

But I expect your issue is three fold:

You do not set the encoding of the output file.

When you read the buffer (10MB) you may get fewer characters read – the return from ReadBlock. But you always write the complete block. Limit the write to match the amount read (as updated but the replace).

ReadBlock will include end of lines, but WriteLine will add them: either work on blocks or on lines. Mixing will only create problems (and avoid the second issue above).

This leads to code something like:

using (var rdr = OpenReadFile(...))
using (var wtr = OpenWriteFile(...)) {
  string line;
  while ((line = rdr.ReadLine()) != null) {
    line = line.Replace(x, y);
     str.WriteLine(line);
  }
}

NB Processing XML as text could lead to corrupting the XML (there is no such thing as "invalid XML": either the document is valid XML or it isn't XML, just something that looks a bit like it might be XML). Therefore any such approach needs to be handled with caution. The "proper" answer is to process as XML with the streaming APIs (XmlReader and XmlWriter) to avoid parsing the whole document as one.


问:
Sharepoint XSL - break string into componant parts
I'm using a "choice" site column with the multiple-check option enabled so that users can tag a list item with several choices from the column.

This column then powers a design feature in a content query webpart - where the column choice is appended to create an image filename.

Choice1

Choice2

Choice3

Choice4

becomes

```<code><img src="http://mysite/content-Choice1.jpg />
</code>```

The problem I've got is that the XSL parser is fed a string which has semicolons (;) and hashes (#) separating the choice values. If all 4 options were ticked, the string fed into the XSLT parser would be:

```<code>;#Choice1;#Choice2;#Choice3;#Choice4
</code>```

How can I work through the string and separate each choice into its own XSL variable?

I've tried various substring-before functions, but I can't get anything working.

答:
Since XPath 1.0 does not support the tokenize() function, you'll have to do all the work yourself. For instance, you can generate the  elements recursively from the choices:

```<code><xsl:template name="RecurseConvertChoicesToImages">
    <xsl:param name="choices" />

    <xsl:variable name="token"
        select="substring-before($choices, ';#')" />
    <xsl:variable name="nextToken"
        select="substring-after($choices, ';#')" />

    <xsl:if test="$token">
        <img src="http://mysite/content-{$token}.jpg" />
    </xsl:if>
    <xsl:if test="$nextToken">
        <xsl:call-template name="RecurseConvertChoicesToImages">
            <xsl:with-param name="choices" select="$nextToken" />
        </xsl:call-template>
    </xsl:if>
</xsl:template>
</code>```

Body:
I'm using a "choice" site column with the multiple-check option enabled so that users can tag a list item with several choices from the column.

This column then powers a design feature in a content query webpart - where the column choice is appended to create an image filename.

Choice1

Choice2

Choice3

Choice4

becomes

The problem I've got is that the XSL parser is fed a string which has semicolons (;) and hashes (#) separating the choice values. If all 4 options were ticked, the string fed into the XSLT parser would be:

;#Choice1;#Choice2;#Choice3;#Choice4

How can I work through the string and separate each choice into its own XSL variable?

I've tried various substring-before functions, but I can't get anything working.

Body:
Since XPath 1.0 does not support the tokenize() function, you'll have to do all the work yourself. For instance, you can generate the <img> elements recursively from the choices:

<xsl:template name="RecurseConvertChoicesToImages">
    <xsl:param name="choices" />

    <xsl:variable name="token"
        select="substring-before($choices, ';#')" />
    <xsl:variable name="nextToken"
        select="substring-after($choices, ';#')" />

    <xsl:if test="$token">
        <img src="http://mysite/content-{$token}.jpg" />
    </xsl:if>
    <xsl:if test="$nextToken">
        <xsl:call-template name="RecurseConvertChoicesToImages">
            <xsl:with-param name="choices" select="$nextToken" />
        </xsl:call-template>
    </xsl:if>
</xsl:template>


问:
Unable to Build Project after update to android studio preview 3.0 canary 3
I Just update my android studio preview 3.0 canary 3. After this I am trying to run the project but showing following error.</p>

```<code>Error:Could not find com.android.tools.build:gradle:3.0.0.
Searched in the following locations:
    file:/opt/android-studio-preview/gradle/m2repository/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom
    file:/opt/android-studio-preview/gradle/m2repository/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.jar
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.jar
Required by:
    project :
</code>```

答:
The main things you need to do are:

Change your project level build.gradle file to:

```<code>buildscript {
    repositories {
        ...
        // You need to add the following repository to download the
        // new plugin.
        maven {
          url 'https://maven.google.com'
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
    }
}
</code>```

Change the distributionUrl of your gradle-wrapper.properties to the currently latest available release of Gradle.

```<code>distributionUrl=https://services.gradle.org/distributions/gradle-4.0-rc-1-all.zip
</code>```

After this steps your project could not compile yet, and you need to follow all the instructions here on how to convert your app build.gradle to the new plugin

Body:
I Just update my android studio preview 3.0 canary 3. After this I am trying to run the project but showing following error.

Error:Could not find com.android.tools.build:gradle:3.0.0.
Searched in the following locations:
    file:/opt/android-studio-preview/gradle/m2repository/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom
    file:/opt/android-studio-preview/gradle/m2repository/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.jar
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.jar
Required by:
    project :

Body:
The main things you need to do are:

Change your project level build.gradle file to:

buildscript {
    repositories {
        ...
        // You need to add the following repository to download the
        // new plugin.
        maven {
          url 'https://maven.google.com'
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
    }
}

Change the distributionUrl of your gradle-wrapper.properties to the currently latest available release of Gradle.

distributionUrl=https://services.gradle.org/distributions/gradle-4.0-rc-1-all.zip

After this steps your project could not compile yet, and you need to follow all the instructions here on how to convert your app build.gradle to the new plugin


问:
Laravel with with where eloquent
```<code>public function getGroupCategories() {

        $group_categories = GroupCategory::with('groupCategoriesTranslation', function($query) {
            $query->where('code', 'en');
        });

        return $group_categories;
    }
</code>```

Hello,

I want to write this query in eloquent :

SELECT * FROM group_categories AS gc INNER JOIN
  group_categories_translation AS gct ON gc.id = gct.group_category_id
  WHERE gct.code = 'en'

Laravel version is 5.3

Error :

mb_strpos() expects parameter 1 to be string, object given

It works when i use whereHas instead of with, but it returns only group_category.

答:
You're using wrong syntax. Correct syntax for with() is:</p>

```<code>public function getGroupCategories() {

    $group_categories = GroupCategory::with(['groupCategoriesTranslation' => function($query){
        $query->where('code', 'en');
    }]);

    return $group_categories;
}
</code>```

Title: Laravel with with where eloquent

Body:
public function getGroupCategories() {

        $group_categories = GroupCategory::with('groupCategoriesTranslation', function($query) {
            $query->where('code', 'en');
        });

        return $group_categories;
    }

Hello,

I want to write this query in eloquent :

SELECT * FROM group_categories AS gc INNER JOIN
  group_categories_translation AS gct ON gc.id = gct.group_category_id
  WHERE gct.code = 'en'

Laravel version is 5.3

Error :

mb_strpos() expects parameter 1 to be string, object given

It works when i use whereHas instead of with, but it returns only group_category.

Body:
You're using wrong syntax. Correct syntax for with() is:

public function getGroupCategories() {

    $group_categories = GroupCategory::with(['groupCategoriesTranslation' => function($query){
        $query->where('code', 'en');
    }]);

    return $group_categories;
}


问:
Check mime type is correct image?
I want when upload image to check is really image?

I use this-

```<code>$finfo = finfo_open(FILEINFO_MIME_TYPE);
$temp = $_FILES["avatar"]["tmp_name"];
$ext = finfo_file($finfo, $temp);
</code>```

Return is something like that-

text/html

image/gif

application/vnd.ms-excel

Maybe if i create array like this-

```<code>$array = arry("image/jpeg", "image/jpg", "image/png", "image/gif");
</code>```

And want to check if $ext value is in that array then it's correct image ?

答:
You can do like below:

```<code>if(in_array($ext,$array))
{
//image
}
else
{
//not an image
}
</code>```

More information check here

Title: Check mime type is correct image?

Body:
I want when upload image to check is really image?

I use this-

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$temp = $_FILES["avatar"]["tmp_name"];
$ext = finfo_file($finfo, $temp);

Return is something like that-

text/html

image/gif

application/vnd.ms-excel

Maybe if i create array like this-

$array = arry("image/jpeg", "image/jpg", "image/png", "image/gif");

And want to check if $ext value is in that array then it's correct image ?

Body:
You can do like below:

if(in_array($ext,$array))
{
//image
}
else
{
//not an image
}

More information check here


问:
Retrieve an Integer part from a String
I have to use an int value "nid" to work on. But this int value should be an combination of int "did" and String "a"!

```<code>int did = 123456;
String a = "_b";
int nid = Integer.parseInt((did+a).toString());
</code>```

But for this code i get the error message

```<code>java.lang.NumberFormatException: For input string: "123456_b"
</code>```

Is there any way, to convert a combination of int and string to int?

答:
Is there any way, to convert a combination of int and string to int?

Only if the string is a numeric value.

It is not your case.

Integer.parseInt(String) waits for a String parameter that is a parsable integer.
But you could never use the "_b" String as a valid part of an integer value.

However, you can store the computation as a String :

```<code>int did = 123456;
String a = "_b";
String nid = did + a;
</code>```

Title: Retrieve an Integer part from a String

Body:
I have to use an int value "nid" to work on. But this int value should be an combination of int "did" and String "a"!

int did = 123456;
String a = "_b";
int nid = Integer.parseInt((did+a).toString());

But for this code i get the error message

java.lang.NumberFormatException: For input string: "123456_b"

Is there any way, to convert a combination of int and string to int?

Body:
Is there any way, to convert a combination of int and string to int?

Only if the string is a numeric value.

It is not your case.

Integer.parseInt(String) waits for a String parameter that is a parsable integer.
But you could never use the "_b" String as a valid part of an integer value.

However, you can store the computation as a String :

int did = 123456;
String a = "_b";
String nid = did + a;


问:
What is the best way to implement shorting(Multiple time on single data) and filter with core data with Swift 3?
[Core data provides NSFetchResultController to help with UITableView. I want to sort data with Duration, Depart, Arrival, Price, and Number of stops with ascending and descending orders.
I con sort data by providing sort descriptor to fetch request.

I just want to know is it best way to create FetchResultController for each sorting?

答:
Yes, you should create a new fetchedResultsController each time you need to sort. A fetchedResultsController tracks updates, deletes, inserts and moves, so if your data changes after you fetch it, the fetchedResultsController will tell you how to update your view.  If you just do a fetch and then resort the results, the data can get out of date. And worse, if you access an object after it has been deleted your app will crash.  A fetchedResultsController protects you from those issues.

Even with large data sets I have not had any problem creating a new fetchedResultsController every time the user wishes to sort.  If you find that you have performance problems you should deal with it then and not pre-optimize.


问:
How to select a custom serilaizer for a particular field of a model in below scenario
below are two custom date serializers:

```<code>package test;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class DateFormatter extends StdSerializer<Date> {

    private SimpleDateFormat sampleFormatOne= new SimpleDateFormat("dd-MMM-yyyy");

    public DateFormatter(Class<Date> t) {
        super(t);
    }

    public DateFormatter() {
        super(Date.class);
    }

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException,
            JsonGenerationException {
        java.util.Date inputDate = new java.util.Date(date.getTime());

        jsonGenerator.writeString(sampleFormatOne.format(inputDate));
    }

}
</code>```

Also there is another serializer for date:

```<code>package test;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class DateFormatterTwo extends StdSerializer<Date> {

      private SimpleDateFormat samoelFormatTwo= new SimpleDateFormat("dd-mm-yyyy");y");

    public DateFormatterTwo (Class<Date> t) {
        super(t);
    }

    public DateFormatterTwo () {
        super(Date.class);
    }

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException,
            JsonGenerationException {
        java.util.Date inputDate = new java.util.Date(date.getTime());

        jsonGenerator.writeString(samoelFormatTwo.format(inputDate));
    }

}
</code>```

Spring configuration is as below:

```<code><beans:bean id="customDate"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <beans:property name="objectMapper">
            <beans:bean
                class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                <beans:property name="serializers">
                    <beans:array>
                        <beans:bean class="test.DateFormatter" />
                        <beans:bean class="test.DateFormatterTwo" />
                    </beans:array>
                </beans:property>
            </beans:bean>
        </beans:property>
    </beans:bean>

    <beans:bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter" />
                <beans:ref bean="customDate" />
            </beans:list>
        </beans:property>
    </beans:bean>
</code>```

Now what I need to do is create a JSON object that does serialization of date based on first or second formatter depending on the value of field value employeeType.

With current implementation I could generate a JSON with fixed first format. How can a serializer be selected at run time based on another field value. ?

Following are the fields in model

```<code>private field String employeeType;

    @JsonProperty("empJoiningDate")
    @JsonSerialize(using=DateFormatter.class)
    private Date empJoiningDate = null;
</code>```

答:
In order to have the empJoiningDate field serialized with a format depending on the employeeType, you would need to create a custom Serializer for the Employee POJO type instead of the Date field.

Following this approach, you will have access to all the object fields and may provide your conditional date serialization logic.

The Serializer implementation would be something as follows:

private static class EmployeeSerializer extends StdSerializer<Employee> {

    private static final String TYPE_ONE = "SomeType";

    private static final String TYPE_TWO = "SomeOtherType";

    private SimpleDateFormat sampleFormatOne = /** format initialized **/;

    private SimpleDateFormat sampelFormatTwo = /** format initialized **/;

    protected EmployeeSerializer() {
        super(Employee.class);
    }

    @Override
    public void serialize(Employee employee, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeString(employee.getEmployeeType());
        switch (employee.getEmployeeType()) {
            case TYPE_ONE: jsonGenerator.writeString(sampleFormatOne.format(employee.getEmpJoiningDate()));
            case TYPE_TWO: jsonGenerator.writeString(sampelFormatTwo.format(employee.getEmpJoiningDate()));
        }
        jsonGenerator.writeEndObject();
    }
}
```

<p>You would then need to annotate your <code>Employee</code> value class with your custom serializer instead of the instance date field:</p>

<pre class="lang-java prettyprint-override"><code>@JsonSerialize(using = EmployeeSerializer.class)
public class Employee {
    //...
}
</code>```

Body:
below are two custom date serializers:

package test;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class DateFormatter extends StdSerializer<Date> {

    private SimpleDateFormat sampleFormatOne= new SimpleDateFormat("dd-MMM-yyyy");

    public DateFormatter(Class<Date> t) {
        super(t);
    }

    public DateFormatter() {
        super(Date.class);
    }

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException,
            JsonGenerationException {
        java.util.Date inputDate = new java.util.Date(date.getTime());

        jsonGenerator.writeString(sampleFormatOne.format(inputDate));
    }

}

Also there is another serializer for date:

package test;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class DateFormatterTwo extends StdSerializer<Date> {

      private SimpleDateFormat samoelFormatTwo= new SimpleDateFormat("dd-mm-yyyy");y");

    public DateFormatterTwo (Class<Date> t) {
        super(t);
    }

    public DateFormatterTwo () {
        super(Date.class);
    }

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException,
            JsonGenerationException {
        java.util.Date inputDate = new java.util.Date(date.getTime());

        jsonGenerator.writeString(samoelFormatTwo.format(inputDate));
    }

}

Spring configuration is as below:

<beans:bean id="customDate"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <beans:property name="objectMapper">
            <beans:bean
                class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                <beans:property name="serializers">
                    <beans:array>
                        <beans:bean class="test.DateFormatter" />
                        <beans:bean class="test.DateFormatterTwo" />
                    </beans:array>
                </beans:property>
            </beans:bean>
        </beans:property>
    </beans:bean>

    <beans:bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter" />
                <beans:ref bean="customDate" />
            </beans:list>
        </beans:property>
    </beans:bean>

Now what I need to do is create a JSON object that does serialization of date based on first or second formatter depending on the value of field value employeeType.

With current implementation I could generate a JSON with fixed first format. How can a serializer be selected at run time based on another field value. ?

Following are the fields in model

private field String employeeType;

    @JsonProperty("empJoiningDate")
    @JsonSerialize(using=DateFormatter.class)
    private Date empJoiningDate = null;

Body:
In order to have the empJoiningDate field serialized with a format depending on the employeeType, you would need to create a custom Serializer for the Employee POJO type instead of the Date field.

Following this approach, you will have access to all the object fields and may provide your conditional date serialization logic.

The Serializer implementation would be something as follows:

private static class EmployeeSerializer extends StdSerializer<Employee> {

    private static final String TYPE_ONE = "SomeType";

    private static final String TYPE_TWO = "SomeOtherType";

    private SimpleDateFormat sampleFormatOne = /** format initialized **/;

    private SimpleDateFormat sampelFormatTwo = /** format initialized **/;

    protected EmployeeSerializer() {
        super(Employee.class);
    }

    @Override
    public void serialize(Employee employee, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeString(employee.getEmployeeType());
        switch (employee.getEmployeeType()) {
            case TYPE_ONE: jsonGenerator.writeString(sampleFormatOne.format(employee.getEmpJoiningDate()));
            case TYPE_TWO: jsonGenerator.writeString(sampelFormatTwo.format(employee.getEmpJoiningDate()));
        }
        jsonGenerator.writeEndObject();
    }
}

You would then need to annotate your Employee value class with your custom serializer instead of the instance date field:

@JsonSerialize(using = EmployeeSerializer.class)
public class Employee {
    //...
}


问:
Color top section of Android CardView while keeping rounded corners
So I feel like I'm missing something, but I just cant seem to figure this out. So I want to make a small strip of color on the top of my CardView, but if I use a frame layout, or any kind of layout and set the background color, it covers up the rounded corners of the CardView. Here is some code and a screenshot of the issue. Thank you ahead of time!

```<code><android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
card_view:cardCornerRadius="10dp">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="16dp"
    android:layout_gravity="end"
    android:background="@color/colorPrimaryDark"
    android:clipChildren="true"/>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/menuCardImage"
        android:layout_width="128dp"
        android:layout_height="128dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_margin="8dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_margin="8dp"
        android:layout_toRightOf="@+id/menuCardImage"
        android:orientation="vertical">

        <TextView
            android:id="@+id/menuCardName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="32sp"
            android:textStyle="bold" />

    </LinearLayout>

</RelativeLayout>
</android.support.v7.widget.CardView>
</code>```

Edit:
Turns out it was just a display issue in android studio. When I installed the app it worked correctly.

答:
rather than setting color as background use this drawable to set background.

Create top_strip.xml in drawable folder.

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
    <solid android:color="#FFffffff"/>
</shape>
</code>```

set the radius equal to that of card corner radius and change color as required. It will work

Body:
So I feel like I'm missing something, but I just cant seem to figure this out. So I want to make a small strip of color on the top of my CardView, but if I use a frame layout, or any kind of layout and set the background color, it covers up the rounded corners of the CardView. Here is some code and a screenshot of the issue. Thank you ahead of time!

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
card_view:cardCornerRadius="10dp">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="16dp"
    android:layout_gravity="end"
    android:background="@color/colorPrimaryDark"
    android:clipChildren="true"/>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/menuCardImage"
        android:layout_width="128dp"
        android:layout_height="128dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_margin="8dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_margin="8dp"
        android:layout_toRightOf="@+id/menuCardImage"
        android:orientation="vertical">

        <TextView
            android:id="@+id/menuCardName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="32sp"
            android:textStyle="bold" />

    </LinearLayout>

</RelativeLayout>
</android.support.v7.widget.CardView>

Edit:
Turns out it was just a display issue in android studio. When I installed the app it worked correctly.

Body:
rather than setting color as background use this drawable to set background.

Create top_strip.xml in drawable folder.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
    <solid android:color="#FFffffff"/>
</shape>

set the radius equal to that of card corner radius and change color as required. It will work


问:
How to get time of page's first paint
While it is easy enough to get firstPaint times from dev tools, is there a way to get the timing from JS?

答:
Yes, this is part of the paint timing API.

You probably want the timing for first-contentful-paint, which you can get using:

```<code>const paintTimings = performance.getEntriesByType('paint');
const fmp = paintTimings.find(({ name }) => name === "first-contentful-paint");
enter code here
console.log(`First contentful paint at ${fmp.startTime}ms`);
</code>```

Title: How to get time of page's first paint

Body:
Yes, this is part of the paint timing API.

You probably want the timing for first-contentful-paint, which you can get using:

const paintTimings = performance.getEntriesByType('paint');
const fmp = paintTimings.find(({ name }) => name === "first-contentful-paint");
enter code here
console.log(`First contentful paint at ${fmp.startTime}ms`);


问:
Limit number of text outputted using Meteor blaze
I have an app that accepts the 1000 minimum character as input, when I want to display it on the screen only about 400 characters should be displayed but I seem not to have found away of how to do this. This helper class returns an object, so via this all the variables can be accessed.

Template helper:

```<code>Template.SchoolDashboardLayout.helpers({
    selected: function () {
    return Session.equals('selectedSchool', this.__originalId) ? 'selected' : '';
}
})
</code>```

This is the frontend using blaze which returns all the 1000 characters but I want to limit the display to only 400 characters, how can I do this?

```<code><span> {{sellschoolvar}} </span>
</code>```

答:
You could register another helper to truncate the string. If you register it as a global helper as below, you can use it elsewhere in your app (but you could just include it in the SchoolDashboardLayout helpers if you like).

```<code>Template.registerHelper("truncate", function(text) {
  return text.substring(0, 400)
});
</code>```

And then your template would change to

```<code><span>{{truncate sellschoolvar}}</span>
</code>```

That's the basic idea - now you can play around with it to change the length of the truncated text, or add "..." to the end, or whatever you like.

See more about global template helpers here

Body:
I have an app that accepts the 1000 minimum character as input, when I want to display it on the screen only about 400 characters should be displayed but I seem not to have found away of how to do this. This helper class returns an object, so via this all the variables can be accessed.

Template helper:

Template.SchoolDashboardLayout.helpers({
    selected: function () {
    return Session.equals('selectedSchool', this.__originalId) ? 'selected' : '';
}
})

This is the frontend using blaze which returns all the 1000 characters but I want to limit the display to only 400 characters, how can I do this?

 {{sellschoolvar}}

Body:
You could register another helper to truncate the string. If you register it as a global helper as below, you can use it elsewhere in your app (but you could just include it in the SchoolDashboardLayout helpers if you like).

Template.registerHelper("truncate", function(text) {
  return text.substring(0, 400)
});

And then your template would change to

<span>{{truncate sellschoolvar}}</span>

That's the basic idea - now you can play around with it to change the length of the truncated text, or add "..." to the end, or whatever you like.

See more about global template helpers here


问:
How can I scroll content under a fixed header while respecting max-height inherit in Internet Explorer 11?
I have a container with a max-height. I'd like to place in it a header and a scrolling body. It's simple in most browsers, but I'm struggling with IE11. Using max-height: inherit;, the .scroll div and its scrollbar extends below its parent (see snippet in IE11)

It's trivial using flexbox instead, but IE11 has a bug that requires changing the display of body to resolve. But I can't do that.

Is there some way to get .scroll to scroll correctly in IE11 without flexbox, and while respecting the max-height functionality on the container?

div {
  border: 1px solid #DDD;
}
.container {
  max-height: 150px;
  overflow: hidden;
}
.header {
  height: 40px;
}
.scroll {
  max-height: inherit;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="container">
    <div class="header">
      header
    </div>
    <div class="scroll">
      <div>scroll</div>
      <div>scroll</div>
      <div>scroll</div>
      <div>scroll</div>
      <div>scroll</div>
      <div>scroll</div>
      <div>scroll</div>
      <div>scroll</div>
      <div>scroll</div>
      <div>scroll</div>
      <div>scroll</div>
    </div>
  </div></code>```

答:
I had exactly the same issue, but after some searching I found that you could add the following styles to your container:

```<code>display: flex; flex-direction: column;
</code>```

And change the max-height style to height.

This seems to work in IE11 as well as all other major browsers, and I didn't have to edit the body at all. Please see this JSFiddle for an example using the code you provided.

I hope this helps!

Body:
I have a container with a max-height. I'd like to place in it a header and a scrolling body. It's simple in most browsers, but I'm struggling with IE11. Using max-height: inherit;, the .scroll div and its scrollbar extends below its parent (see snippet in IE11)

It's trivial using flexbox instead, but IE11 has a bug that requires changing the display of body to resolve. But I can't do that.

Is there some way to get .scroll to scroll correctly in IE11 without flexbox, and while respecting the max-height functionality on the container?

div {
  border: 1px solid #DDD;
}
.container {
  max-height: 150px;
  overflow: hidden;
}
.header {
  height: 40px;
}
.scroll {
  max-height: inherit;
  overflow: auto;
}

      header

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

scroll

Body:
I had exactly the same issue, but after some searching I found that you could add the following styles to your container:

display: flex; flex-direction: column;

And change the max-height style to height.

This seems to work in IE11 as well as all other major browsers, and I didn't have to edit the body at all. Please see this JSFiddle for an example using the code you provided.

I hope this helps!


问:
Java get resource is not working
I try to read a resource file from my application but it doesn't work.

Code:

```<code>String filename = getClass().getClassLoader().getResource("test.xsd").getFile();
System.out.println(filename);
File file = new File(filename);
System.out.println(file.exists());
</code>```

Output when I execute the jar-file:

file:/C:/Users/username/Repo/run/Application.jar!/test.xsd

  false

It works when I run the application from IntelliJ but not when I execute the jar-file. If I open my jar-file with 7-zip test.xsd is located in the root-folder. Why isn't the code working when I execute the jar-file?

答:
Also, File refers to actual OS file-system files; in the OS's file-system, there is only a jar file, and that jar file is not a folder. You should either extract the contents of the URL to a temporary file, or operate with its bytes in-memory or as a stream.

Note that myURL.getFile() is returning a String representation, and not an actual File. In a similar way, this will not work:

```<code> File f = new URL("http://www.example.com/docs/resource1.html").getFile();
 f.exists(); // always false - will not be found in the local filesystem
</code>```

A nice wrapper could be the following:

```<code>public static File openResourceAsTempFile(ClassLoader loader, String resourceName)
       throws IOException {
    Path tmpPath = Files.createTempFile(null, null);
    try (InputStream is = loader.getResourceAsStream(resourceName)) {
        Files.copy(is, tmpPath, StandardCopyOption.REPLACE_EXISTING);
        return tmpPath.toFile();
    } catch (Exception e) {
        if (Files.exists(tmpPath)) Files.delete(tmpPath);
        throw new IOException("Could not create temp file '" + tmpPath
                + "' for resource '" + resourceName + "': " + e, e);
    }
}
</code>```

Title: Java get resource is not working

Body:
I try to read a resource file from my application but it doesn't work.

Code:

String filename = getClass().getClassLoader().getResource("test.xsd").getFile();
System.out.println(filename);
File file = new File(filename);
System.out.println(file.exists());

Output when I execute the jar-file:

file:/C:/Users/username/Repo/run/Application.jar!/test.xsd

  false

It works when I run the application from IntelliJ but not when I execute the jar-file. If I open my jar-file with 7-zip test.xsd is located in the root-folder. Why isn't the code working when I execute the jar-file?

Body:
Also, File refers to actual OS file-system files; in the OS's file-system, there is only a jar file, and that jar file is not a folder. You should either extract the contents of the URL to a temporary file, or operate with its bytes in-memory or as a stream.

Note that myURL.getFile() is returning a String representation, and not an actual File. In a similar way, this will not work:

 File f = new URL("http://www.example.com/docs/resource1.html").getFile();
 f.exists(); // always false - will not be found in the local filesystem

A nice wrapper could be the following:

public static File openResourceAsTempFile(ClassLoader loader, String resourceName)
       throws IOException {
    Path tmpPath = Files.createTempFile(null, null);
    try (InputStream is = loader.getResourceAsStream(resourceName)) {
        Files.copy(is, tmpPath, StandardCopyOption.REPLACE_EXISTING);
        return tmpPath.toFile();
    } catch (Exception e) {
        if (Files.exists(tmpPath)) Files.delete(tmpPath);
        throw new IOException("Could not create temp file '" + tmpPath
                + "' for resource '" + resourceName + "': " + e, e);
    }
}


问:
ActiveModel::MissingAttributeError: can't write unknown attribute `attendee_id`
I am trying to create an association between a User model and an Attendance model in which an attendee_id references a user. The association is a many to many relationship between users and concerts. The join table attendances has two fields
:attendee and :concert.

seed.rb file:

```<code>require 'faker'

Concert.destroy_all
User.destroy_all
Attendance.destroy_all

15.times do
  Concert.create(band: Faker::RockBand.name, venue: "#{Faker::LordOfTheRings.location}", date: Faker::Date.forward(rand(30)), start_time: "8:00 PM")
end

5.times do |number|
  User.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: "#{number}@email.com", password: "password")
end

concerts = Concert.all
users = User.all

15.times do
  Attendance.create(attendee: users.sample, concert: concerts.sample)
end
</code>```

Here are the models:

```<code>class Attendance < ApplicationRecord
  belongs_to :attendee, class_name: "User"
  belongs_to :concert
end
class Concert < ApplicationRecord
  validates :band, :venue, :date, :start_time, presence: true
  has_many :attendances
  has_many :attendees, through: :attendances
end
class User < ApplicationRecord
  validates :first_name, :last_name, :email, presence: true
  validates_format_of :email, with: /@/
  has_secure_password
  has_many :attendances, foreign_key: :attendee_id
  has_many :concerts, through: :attendances
end
</code>```

Here are the migrations:

```<code>class CreateAttendances < ActiveRecord::Migration[5.0]
  def change
    create_table :attendances do |t|
      t.references :attendee
      t.references :concert, index: true

      t.timestamps
    end
  end
end

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.string :password_digest

      t.timestamps
    end
  end
end

class CreateConcerts < ActiveRecord::Migration[5.0]
  def change
    create_table :concerts do |t|
      t.string :band
      t.string :venue
      t.datetime :date
      t.time :start_time

      t.timestamps
    end
  end
end
</code>```

答:
Looks like there are no attendee_id column

bundle exec rails db:reset (same as db:drop + db:create + db:migrate + db:seed)

And for tests bundle exec rails db:test:prepare

If it`s not solve the problem, i think, we need moar stacktraces)

Body:
I am trying to create an association between a User model and an Attendance model in which an attendee_id references a user. The association is a many to many relationship between users and concerts. The join table attendances has two fields
:attendee and :concert.

seed.rb file:

require 'faker'

Concert.destroy_all
User.destroy_all
Attendance.destroy_all

15.times do
  Concert.create(band: Faker::RockBand.name, venue: "#{Faker::LordOfTheRings.location}", date: Faker::Date.forward(rand(30)), start_time: "8:00 PM")
end

5.times do |number|
  User.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: "#{number}@email.com", password: "password")
end

concerts = Concert.all
users = User.all

15.times do
  Attendance.create(attendee: users.sample, concert: concerts.sample)
end

Here are the models:

class Attendance < ApplicationRecord
  belongs_to :attendee, class_name: "User"
  belongs_to :concert
end
class Concert < ApplicationRecord
  validates :band, :venue, :date, :start_time, presence: true
  has_many :attendances
  has_many :attendees, through: :attendances
end
class User < ApplicationRecord
  validates :first_name, :last_name, :email, presence: true
  validates_format_of :email, with: /@/
  has_secure_password
  has_many :attendances, foreign_key: :attendee_id
  has_many :concerts, through: :attendances
end

Here are the migrations:

class CreateAttendances < ActiveRecord::Migration[5.0]
  def change
    create_table :attendances do |t|
      t.references :attendee
      t.references :concert, index: true

      t.timestamps
    end
  end
end

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.string :password_digest

      t.timestamps
    end
  end
end

class CreateConcerts < ActiveRecord::Migration[5.0]
  def change
    create_table :concerts do |t|
      t.string :band
      t.string :venue
      t.datetime :date
      t.time :start_time

      t.timestamps
    end
  end
end


问:
Ruby on Rails: Why a select box does not show the current object value?
Here is the relevant code from views/products/edit.html.erb:

```<code><%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
  <%= render(:partial => "form", :locals => {:f => f}) %>
  <%= submit_tag("Update Product") %>
<% end %>
</code>```

from views/products/_form.html.erb:

```<code><%= select_with_new_option(f, :shop, :name, :id) %>
</code>```

and from helpers/products_helper.rb:

```<code>def select_options_with_create_new(objects, text_field, value_field, options={})
  object = objects.to_s.singularize
  all_objects = object.capitalize.constantize.all
  all_objects = all_objects.sort_by(&options[:order_by]) if options.has_key?(:order_by)
  select_options = all_objects.map{ |obj| [obj.send(text_field), obj.send(value_field)] }
  select_options << [wrap_create_new_option("create new #{object}".titleize), "new_#{object}"]
  options_for_select(select_options)
end

def wrap_create_new_option(str)
  ">> #{str} <<"
end

# By default, sorts by 'text_field'.
def select_with_new_option(f, object, text_field, value_field)
  f.select(:"#{object}_id", select_options_with_create_new(object.pluralize, text_field, value_field, :order_by => text_field))
end
</code>```

I expect the select box to be @product.shop_id by default, but this is not true (the first option is always the default value).

What am I missing ?

答:
I think that, in this case, all you need to do is make sure you set @product in your edit action:

```<code>def edit
  @product = Product.find(params[:id])
end
</code>```

Then change your first line:

```<code><%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
</code>```

to

```<code><%= form_for(@product, :url => {:action => 'update', :id => @product.id}) do |f| %>
</code>```

The first code block will certainly update the proper product, but you'll only see the current values reflected if you generate a form_for @product, with that @product variable set.

Body:
Here is the relevant code from views/products/edit.html.erb:

<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
  <%= render(:partial => "form", :locals => {:f => f}) %>
  <%= submit_tag("Update Product") %>
<% end %>

from views/products/_form.html.erb:

<%= select_with_new_option(f, :shop, :name, :id) %>

and from helpers/products_helper.rb:

def select_options_with_create_new(objects, text_field, value_field, options={})
  object = objects.to_s.singularize
  all_objects = object.capitalize.constantize.all
  all_objects = all_objects.sort_by(&options[:order_by]) if options.has_key?(:order_by)
  select_options = all_objects.map{ |obj| [obj.send(text_field), obj.send(value_field)] }
  select_options << [wrap_create_new_option("create new #{object}".titleize), "new_#{object}"]
  options_for_select(select_options)
end

def wrap_create_new_option(str)
  ">> #{str} <<"
end

# By default, sorts by 'text_field'.
def select_with_new_option(f, object, text_field, value_field)
  f.select(:"#{object}_id", select_options_with_create_new(object.pluralize, text_field, value_field, :order_by => text_field))
end

I expect the select box to be @product.shop_id by default, but this is not true (the first option is always the default value).

What am I missing ?

Body:
I think that, in this case, all you need to do is make sure you set @product in your edit action:

def edit
  @product = Product.find(params[:id])
end

Then change your first line:

<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>

to

<%= form_for(@product, :url => {:action => 'update', :id => @product.id}) do |f| %>

The first code block will certainly update the proper product, but you'll only see the current values reflected if you generate a form_for @product, with that @product variable set.


问:
Android Instant-release build not includes base APK
We are preparing to publish instant app apks to play store via "Instant app development" channel for testing purpose.
When we sign instant app (using same keystore used for Installed App), only geting one feature module apk inside zip folder(instant-release.zip) which giving error while uploading to Play Store by complaining "Your Instant App APKs should contain at least one base APK"

Anyway we able to see the expected structure under instant-debug version

Structure deference between debug and release version as below

instant-debug.zip

hello-debug.apk

base-debug.apk

bye-debug.apk

instant-release.zip

hello-release.apk

And not sure whether we making any mistake on gradle configuration. It will very helpful if anyone can advise on this ?

答: You have to sign all the modules including the baseFeature module separately. Sign all of them by going in their gradle file. I was getting the same error then I signed all the modules and it worked for me.</p>


问:
airflow pass parameter from cli
Is there a way to pass a parameter to:

```<code>airflow trigger_dag dag_name {param}
</code>```

?

I have a script that monitors a directory for files - when a file gets moves into the target directory I want to trigger the dag passing as a parameter the file path.

答:
yes you can. Your Dag should have a Dag and a Bask Task like this:

```<code>from airflow.operators.bash_operators import BashOperator

args = {'start_date':datetime.now(),
        'owner':'airflow',}
dag = DAG(
      dag_id='param_dag',
      default_args=args,
      schedule_interval=None)

bash_task=BashOperator(
     task_id="bash_task"
     bash_command= 'bash ~/path/bashscript.sh {{ dag_run.conf["parameter"] if dag_run else "" }} ',
    //bashscript your script you want to run and the dag_run.conf will hold the parameter you want to pass
     dag=dag)
</code>```

Now on your command line just type the command:

```<code> airflow trigger_dag dag_id --conf '{"parameter":"~/path" }'
</code>```

Title: airflow pass parameter from cli

Body:
Is there a way to pass a parameter to:

airflow trigger_dag dag_name {param}

?

I have a script that monitors a directory for files - when a file gets moves into the target directory I want to trigger the dag passing as a parameter the file path.

Body:
yes you can. Your Dag should have a Dag and a Bask Task like this:

from airflow.operators.bash_operators import BashOperator

args = {'start_date':datetime.now(),
        'owner':'airflow',}
dag = DAG(
      dag_id='param_dag',
      default_args=args,
      schedule_interval=None)

bash_task=BashOperator(
     task_id="bash_task"
     bash_command= 'bash ~/path/bashscript.sh {{ dag_run.conf["parameter"] if dag_run else "" }} ',
    //bashscript your script you want to run and the dag_run.conf will hold the parameter you want to pass
     dag=dag)

Now on your command line just type the command:

 airflow trigger_dag dag_id --conf '{"parameter":"~/path" }'


问:
Spring: migrate XML config to Annotation for util:map
I have the below Spring configuration in an XML file:

```<code><util:map id="myService">
    <entry key="s1" value-ref="goodService" />
    <entry key="s2" value-ref="betterService" />
</util:map>
</code>```

is there a way to migrate this to Annotation based configuration, i.e.

```<code>@Bean
public Map<String, MyService> serviceMap() {
    Map<String, MyService> map = new HashMap<>();
    ...
</code>```

So the values in the Map are references to beans.

答:
In the config class autowire the instances and place the properties to the map</p>

```<code>@Autowired
private GoodService goodService;
@Autowired
private BetterService betterService;

@Bean
public Map<String, MyService> serviceMap() {
    Map<String, MyService> map = new HashMap<>();
    map.put("s1", goodService);
    map.put("s2", betterService);
</code>```

Body:
I have the below Spring configuration in an XML file:

<util:map id="myService">
    <entry key="s1" value-ref="goodService" />
    <entry key="s2" value-ref="betterService" />
</util:map>

is there a way to migrate this to Annotation based configuration, i.e.

@Bean
public Map<String, MyService> serviceMap() {
    Map<String, MyService> map = new HashMap<>();
    ...

So the values in the Map are references to beans.

Body:
In the config class autowire the instances and place the properties to the map

@Autowired
private GoodService goodService;
@Autowired
private BetterService betterService;

@Bean
public Map<String, MyService> serviceMap() {
    Map<String, MyService> map = new HashMap<>();
    map.put("s1", goodService);
    map.put("s2", betterService);


问:
How to count every row from select
I want to extract the data from my table and I want to have this result:

```<code>1 Valore
2 Valore
3 Valore
4 Valore
</code>```

So I want to numeration every ROW from 1 to N.

This is my query but not works:

```<code>  SELECT COUNT(DISTINCT dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) AS Count,
         dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
    FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
         AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
   WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)
</code>```

EDIT

My Database is Tsql

and this is my extract data:

```<code>1 Valore
1 Pippo
1 Pluto
</code>```

Instead of

```<code>1 Valore
2 Pippo
3 Pluto
</code>```

答:
The count does not change per-row; there are the same number of rows every time; what you seem to want is not a count, but a row-number.

To get a row-number, you need to use the ROW_NUMBER API; for example:

```<code>SELECT ROW_NUMBER() OVER (
   ORDER BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) as [Position],
dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) as [Name]
...
ORDER BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)
</code>```

However, unless you are actually partitioning (so getting a row-number per partition), it would be easier to handle this at the receiving client.

Title: How to count every row from select

Body:
I want to extract the data from my table and I want to have this result:

1 Valore
2 Valore
3 Valore
4 Valore

So I want to numeration every ROW from 1 to N.

This is my query but not works:

  SELECT COUNT(DISTINCT dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) AS Count,
         dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
    FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
         AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
   WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)

EDIT

My Database is Tsql

and this is my extract data:

1 Valore
1 Pippo
1 Pluto

Instead of

1 Valore
2 Pippo
3 Pluto

Body:
The count does not change per-row; there are the same number of rows every time; what you seem to want is not a count, but a row-number.

To get a row-number, you need to use the ROW_NUMBER API; for example:

SELECT ROW_NUMBER() OVER (
   ORDER BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) as [Position],
dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) as [Name]
...
ORDER BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)

However, unless you are actually partitioning (so getting a row-number per partition), it would be easier to handle this at the receiving client.


问:
Why does single test fail with "Error XSDB6: Another instance of Derby may have already booted the database"?
I use Spark 1.6.

We have a HDFS write method that wrote to HDFS using SqlContext. Now we needed to switch over to using HiveContext. When we did that existing unit tests do not run and give the error

Error XSDB6: Another instance of Derby may have already booted the database <local path>\metastore_db

This happens whether I run a single test via IntelliJ test runner or via maven on the command line.

As I understand the issue happens when multiple HiveContexts or multiple processes are trying to access the metastore_db. However I am running a single test and no other jobs on my local machine so I fail to understand where the multiple processes are coming from

答:
Figured out why I was getting an error. In the unit test we were writing data to ORC on the local file system and then reading to verify the write was done properly.

The write and read methods were creating their own HiveContexts in the same process which resulted in the lock on the metastore. I am guessing that when it was SqlContext it wasn't a blocker since a local metastore was not needed.

We have now moved to creating the HiveContext when we construct our persistence service. Semantically that makes more sense. This option was chosen over creating and destroying a new SparkContext (and thereby a new HiveContext) for every test since that would add considerable overhead to our test suite without providing much benefit (please do correct me if you have a different opinion)


问:
How to create image and labels using location data stored in NSArray
i have to create an 2images and 3 labels by using code (cgrectmake)and i am having X location, y location, width and height all are stored in arrays(which i have retrieved from the web services)how can i create the image and labels can any one help me</p>

答:
may be this is usefull to you.

```<code>NSString *str;

str = [arrayName objectAtIndex:i(Index NO)];
</code>```

OK by this easily you can access object from the array. any type of object u can fetch this way only reception object type are change in left side.

Best of Luck.

Body:
may be this is usefull to you.

NSString *str;

str = [arrayName objectAtIndex:i(Index NO)];

OK by this easily you can access object from the array. any type of object u can fetch this way only reception object type are change in left side.

Best of Luck.


问:
Docker doesn't work after installed on Ubuntu 14 based on official tutorial
I am using official Ubuntu 14

I am following this official document to install docker.

After install, docker exists on the server, but it just doesn't work.

```<code>docker ps
// or
docker run hello-world
</code>```

All return the same error

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.

I am really new to docker, what is going wrong? How to run docker deamon?

Result of "sudo service docker status" command:

答:
You didn't add your user to dockergroup, then, your user isn't able to user Docker daemon. To fix this, you have two options.

Option 1) Add your user to docker group with the following command:

sudo usermod -aG docker your_user

Option 2) Execute your docker commands using sudo

Be aware that add your user to docker group is equivalent to give full root access to your user. https://www.andreas-jung.com/contents/on-docker-security-docker-group-considered-harmful

Body:
I am using official Ubuntu 14

I am following this official document to install docker.

After install, docker exists on the server, but it just doesn't work.

docker ps
// or
docker run hello-world

All return the same error

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.

I am really new to docker, what is going wrong? How to run docker deamon?

Result of "sudo service docker status" command:


问:
Checking Total Values of Fields = Total Quantity in Form
I am creating a form and have 1 Total Quantity and 3 other separate fields.

I would like to check and prompt when user input is more than the Total Quantity.

Example:

Total Quantity: 10

Site 1: 5

Site 2: 3

Site 3: 1

If the total quantity of Site 1, Site 2 and Site 3 is more than 10, I would like to halt save data or prompt an error.

PS: New to Access 2016 currently, pardon if this is a basic question.

Thank you.

答:
Set form's Before Update event to "[Event Procedure]" and the actual field names inside the brackets [] below.

```<code>Private Sub Form_BeforeUpdate(Cancel As Integer)
    With Me
        If Nz(![Site 1], 0) + Nz(![Site 2], 0) + Nz(![Site 3], 0) > ![Total Quantity] Then
            Cancel = True
            MsgBox "Invalid quantity."
        End If
    End With
End Sub
</code>```

Body:
Set form's Before Update event to "[Event Procedure]" and the actual field names inside the brackets [] below.

Private Sub Form_BeforeUpdate(Cancel As Integer)
    With Me
        If Nz(![Site 1], 0) + Nz(![Site 2], 0) + Nz(![Site 3], 0) > ![Total Quantity] Then
            Cancel = True
            MsgBox "Invalid quantity."
        End If
    End With
End Sub


问:
$scope.myFunc() is not a function
I'm trying to ng-bind $scope.span00, span01, span10, and so on in a grid.

```<code>$scope.span01 = 'test'; // this works fine
</code>```

Now for the ng-click...

```<code>$scope.clickedOn = function(row, column) {

  var gridLocation = function() { return 'span'.concat(row).concat(column); } // returns span01
  $scope.gridLocation() = 'test'; // says $scope.gridLocation() is not a function.
}
</code>```

It's saying it's not a function. What do I do here?

答:
Because the function does not exist on $scope. This is what you need to do:

```<code>$scope.gridLocation = function (row, column) {
    return 'span'.concat(row).concat(column);
};

$scope.clickedOn = function (row, column) {
    $scope.gridLocation(row, column);
};
</code>```

Edit

To do what you asked for in the comments (I hope I understood correctly):

```<code>$scope.clickedOn = function (row, column) {
    $scope[$scope.gridLocation(row, column)] = 'test';
};
</code>```

Title: $scope.myFunc() is not a function

Body:
I'm trying to ng-bind $scope.span00, span01, span10, and so on in a grid.

$scope.span01 = 'test'; // this works fine

Now for the ng-click...

$scope.clickedOn = function(row, column) {

  var gridLocation = function() { return 'span'.concat(row).concat(column); } // returns span01
  $scope.gridLocation() = 'test'; // says $scope.gridLocation() is not a function.
}

It's saying it's not a function. What do I do here?

Body:
Because the function does not exist on $scope. This is what you need to do:

$scope.gridLocation = function (row, column) {
    return 'span'.concat(row).concat(column);
};

$scope.clickedOn = function (row, column) {
    $scope.gridLocation(row, column);
};

Edit

To do what you asked for in the comments (I hope I understood correctly):

$scope.clickedOn = function (row, column) {
    $scope[$scope.gridLocation(row, column)] = 'test';
};


问:
how to get creation date from object id in mongoose?
I understand from ObjectId — MongoDB Manual that the first 4 bytes of any mongodb object id is the creation timestamp.

Any well supported way of extracting that information from mongoose?

答:
```<code>_id.getTimestamp()
</code>```

doesn't work for me but

```<code>_id.Time()
</code>```

works perfect

Body:
_id.getTimestamp()

doesn't work for me but

_id.Time()

works perfect


问:
How to read text file from File object in java
I have this code which load the File from class path
a=its text file and i want to read it to string
what im using is :

```<code> File file = new File(classLoader.getResource("sample.json").getFile());
</code>```

i don't want to use:

```<code>file.getAbsolutePath();
</code>```

how can i read this text file into String ?

UPDATE
i found the solution , what do you think?

```<code> ClassLoader classLoader = getClass().getClassLoader();
is = classLoader.getResourceAsStream("sample.json");
String txt = IOUtils.toString(is);
</code>```

答:
If you're using Java 8, you can use this for reading lines from a file:

```<code>List<String> lines = Files.readallLines(file.toPath());
</code>```

Refer to the docs below:

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-

https://docs.oracle.com/javase/8/docs/api/java/io/File.html#toPath--

EDIT:

For reading from a resource you got as an inputstream, you can use a combination of BufferedReader and InputStreamReader:

```<code>String getText() throws IOException{
    StringBuilder txt = new StringBuilder();
    InputStream res = getClass().getClassLoader().getResourceAsStream("sample.json");
    try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) {
        String sCurrentLine;
        while ((sCurrentLine = br.readLine()) != null) {
            txt.append(sCurrentLine + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return txt.toString();
}
</code>```

Hope this helps!

Body:
I have this code which load the File from class path
a=its text file and i want to read it to string
what im using is :

 File file = new File(classLoader.getResource("sample.json").getFile());

i don't want to use:

file.getAbsolutePath();

how can i read this text file into String ?

UPDATE
i found the solution , what do you think?

 ClassLoader classLoader = getClass().getClassLoader();
is = classLoader.getResourceAsStream("sample.json");
String txt = IOUtils.toString(is);

Body:
If you're using Java 8, you can use this for reading lines from a file:

List<String> lines = Files.readallLines(file.toPath());

Refer to the docs below:

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-

https://docs.oracle.com/javase/8/docs/api/java/io/File.html#toPath--

EDIT:

For reading from a resource you got as an inputstream, you can use a combination of BufferedReader and InputStreamReader:

String getText() throws IOException{
    StringBuilder txt = new StringBuilder();
    InputStream res = getClass().getClassLoader().getResourceAsStream("sample.json");
    try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) {
        String sCurrentLine;
        while ((sCurrentLine = br.readLine()) != null) {
            txt.append(sCurrentLine + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return txt.toString();
}

Hope this helps!