问:
Add column to SQL Server database when year changes
I am developing a small project as an hobby and came to a dead end. I am using Visual Studio and SQL Server Management Studio.

I use Entity Framework model to be able to add data entries to a table with 4 columns. Two of those are supposed to log data entry taking place in 2017 like this:

```<code>if (CheckBoxBulb.Checked == true)
{
    string roomNo = "";
    roomNo = DropDownList1.SelectedValue.ToString();
    testtable2017 entry = new testtable2017();

    SqlConnection dataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["iPadLoanConnectionString2"].ToString());

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "UPDATE testtable2017 SET Last_Bulb_Replaced_2017 = '" + Calendar1.SelectedDate.ToString() + "' WHERE Room_No ='" + roomNo + "'";

    cmd.Connection = dataConnection;

    dataConnection.Open();
    cmd.ExecuteNonQuery();
    dataConnection.Close();

    iPadEntities db = new iPadEntities();
    db.testtable2017.Add(entry);
    db.SaveChanges();
}
else if(CheckBoxFilter.Checked == true)
{
    string roomNo = "";
    roomNo = DropDownList1.SelectedValue.ToString();

    testtable2017 entry = new testtable2017();

    SqlConnection dataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["iPadLoanConnectionString2"].ToString());

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "UPDATE testtable2017 SET Last_Cleaned_Filter_2017 = '" + Calendar1.SelectedDate.ToString() + "' WHERE Room_No ='" +roomNo +"'";

    cmd.Connection = dataConnection;

    dataConnection.Open();
    cmd.ExecuteNonQuery();
    dataConnection.Close();

    iPadEntities db = new iPadEntities();
    db.testtable2017.Add(entry);
    db.SaveChanges();
}
</code>```

So far so good and it is working perfectly but lets say that when the year changes to 2018 I want to create two more columns that will hold all the data logged within 2018. Is there any way of achieving that and if so how could I also manipulate the code in C# to then start save any data entries to the newly created columns?

Thank you

答:
I agree with all the people who say this is a bad design and a horrible idea.

However, treating your question as academic, you could simply add some logic to your program to check what year it is today, and query the database to see if the column exists with the year in the name.

If the column doesn't exist, then run an ALTER TABLE statement to add it before proceeding with the rest of the script.   You would also need to use the Year today to build your UPDATE query instead of hard-coding "2017" in it.

Body:
I am developing a small project as an hobby and came to a dead end. I am using Visual Studio and SQL Server Management Studio.

I use Entity Framework model to be able to add data entries to a table with 4 columns. Two of those are supposed to log data entry taking place in 2017 like this:

if (CheckBoxBulb.Checked == true)
{
    string roomNo = "";
    roomNo = DropDownList1.SelectedValue.ToString();
    testtable2017 entry = new testtable2017();

    SqlConnection dataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["iPadLoanConnectionString2"].ToString());

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "UPDATE testtable2017 SET Last_Bulb_Replaced_2017 = '" + Calendar1.SelectedDate.ToString() + "' WHERE Room_No ='" + roomNo + "'";

    cmd.Connection = dataConnection;

    dataConnection.Open();
    cmd.ExecuteNonQuery();
    dataConnection.Close();

    iPadEntities db = new iPadEntities();
    db.testtable2017.Add(entry);
    db.SaveChanges();
}
else if(CheckBoxFilter.Checked == true)
{
    string roomNo = "";
    roomNo = DropDownList1.SelectedValue.ToString();

    testtable2017 entry = new testtable2017();

    SqlConnection dataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["iPadLoanConnectionString2"].ToString());

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "UPDATE testtable2017 SET Last_Cleaned_Filter_2017 = '" + Calendar1.SelectedDate.ToString() + "' WHERE Room_No ='" +roomNo +"'";

    cmd.Connection = dataConnection;

    dataConnection.Open();
    cmd.ExecuteNonQuery();
    dataConnection.Close();

    iPadEntities db = new iPadEntities();
    db.testtable2017.Add(entry);
    db.SaveChanges();
}

So far so good and it is working perfectly but lets say that when the year changes to 2018 I want to create two more columns that will hold all the data logged within 2018. Is there any way of achieving that and if so how could I also manipulate the code in C# to then start save any data entries to the newly created columns?

Thank you


来源: stackexchange

问:
How to avoid the 40 character maximum, when reading a filename from a Weblogic server?
I am trying to read the name of some files from a weblogic server.

```<code>dir.eachFileRecurse(FileType.FILES) { file ->
  println file.getName()
}
</code>```

However the base filename must be too long, since it's cutted of when i print the file.getName(). Looking at the deployed jar, I have the file

OnlineOfflineSomethingknowledgement-2.DDD

The result of the print however is

OnlineOfflineSomethingknowledgement-2.D

It's like 40 characters is the maximum length of the filename.

Looking at the SB-console, and look at the list of files. The 40 character maximum is also present in the web view. Hovering the mouse over the filename though, will show the full name of the file.

Is there a way to get the full file name from the code?

答:
not clear of the environment of your script execution.

normally, there is no such limitation.

try to print the class of your dir and file variables and probably this will give you an answer.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to read the name of some files from a weblogic server.

dir.eachFileRecurse(FileType.FILES) { file ->
  println file.getName()
}

However the base filename must be too long, since it's cutted of when i print the file.getName(). Looking at the deployed jar, I have the file

OnlineOfflineSomethingknowledgement-2.DDD

The result of the print however is

OnlineOfflineSomethingknowledgement-2.D

It's like 40 characters is the maximum length of the filename.

Looking at the SB-console, and look at the list of files. The 40 character maximum is also present in the web view. Hovering the mouse over the filename though, will show the full name of the file.

Is there a way to get the full file name from the code?


问:
Table A drops rows in table B in SQL JOIN
I have two tables which I need joined. I have two select statements with the same columns except OrderValue and SalesTarget:

```<code>SELECT
    b.TrnYear, b.TrnMonth, b.Branch, b.Salesperson, b.OrderValue
FROM
    dbo.vw_jab_Consolidated_Orders as b
INNER JOIN
    dbo.vw_jab_SalTargets as a ON a.Sequence2 = b.Salesperson
WHERE
    b.TrnYear = '2017'
ORDER BY
    a.TrnMonth

SELECT
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget
FROM
    dbo.vw_jab_SalTargets as a
WHERE
    a.TrnYear = '2017' AND a.SequenceType = 'BR'
GROUP BY
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget
</code>```

My problem is that as there are months where there are no OrderValues, the SalesTarget value is being filtered out when I join the two tables as follows:

```<code>SELECT
    a.TrnYear, SUM(a.SalesTarget) as SalesTarget, SUM(b.InvoicedSales) AS InvoicedSales
FROM
    (SELECT
         TrnYear, SUM(SalesTarget) AS SalesTarget
     FROM
         dbo.vw_jab_SalTargets
     WHERE
         (SequenceType = 'BR')
     GROUP BY
         SequenceType, TrnYear) AS A
LEFT JOIN
    (SELECT
         TrnYear, SUM(ActualSales) AS InvoicedSales
     FROM
         dbo.vw_jab_Consolidated_Sales
     GROUP BY
         TrnYear) AS b ON a.TrnYear = b.TrnYear
WHERE
    a.TrnYear = '2017'
GROUP BY
    a.TrnYear
</code>```

答:
You want a right outer join, instead of an inner join. For a right outer join, all columns of the right table are kept even if there is not a matching value in the left table.

Try this:

```<code> SELECT        a.TrnYear, a.TrnMonth, SUM(a.SalesTarget) as SalesTarget, SUM(b.InvoicedSales) AS InvoicedSales
    FROM            (SELECT        TrnYear, TrnMonth, SUM(SalesTarget) AS SalesTarget
                              FROM            dbo.vw_jab_SalTargets
                              WHERE        (SequenceType = 'BR')
                              GROUP BY SequenceType, TrnYear, TrnMonth) AS a RIGHT OUTER JOIN
                                 (SELECT        TrnYear, TrnMonth, SUM(ActualSales) AS InvoicedSales
                                   FROM            dbo.vw_jab_Consolidated_Sales
                                   GROUP BY TrnYear, TrnMonth) AS b ON a.TrnYear = b.TrnYear and a.TrnMonth=b.TrnMonth
                                   WHERE a.TrnYear = '2017'
    GROUP BY a.TrnYear, a.TrnMonth
    ORDER BY TrnMonth
</code>```

Body:
I have two tables which I need joined. I have two select statements with the same columns except OrderValue and SalesTarget:

SELECT
    b.TrnYear, b.TrnMonth, b.Branch, b.Salesperson, b.OrderValue
FROM
    dbo.vw_jab_Consolidated_Orders as b
INNER JOIN
    dbo.vw_jab_SalTargets as a ON a.Sequence2 = b.Salesperson
WHERE
    b.TrnYear = '2017'
ORDER BY
    a.TrnMonth

SELECT
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget
FROM
    dbo.vw_jab_SalTargets as a
WHERE
    a.TrnYear = '2017' AND a.SequenceType = 'BR'
GROUP BY
    a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget

My problem is that as there are months where there are no OrderValues, the SalesTarget value is being filtered out when I join the two tables as follows:

SELECT
    a.TrnYear, SUM(a.SalesTarget) as SalesTarget, SUM(b.InvoicedSales) AS InvoicedSales
FROM
    (SELECT
         TrnYear, SUM(SalesTarget) AS SalesTarget
     FROM
         dbo.vw_jab_SalTargets
     WHERE
         (SequenceType = 'BR')
     GROUP BY
         SequenceType, TrnYear) AS A
LEFT JOIN
    (SELECT
         TrnYear, SUM(ActualSales) AS InvoicedSales
     FROM
         dbo.vw_jab_Consolidated_Sales
     GROUP BY
         TrnYear) AS b ON a.TrnYear = b.TrnYear
WHERE
    a.TrnYear = '2017'
GROUP BY
    a.TrnYear

Body:
You want a right outer join, instead of an inner join. For a right outer join, all columns of the right table are kept even if there is not a matching value in the left table.

Try this:

 SELECT        a.TrnYear, a.TrnMonth, SUM(a.SalesTarget) as SalesTarget, SUM(b.InvoicedSales) AS InvoicedSales
    FROM            (SELECT        TrnYear, TrnMonth, SUM(SalesTarget) AS SalesTarget
                              FROM            dbo.vw_jab_SalTargets
                              WHERE        (SequenceType = 'BR')
                              GROUP BY SequenceType, TrnYear, TrnMonth) AS a RIGHT OUTER JOIN
                                 (SELECT        TrnYear, TrnMonth, SUM(ActualSales) AS InvoicedSales
                                   FROM            dbo.vw_jab_Consolidated_Sales
                                   GROUP BY TrnYear, TrnMonth) AS b ON a.TrnYear = b.TrnYear and a.TrnMonth=b.TrnMonth
                                   WHERE a.TrnYear = '2017'
    GROUP BY a.TrnYear, a.TrnMonth
    ORDER BY TrnMonth


问:
Discount for particular customer group in magento
I met with a requirement for my magento project, according this I need to provide special discount to specific customer group on their purchase. This discount must be shown in customer account,if they belong to that particular group, and when user want to use that particular discount, price of that item must be discounted according to that discount offer to them.

I know how to create a customer group, but how can I give them desired discount and make it show at time of purchase. so that customer can use it.

please suggest me any method or refer any document.

Thanks!

答:
Since you want a discount to show "at time of purchase", use a Shopping Cart Price Rule from the Promotions menu. It can be restricted to certain customer groups.

A customer's group can be set by editing their account from Customers > Manage Customers menu, then look in Account Information for the Customer Group control.

The links I gave are both from the Magento User Guide. Please read it all.

http://www.magentocommerce.com/wiki/welcome_to_the_magento_user_s_guide/welcome_to_the_magento_user_s_guide

ContentLicense: CC BY-SA 2.5


问:
How do I block comment in Jupyter notebook?
I want to comment out a block of multiple lines in Jupyter  Notebook, but can't find out how to do that in this current version.

It used to be in one of the drop down menus but is no longer there.

How do you comment out multi-line blocks of code at once?

This is not a duplicate because the solution given in the following link doesn't seem to work anymore:

How can I block comment code in the IPython notebook?

Ctrl + / does nothing.

答: Another thing to add, in the version I'm using, the code has to be initialized in order to be to comment it out using CTRL and / . If you haven't ran the code and the code isn't colorized it wont work. </p>

ContentLicense: CC BY-SA 4.0


问:
Python text file append error
So I was presented with making a program that uses a text file to store passwords to not forget them. The text file is below.(Passwords.txt)

```<code>    'Application1': ['Username1', 'Password1']
    'Application2': ['Username2', 'Password2']
</code>```

So, to this I would like to add a new line which would be:
'Application3': ['Username3','Password3']
However when I run the following code it tells me an error saying str is not callable. (passwordsappend.py)

```<code>    hp = open("Passwords.txt","a") #open the file

    key = raw_input("Which app: ")
    usr = raw_input("Username: ")
    psw = raw_input("Password: ") #make variables to add

    hp.write('\n\''(key)'\': ''[\''(usr)'\', ' '\''(psw)'\'],') #make it so that it's like the rest of the file

    hp.close() #close the file
</code>```

I was trying to study python codes to learn how to, but I can't see the problem... Can anyone give me advice?

答:
As said in a different answer the problem is your string handling when writing to the file. I would recommend to use string formatting:

```<code>hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))
</code>```

See https://pyformat.info/

Recommended code:

```<code># Ask for variables to add
key = raw_input("Which app: ")
usr = raw_input("Username: ")
psw = raw_input("Password: ")

# Open file
with open("Passwords.txt", "a") as hp:
    # Add line with same format as the rest of lines
    hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))
</code>```

If you use the with open(...) as ...: you don't have to call the close method, it's called automatically when you exit the with's scope.

Title: Python text file append error

Body:
So I was presented with making a program that uses a text file to store passwords to not forget them. The text file is below.(Passwords.txt)

    'Application1': ['Username1', 'Password1']
    'Application2': ['Username2', 'Password2']

So, to this I would like to add a new line which would be:
'Application3': ['Username3','Password3']
However when I run the following code it tells me an error saying str is not callable. (passwordsappend.py)

    hp = open("Passwords.txt","a") #open the file

    key = raw_input("Which app: ")
    usr = raw_input("Username: ")
    psw = raw_input("Password: ") #make variables to add

    hp.write('\n\''(key)'\': ''[\''(usr)'\', ' '\''(psw)'\'],') #make it so that it's like the rest of the file

    hp.close() #close the file

I was trying to study python codes to learn how to, but I can't see the problem... Can anyone give me advice?

Body:
As said in a different answer the problem is your string handling when writing to the file. I would recommend to use string formatting:

hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))

See https://pyformat.info/

Recommended code:

# Ask for variables to add
key = raw_input("Which app: ")
usr = raw_input("Username: ")
psw = raw_input("Password: ")

# Open file
with open("Passwords.txt", "a") as hp:
    # Add line with same format as the rest of lines
    hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))

If you use the with open(...) as ...: you don't have to call the close method, it's called automatically when you exit the with's scope.


问:
Talend importing library
I am using Talend 6.2.1 and i have downloaded the json-schema-validation.zip, tried importing it under Window->Preferences->Java->Build Path->User Libraries, but this does not seem to give me access to the library.</p>

答:
It is better to Use the tLibraryLoad component to load a lib file in a job.

Here you can easily load external library from your local file system..

Title: Talend importing library


问:
How to configure ActiveMQ to assign an 'anonymous' user and role to non-authenticated users
I wish to set up a ActiveMQ instance (primarily as a STOMP server) which will service requests from two types of clients:

authenticated users which can read and write to topics

non-authenticated users which can only read from topics

I have been using the SimpleAuthenticationBroker so far and I cannot see anyway to configure the above situation, nor do I see any bit in the code which recognises a wildcard for a user to pass authentication.

If I configure the server to use the authentication broker, it will expect ALL connections to authenticate, which is what I don't want.

The only solution I think I can see is to provide my own implementation to support the functionality I require, but I would love to find some way built into the server.

答: This feature is now available as of ActiveMQ 5.4, as I've just found when searching for the same functionality: http://activemq.apache.org/security.html</p>

OwnerDisplayName: magicbadger


问:
How to read space seperated file which contains spaces in column also using pandas?
I want to read one space separated file using python pandas. This file's first column contains some spaces so I'm not able to read this file successfully.

Input File Data-

```<code>       Jan1 Jan2 Jan3 Jan4 Jan5 total
A BC    1    2    4    4    5    16
PQ R    1    2    3    4    5    15
X Y Z    2    2    2    2    2    10
</code>```

I'm tried to read it using below code -

```<code>df = pd.read_csv("text2.txt", sep = r"\s+",engine='python')
df.to_csv("out.csv",index=None)
</code>```

I also tried to use -

delim_whitespace=True

I want to generate csv file from this file which looks like below -

```<code>names,Jan1,Jan2,Jan3,Jan4,Jan5,total
A BC,1,2,4,4,5,16
PQ R,1,2,3,4,5,15
X Y Z,2,2,2,2,2,10
</code>```

Is I'm missing some p

答:
You will have to parse it semi-manually

```<code>def read_funny_csv(filehandle):
    columns = None
    index = list()
    data = list()

    split_pattern = re.compile('\s+')

    num_columns = None
    for line in filehandle:
        parts = split_pattern.split(line.strip())
        if num_columns is None:
            num_columns = len(parts)
            columns = parts
            continue
        index.append(' '.join(parts[:-num_columns]))
        data.append(parts[-num_columns:])
    return columns, index, data
</code>```

calling this

```<code>with open("text2.txt", 'r') as filehandle:
    columns, index, data = read_funny_csv(filehandle)

df = pd.DataFrame(index=index, data=data, columns=columns)
</code>```

You will have to specify the dtypes yourself.

If you want to make pandas make a stab at it itself you could export this to a decently delimited csv, and reload it

Body:
I want to read one space separated file using python pandas. This file's first column contains some spaces so I'm not able to read this file successfully.

Input File Data-

       Jan1 Jan2 Jan3 Jan4 Jan5 total
A BC    1    2    4    4    5    16
PQ R    1    2    3    4    5    15
X Y Z    2    2    2    2    2    10

I'm tried to read it using below code -

df = pd.read_csv("text2.txt", sep = r"\s+",engine='python')
df.to_csv("out.csv",index=None)

I also tried to use -

delim_whitespace=True

I want to generate csv file from this file which looks like below -

names,Jan1,Jan2,Jan3,Jan4,Jan5,total
A BC,1,2,4,4,5,16
PQ R,1,2,3,4,5,15
X Y Z,2,2,2,2,2,10

Is I'm missing some p

Body:
You will have to parse it semi-manually

def read_funny_csv(filehandle):
    columns = None
    index = list()
    data = list()

    split_pattern = re.compile('\s+')

    num_columns = None
    for line in filehandle:
        parts = split_pattern.split(line.strip())
        if num_columns is None:
            num_columns = len(parts)
            columns = parts
            continue
        index.append(' '.join(parts[:-num_columns]))
        data.append(parts[-num_columns:])
    return columns, index, data

calling this

with open("text2.txt", 'r') as filehandle:
    columns, index, data = read_funny_csv(filehandle)

df = pd.DataFrame(index=index, data=data, columns=columns)

You will have to specify the dtypes yourself.

If you want to make pandas make a stab at it itself you could export this to a decently delimited csv, and reload it


问:
Unit testing rendering context. Page context throws an exception
I am trying to create unit test using sitecoreFakeDB my code displays below:

```<code>using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db() { new Sitecore.FakeDb.DbItem("source") })
        {
            var contextItem = db.GetItem("/sitecore/content/source");
            var args = new Sitecore.Pipelines.PipelineArgs();
            using (RenderingContext.EnterContext(new Rendering(), contextItem))
            {

                var processor = new Mock<Sitecore.FakeDb.Pipelines.IPipelineProcessor>();

                db.PipelineWatcher.Register("mypipeline", processor.Object);

                Sitecore.Pipelines.CorePipeline.Run("mypipeline", args);

                Xunit.Assert.NotNull(args.Current));
            }
        }
</code>```

upon checking the pagecontext in the RenderingContext.Current it throws an exception. How can I have a value for the pagecontext?

答:
It seems there is no PageContext.EnterContext method similar to the one used for entering the rendering context. You may set it manually via the ContextService static class (but beware the possible garbage if you won't clean it up properly):

```<code>ContextService.Get().Push(new PageContext());
var currentContext = RenderingContext.Current;
Assert.NotNull(currentContext.PageContext); // pass
</code>```

Body:
I am trying to create unit test using sitecoreFakeDB my code displays below:

using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db() { new Sitecore.FakeDb.DbItem("source") })
        {
            var contextItem = db.GetItem("/sitecore/content/source");
            var args = new Sitecore.Pipelines.PipelineArgs();
            using (RenderingContext.EnterContext(new Rendering(), contextItem))
            {

                var processor = new Mock<Sitecore.FakeDb.Pipelines.IPipelineProcessor>();

                db.PipelineWatcher.Register("mypipeline", processor.Object);

                Sitecore.Pipelines.CorePipeline.Run("mypipeline", args);

                Xunit.Assert.NotNull(args.Current));
            }
        }

upon checking the pagecontext in the RenderingContext.Current it throws an exception. How can I have a value for the pagecontext?

Body:
It seems there is no PageContext.EnterContext method similar to the one used for entering the rendering context. You may set it manually via the ContextService static class (but beware the possible garbage if you won't clean it up properly):

ContextService.Get().Push(new PageContext());
var currentContext = RenderingContext.Current;
Assert.NotNull(currentContext.PageContext); // pass


问:
com.sun.jdi.InvocationException occurred invoking method
I just want to create an object of class, but got this error when debugging. Can anybody tell me what the problem is? The location of this code is in some Spring(2.5) Service class.

There is a similar problem: OJB Reference Descriptor 1:0 relationship? Should I set auto-retrieve to false?

Thanks a lot~

答: I got similar exception in Eclipse. This was due to  java.lang.StackOverflowError error. I had overriden toString() method in child class, having JoinColumn, which was returning string using object of parentclass, resulting in circular dependency. Try to remove that object from toString(), and it will work.


问:
How can i generate child model in mongoose
I'm trying to model the following.

I have a parent model that is called Brick that has some attributes.
There will be 5+ type of bricks that will all have their own specific attributes wich are needed also.

I want to be able to select all Bricks of a certain custumer id later, whatever the type (TwitterBrick, facebookBrick et cetera)  is.

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('Brick', new Schema({
    type: String,
    userid: { type: String, required: true},
    animationspeed: { type: Number, min: 1, max: 100 },
    socialsite: String,     // none, twitter, instagram
    socialsearchtags: String,
    tagline: { type: String, minlength:3,maxlength: 25 },

}));
</code>```

An example for a child is TwitterBrick.
for now it is:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('TwitterBrick', new Schema({
    bgColor1: String,
    bgColor2: String,
    bannerBgColor1: String,
    bannerBgColor2: String,
}));
</code>```

TwitterBrick should inherit the attributes of Brick , but i don't know how..
Can you help me in the right direction?

Thanks!
Steven

答:
My solution was to set a new "content" field in brickSchema, and split in different files:

brick.schema.js

```<code>var mongoose = require('mongoose');

    module.exports = {
          type: String,
          userid: { type: String, required: true},
          animationspeed: { type: Number, min: 1, max: 100 },
          socialsite: String,     // none, twitter, instagram
          socialsearchtags: String,
          tagline: { type: String, minlength:3,maxlength: 25 },
          content: {type:mongoose.Schema.Types.Mixed, required: false, default: null}
    }
</code>```

brick.model.js

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BrickSchema = new Schema(require('brick.schema.js'));
module.exports = mongoose.model('defaultBrick', BrickSchema, 'Bricks');
</code>```

twitterBrick.model.js

```<code>  var mongoose = require('mongoose');
  var Schema = mongoose.Schema;
  var brickSchema = require('brick.schema.js');

  brickSchema.content = new Schema({
  bgColor1: String,
  bgColor2: String,
  bannerBgColor1: String,
  bannerBgColor2: String,
});

var BrickSchema = new Schema(require('brick.schema.js'));
module.exports = mongoose.model('twitterBrick', BrickSchema, 'Bricks');
</code>```

Hope it helps !

Body:
I'm trying to model the following.

I have a parent model that is called Brick that has some attributes.
There will be 5+ type of bricks that will all have their own specific attributes wich are needed also.

I want to be able to select all Bricks of a certain custumer id later, whatever the type (TwitterBrick, facebookBrick et cetera)  is.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('Brick', new Schema({
    type: String,
    userid: { type: String, required: true},
    animationspeed: { type: Number, min: 1, max: 100 },
    socialsite: String,     // none, twitter, instagram
    socialsearchtags: String,
    tagline: { type: String, minlength:3,maxlength: 25 },

}));

An example for a child is TwitterBrick.
for now it is:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('TwitterBrick', new Schema({
    bgColor1: String,
    bgColor2: String,
    bannerBgColor1: String,
    bannerBgColor2: String,
}));

TwitterBrick should inherit the attributes of Brick , but i don't know how..
Can you help me in the right direction?

Thanks!
Steven

Body:
My solution was to set a new "content" field in brickSchema, and split in different files:

brick.schema.js

var mongoose = require('mongoose');

    module.exports = {
          type: String,
          userid: { type: String, required: true},
          animationspeed: { type: Number, min: 1, max: 100 },
          socialsite: String,     // none, twitter, instagram
          socialsearchtags: String,
          tagline: { type: String, minlength:3,maxlength: 25 },
          content: {type:mongoose.Schema.Types.Mixed, required: false, default: null}
    }

brick.model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BrickSchema = new Schema(require('brick.schema.js'));
module.exports = mongoose.model('defaultBrick', BrickSchema, 'Bricks');

twitterBrick.model.js

  var mongoose = require('mongoose');
  var Schema = mongoose.Schema;
  var brickSchema = require('brick.schema.js');

  brickSchema.content = new Schema({
  bgColor1: String,
  bgColor2: String,
  bannerBgColor1: String,
  bannerBgColor2: String,
});

var BrickSchema = new Schema(require('brick.schema.js'));
module.exports = mongoose.model('twitterBrick', BrickSchema, 'Bricks');

Hope it helps !


问:
How to pass long number through javascript?
I want to convert numberLong date from the mongo db database into dd/mm/yyyy format in javascript.

When I put direct hardcoded value like the following code, it gives me correct result:

```<code>function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));
</code>```

Here is my code :

```<code>for(var i=0;i<keys;i++)
                {
                var tr="<tr>";
                tr+= "<td><input type='checkbox' name='record'></td>"
                tr+="<td>"+positionList[i]["fromDate"]+"</td>";
                var j = (positionList[i]["fromDate"]);
                console.log("value of j is =========="+j);
                console.log(getDateIfDate("/Date(j)/")); // actual conversion should happen here
}
</code>```

What changes I should make in my code to get the date in required format?

答:
You should invoke function like this  getDateIfDate("/Date("+j+")/");

instead of getDateIfDate("/Date(j)/") this means you are passing string "/Date(j)/".

function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

var j= 1460008501597;

console.log(getDateIfDate("/Date("+j+")/"));```

Body:
I want to convert numberLong date from the mongo db database into dd/mm/yyyy format in javascript.

When I put direct hardcoded value like the following code, it gives me correct result:

function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));

Here is my code :

for(var i=0;i<keys;i++)
                {
                var tr="
";
                tr+= "<input type='checkbox' name='record'>	"
                tr+=""+positionList[i]["fromDate"]+"	";
                var j = (positionList[i]["fromDate"]);
                console.log("value of j is =========="+j);
                console.log(getDateIfDate("/Date(j)/")); // actual conversion should happen here
}

What changes I should make in my code to get the date in required format?


问:
Change the version of ruby
I want to change the version of ruby. I'm in a virtual machine.
The current version of ruby is:

```<code>ruby -v :ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-linux]
gem -v :2.4.3
</code>```

and I want to move to version 2.2.6.

答:
If you're using Rbenv :
https://makandracards.com/makandra/21545-rbenv-how-to-switch-to-another-ruby-version-temporarily-per-project-or-globally

If you're using RVM :
https://rvm.io/rubies/default

If you're not using any of these: you should be using one of these.

Title: Change the version of ruby

Body:
I want to change the version of ruby. I'm in a virtual machine.
The current version of ruby is:

ruby -v :ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-linux]
gem -v :2.4.3

and I want to move to version 2.2.6.


问:
How to parse String data from xml dom parser?
I am using XMLparser WS.so I get below kind of data in response.

```<code> <?xml version="1.0" encoding="utf-8"?>
 <string xmlns="http://tempuri.org/">

     {"DBVersionList":[]}

 </string>
</code>```

I want to parse above data and need only {"DBVersionList":[]} this as value.

I tried as below code.

```<code>    Document doc = xmlparser.getDomElement(response); // getting DOM
    NodeList n2 = doc.getElementsByTagName("string");
    Log.e("Log","value="+n2.item(0));
</code>```

Thanks in Advance

答:
Finally, I got an answer of my question.</p>

```<code>    Document doc = xmlparser.getDomElement(response);
    Element element=doc.getDocumentElement();
    element.normalize();
    Log.e("Log","Value="+element.getTextContent());
</code>```

Body:
I am using XMLparser WS.so I get below kind of data in response.

 <?xml version="1.0" encoding="utf-8"?>
 <string xmlns="http://tempuri.org/">

     {"DBVersionList":[]}

 </string>

I want to parse above data and need only {"DBVersionList":[]} this as value.

I tried as below code.

    Document doc = xmlparser.getDomElement(response); // getting DOM
    NodeList n2 = doc.getElementsByTagName("string");
    Log.e("Log","value="+n2.item(0));

Thanks in Advance

Body:
Finally, I got an answer of my question.

    Document doc = xmlparser.getDomElement(response);
    Element element=doc.getDocumentElement();
    element.normalize();
    Log.e("Log","Value="+element.getTextContent());


问:
Creating an extension method in C#
I'm trying to create an extension method in C# for the HtmlHelper class. I've read the MSDN page for it, and I'm sure I'm referencing the correct namespaces. I wonder what I could be doing wrong.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; //Correctly referencing the necessary namespaces, right?

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            CategoryRepository categoryRepo = new CategoryRepository();
            var categories = categoryRepo.FindAllCategories();

            foreach (Category c in categories)
            {
                helper.RouteLink(blablabla); //Construct links and return them.
            }

            //helper.RouteLink doesn't show up! C# wipeouuuuuttttt.
            //It's as if 'helper' doesn't have the RouteLink method there.
        }
    }
}
</code>```

First time that this happens to me when programming in C#. Anyone else encounter this problem?

答: You need to reference System.Web.Mvc for the HtmlHelper, but the extension is in System.Web.Mvc.Html.

OwnerDisplayName: delete

Title: Creating an extension method in C#

Body:
I'm trying to create an extension method in C# for the HtmlHelper class. I've read the MSDN page for it, and I'm sure I'm referencing the correct namespaces. I wonder what I could be doing wrong.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; //Correctly referencing the necessary namespaces, right?

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            CategoryRepository categoryRepo = new CategoryRepository();
            var categories = categoryRepo.FindAllCategories();

            foreach (Category c in categories)
            {
                helper.RouteLink(blablabla); //Construct links and return them.
            }

            //helper.RouteLink doesn't show up! C# wipeouuuuuttttt.
            //It's as if 'helper' doesn't have the RouteLink method there.
        }
    }
}

First time that this happens to me when programming in C#. Anyone else encounter this problem?


问:
Scala : Type Nothing with User defined classes
In scala Nothing is a subtype of every other type.

```<code>scala> class A {}
defined class A

scala> def x[T >: Nothing](t: T): Unit = {}
x: [T](t: T)Unit

scala> x(new A)
</code>```

When we create an arbitrary class, it automatically becomes a supertype of Nothing

How this property is maintained in scala? Does the compiler makes Nothing extend every other class at compile time?

Like this way, is it possible to define a custom class X as a subtype of a set of classes(say set s) without making X extend from all the classes in the s? (e.g: Class X is a subtype of all the classes in package com.myproject.models)

Please share your thoughts.

答:
How this property is maintained in scala? Does the compiler makes Nothing extend every other class at compile time?

Nothing is not implemented with an actual class, it's a pure artifact of the compiler. The actual handling of the Nothing type can be vulgarized as hardcoding Nothing in several places inside the compiler, for instance, isSubType(t1: Type, t2: Type): Boolean is unconditionally true when t1 == Nothing.

Like this way, is it possible to define a custom class X as a subtype of a set of classes(say set s) without making X extend from all the classes in the s?

No.

Body:
In scala Nothing is a subtype of every other type.

scala> class A {}
defined class A

scala> def x[T >: Nothing](t: T): Unit = {}
x: [T](t: T)Unit

scala> x(new A)

When we create an arbitrary class, it automatically becomes a supertype of Nothing

How this property is maintained in scala? Does the compiler makes Nothing extend every other class at compile time?

Like this way, is it possible to define a custom class X as a subtype of a set of classes(say set s) without making X extend from all the classes in the s? (e.g: Class X is a subtype of all the classes in package com.myproject.models)

Please share your thoughts.


问:
Less wrong TryGetValue then null check syntax
I'm a little new to C# still... I'm finding myself reusing a specific procedure over and over. Before I go writing a helper method for personal laziness, is there a shorter or less wrong way to write this sort of statement?

```<code>Dictionary<string, string> data = someBigDictionary;
string createdBy;
data.TryGetValue("CreatedBy", out createdBy);
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = createdBy ?? "Unknown",
    //set 15 other values
    ...
}
</code>```

Essentially, set a property on an object by trying to get a value, then if it's null use a default value. I have a LOT of properties, it would be better if I could just

```<code>MyEntity me = new MyEntity{
    CreatedBy = TryToGetValueOrReturnNull(data, "CreatedBy") ?? "Unknown",
    ...
}
</code>```

Again, I am perfectly capable of writing my own helper function. I'm looking for an existing native functionality or shorthand before I do so.

答:
```<code>public static class DictionaryExtensions
{
    public static U TryGetValueOrDefault<T, U>(this IDictionary<T, U> dict, T key, U defaultValue)
    {
        U temp;

        if (dict.TryGetValue(key, out temp))
            return temp;

        return defaultValue;
    }
}
</code>```

then do something like:

```<code>Dictionary<string, string> data = someBigDictionary;
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = data.TryGetValueOrDefault("CreatedBy", "Unknown"),
    //set 15 other values
    ...
}
</code>```

Body:
I'm a little new to C# still... I'm finding myself reusing a specific procedure over and over. Before I go writing a helper method for personal laziness, is there a shorter or less wrong way to write this sort of statement?

Dictionary<string, string> data = someBigDictionary;
string createdBy;
data.TryGetValue("CreatedBy", out createdBy);
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = createdBy ?? "Unknown",
    //set 15 other values
    ...
}

Essentially, set a property on an object by trying to get a value, then if it's null use a default value. I have a LOT of properties, it would be better if I could just

MyEntity me = new MyEntity{
    CreatedBy = TryToGetValueOrReturnNull(data, "CreatedBy") ?? "Unknown",
    ...
}

Again, I am perfectly capable of writing my own helper function. I'm looking for an existing native functionality or shorthand before I do so.

Body:
public static class DictionaryExtensions
{
    public static U TryGetValueOrDefault<T, U>(this IDictionary<T, U> dict, T key, U defaultValue)
    {
        U temp;

        if (dict.TryGetValue(key, out temp))
            return temp;

        return defaultValue;
    }
}

then do something like:

Dictionary<string, string> data = someBigDictionary;
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = data.TryGetValueOrDefault("CreatedBy", "Unknown"),
    //set 15 other values
    ...
}


问:
Build trigger failed in Container Registry
I created a trigger in Container Registry. I have my script in GIT HUB repo.
In Build trigger selected repository hosting option as GitHub and Authenticated.

STEP: 1: Selected git hub source repository

STEP:2: Selected my git hub repo and authenticated.

STEP 3: Created trigger using docker file option.

STEP 4: Trigger ran & I got build failed.

Build log

```<code>starting build "5b04afe3-b669-48c6-83b1-58342f918256"

FETCHSOURCE
Initialized empty Git repository in /workspace/.git/
From https://source.developers.google.com/p/project-id/r/github-dhandapanisattanathan-gcb
* branch 59182f2dd5caffcc224d49299595056afd64d295 -> FETCH_HEAD
HEAD is now at 59182f2 ver 2
BUILD
Already have image (with digest): gcr.io/cloud-builders/docker
unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /workspace/Dockerfile: no such file or directory
ERROR
ERROR: build step "gcr.io/cloud-builders/docker@sha256:bb4f74d4d598896f932f4d2a5b12b3a816f5f6d3c9cf1f50d0bdd98fd4004d2d" failed: exit status 1
</code>```

I got this issue unable to prepare context: unable to evaluate symlinks in Docker file path: lstat /workspace/Dockerfile: no such file or directory.

I don't know what I missed here. But each push in git hub trigger running automatically with build failed.

Please help me to fix this.

答:
The contents of /workspace are the contents of your git repository; in this case, https://github.com/dhandapanisattanathan/gcb. Your repository has no Dockerfile, so you can't use that non-existent Dockerfile to build.

It looks like your repository is for a GAE standard app. It's probably possible to transform it into a runnable container, but I don't know exactly what you would put in your Dockerfile to make it happen.

Body:
I created a trigger in Container Registry. I have my script in GIT HUB repo.
In Build trigger selected repository hosting option as GitHub and Authenticated.

STEP: 1: Selected git hub source repository

STEP:2: Selected my git hub repo and authenticated.

STEP 3: Created trigger using docker file option.

STEP 4: Trigger ran & I got build failed.

Build log

starting build "5b04afe3-b669-48c6-83b1-58342f918256"

FETCHSOURCE
Initialized empty Git repository in /workspace/.git/
From https://source.developers.google.com/p/project-id/r/github-dhandapanisattanathan-gcb
* branch 59182f2dd5caffcc224d49299595056afd64d295 -> FETCH_HEAD
HEAD is now at 59182f2 ver 2
BUILD
Already have image (with digest): gcr.io/cloud-builders/docker
unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /workspace/Dockerfile: no such file or directory
ERROR
ERROR: build step "gcr.io/cloud-builders/docker@sha256:bb4f74d4d598896f932f4d2a5b12b3a816f5f6d3c9cf1f50d0bdd98fd4004d2d" failed: exit status 1

I got this issue unable to prepare context: unable to evaluate symlinks in Docker file path: lstat /workspace/Dockerfile: no such file or directory.

I don't know what I missed here. But each push in git hub trigger running automatically with build failed.

Please help me to fix this.


问:
Rails 5: Cron jobs using Whenever not running
I am trying to make a task run every hour using the Whenever gem.

```<code>#check_price.rake
namespace :check_price do
  desc "TODO"
  task check_now: :environment do
    price_sync = PriceSyncLibrary.new
    Product.all.each do |product|
      product.price.push(price_sync.get_price_from_link(product.flipkart_link))
      product.time.push(Time.now)
      product.save!
    end
  end
end
</code>```

This is my schedule.rb file

```<code>every 1.minute do
  rake "check_price:check_now", environment: 'development'
end
</code>```

When I run

```<code>rake check_price:check_now
</code>```

in the terminal, I am getting the result I want, but the same rake task is not running every minute as specified in the schedule.rb file. Am I missing something?

When I run

```<code>crontab -l
</code>```

in the console, I get this result.

```<code># Begin Whenever generated tasks for: /home/raghav/workspace/apps/Shotgun/config/schedule.rb
* * * * * /bin/bash -l -c 'cd /home/raghav/workspace/apps/Shotgun && RAILS_ENV=production bundle exec rake check_price:check_now --silent'

# End Whenever generated tasks for: /home/raghav/workspace/apps/Shotgun/config/schedule.rb

# Begin Whenever generated tasks for: Shotgun
* * * * * /bin/bash -l -c 'cd /home/raghav/workspace/apps/Shotgun && RAILS_ENV=production bundle exec rake check_price:check_now --silent'

# End Whenever generated tasks for: Shotgun
</code>```

答:
In your schedule.rb file, your environment is set to development and in the response of crontab -l command the environment is set to production,
You can set the environment like this,</p>

```<code>set :environment, "development"
set :output, {:error => "log/cron_error_log.log", :standard => "log/cron_log.log"}

every 1.minute do
  rake "check_price:check_now"
end
</code>```

Body:
I am trying to make a task run every hour using the Whenever gem.

#check_price.rake
namespace :check_price do
  desc "TODO"
  task check_now: :environment do
    price_sync = PriceSyncLibrary.new
    Product.all.each do |product|
      product.price.push(price_sync.get_price_from_link(product.flipkart_link))
      product.time.push(Time.now)
      product.save!
    end
  end
end

This is my schedule.rb file

every 1.minute do
  rake "check_price:check_now", environment: 'development'
end

When I run

rake check_price:check_now

in the terminal, I am getting the result I want, but the same rake task is not running every minute as specified in the schedule.rb file. Am I missing something?

When I run

crontab -l

in the console, I get this result.

# Begin Whenever generated tasks for: /home/raghav/workspace/apps/Shotgun/config/schedule.rb
* * * * * /bin/bash -l -c 'cd /home/raghav/workspace/apps/Shotgun && RAILS_ENV=production bundle exec rake check_price:check_now --silent'

# End Whenever generated tasks for: /home/raghav/workspace/apps/Shotgun/config/schedule.rb

# Begin Whenever generated tasks for: Shotgun
* * * * * /bin/bash -l -c 'cd /home/raghav/workspace/apps/Shotgun && RAILS_ENV=production bundle exec rake check_price:check_now --silent'

# End Whenever generated tasks for: Shotgun

Body:
In your schedule.rb file, your environment is set to development and in the response of crontab -l command the environment is set to production,
You can set the environment like this,

set :environment, "development"
set :output, {:error => "log/cron_error_log.log", :standard => "log/cron_log.log"}

every 1.minute do
  rake "check_price:check_now"
end


问:
How to get date in following format "2017-06-06T07:00:00.000Z" in Python?
I would like to get current date/time in the following format "2017-06-06T07:00:00.000Z" in Python. I have JSON that contains this date formatting and I would like to imitate this. Any idea if this a standard (ISO) format or how I can get this format? I couldn't find this format on StackOverflow.</p>

答: Yes, it is ISO format (see ISO 8601) and you can produce it in Python in several ways, in particular using time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()).


问:
List Map Layers names with geometry types
I am trying to write a Python Tool that shows the names of all layers with their geometry types, but when I run my code it shows all layers as Polygon only. Can someone point out where I am going wrong? I am a newbie.

Here is my code so far:

```<code>import arcpy.mapping as mapping
mxd = mapping.MapDocument ("CURRENT")
layers = mapping.ListLayers(mxd)
inFC = arcpy.GetParameterAsText(0)
outFC = arcpy.GetParameterAsText(1)
desc = arcpy.Describe("C:/Program Files(x86)/ArcGIS/Desktop10.4/Reference Systems/utm.shp")
type = desc.shapeType
for lyr in layers:
    print lyr.name +" " + type
</code>```

答:
You are currently using type = desc.shapeType, describing the shapeType of a particular shapefile. This won't tell you about the individual layers in the MXD (which you're looping through with for lyr in layers:).

In order to get the shapeType of a particular layer, Describe again within the loop:

```<code>for lyr in layers:
    desc = arcpy.Describe(lyr)
    print lyr.name, desc.shapeType
</code>```

Body:
I am trying to write a Python Tool that shows the names of all layers with their geometry types, but when I run my code it shows all layers as Polygon only. Can someone point out where I am going wrong? I am a newbie.

Here is my code so far:

import arcpy.mapping as mapping
mxd = mapping.MapDocument ("CURRENT")
layers = mapping.ListLayers(mxd)
inFC = arcpy.GetParameterAsText(0)
outFC = arcpy.GetParameterAsText(1)
desc = arcpy.Describe("C:/Program Files(x86)/ArcGIS/Desktop10.4/Reference Systems/utm.shp")
type = desc.shapeType
for lyr in layers:
    print lyr.name +" " + type

Body:
You are currently using type = desc.shapeType, describing the shapeType of a particular shapefile. This won't tell you about the individual layers in the MXD (which you're looping through with for lyr in layers:).

In order to get the shapeType of a particular layer, Describe again within the loop:

for lyr in layers:
    desc = arcpy.Describe(lyr)
    print lyr.name, desc.shapeType


问:
universal.angular.io vs prerender.io from googlebot perspective
I have a setup of a website with Angular 1.4.x and prerender.io that serves the rendered static cached pages to googlebot.
Googlebot crawls each page twice. One crawl hit the URL and the second crawl is appending ?_escaped_fragment_ to url to get the cached static page from prerender.io

I'm thinking on moving to universal.angular.io which will render the page in the server side.

What are the different approaches between the two?
Does universal.angular.io server side rendering support serving to googlebot and to end-clients?

Thanks,

答:
Well for something like Prerender, the way it works is by hijacking the AJAX crawl by search engines and serving it a prerendered version that they have cached. In this case only the search bot sees the prerendering. (I believe that ?_escaped_fragment_ is what trigger is, but it's treated by the crawler as the same route as the one without it)

If you migrate your application to Angular (2 or greater) and use Angular Universal, you'll allow your server to render out the pages that get sent to both the search bots as well as the regular user. Nixing the need for the ?_escaped_fragment_.


问:
openssl_pkey_get_details cause internal server error
I make some code to generate public and private code. It was working ok on one machine, but on other server it is causing "Internal Server Error".

```<code>private function keyGen()
{
    if(is_file($this::pubK_path) )
        exec("rm ".$this::pubK_path);
    if(is_file($this::privK_path) )
        exec("rm ".$this::privK_path);

    $config = array(
        "digest_alg" => "sha512",
        "private_key_bits" => 512,
        "private_key_type" => OPENSSL_KEYTYPE_RSA
    );

    // Create the private and public key
    $this->key = openssl_pkey_new($config);

    $pubkey=openssl_pkey_get_details($this->key);
    $this->pubkey=$pubkey["key"];

    $privK=null;
    openssl_pkey_export($this->key, $privK,$this->pass);
    file_put_contents($this::privK_path, $privK);
    file_put_contents($this::pubK_path, $this->pubkey);
}
</code>```

Sadly I didn't find any information about this error in any log. I only find that it is caused by this line:

```<code>$pubkey=openssl_pkey_get_details($this->key);
</code>```

Key is generated properly - when I deleted openssl_pkey_get_details, private key was saved in file.

Any ideas what is wrong, or other method to get public key?

答:
Sadly I didn't find any information about this error in any log.

You can use openssl_error_string() to find out what is  openssl_pkey_new() returning, you should see a false or any other OpenSSL error (from here). Like:

```<code><?php
// lets assume you just called an openssl function that failed
while ($msg = openssl_error_string())
    echo $msg . "<br />\n";
?>
</code>```

Then it should be easy to find the problem (you can update this thread with the error).

Hope it helps!

Body:
I make some code to generate public and private code. It was working ok on one machine, but on other server it is causing "Internal Server Error".

private function keyGen()
{
    if(is_file($this::pubK_path) )
        exec("rm ".$this::pubK_path);
    if(is_file($this::privK_path) )
        exec("rm ".$this::privK_path);

    $config = array(
        "digest_alg" => "sha512",
        "private_key_bits" => 512,
        "private_key_type" => OPENSSL_KEYTYPE_RSA
    );

    // Create the private and public key
    $this->key = openssl_pkey_new($config);

    $pubkey=openssl_pkey_get_details($this->key);
    $this->pubkey=$pubkey["key"];

    $privK=null;
    openssl_pkey_export($this->key, $privK,$this->pass);
    file_put_contents($this::privK_path, $privK);
    file_put_contents($this::pubK_path, $this->pubkey);
}

Sadly I didn't find any information about this error in any log. I only find that it is caused by this line:

$pubkey=openssl_pkey_get_details($this->key);

Key is generated properly - when I deleted openssl_pkey_get_details, private key was saved in file.

Any ideas what is wrong, or other method to get public key?

Body:
Sadly I didn't find any information about this error in any log.

You can use openssl_error_string() to find out what is  openssl_pkey_new() returning, you should see a false or any other OpenSSL error (from here). Like:

<?php
// lets assume you just called an openssl function that failed
while ($msg = openssl_error_string())
    echo $msg . "<br />\n";
?>

Then it should be easy to find the problem (you can update this thread with the error).

Hope it helps!


问:
Is it possible to define a function pointer to a constructor?
I'm using shared library with explicit linking (loading shared lib with dlopen) in order to implement plugin pattern in C++.

Is it possible to define a function pointer to a constructor of a class defined in the shared library or I would have to define factory method, within shared lib, that would instantiate (and initialize) object of a class from shared lib? Of course in my main app, then, I would define a function pointer to a factory method, and that method would return an instance of the class I need.

Cheers

答:
The answer to the question is no, you can not define a member or function pointer to the constructor.

For dlopen, you need to provide a function with c linkage and load it dynamically, which you can use to create the objects, and you also need another function to delete objects.

More about it here


问:
Look and change data on mysql with PHP and strotime() function
I have a problem about strotime() function.

My code like below; (PHP PDO MySQL)

```<code>$BasketLastDate = date('Y-m-d H:i:s',strtotime('+7 minutes'));
$BasketLastDate = strtotime($BasketLastDate);
$sepetONAY = 0;
$sg = "SELECT * FROM baskets WHERE approve=1 and checkout=0";
foreach($db->query($sg) as $basketDetails){
$BasketDate = $basketDetails['basket_date'];
$BasketDate = strtotime($BasketDate);
// If the basket older than 7 minutes
if ($BasketLastDate < $BasketDate){
 // code....
}
</code>```

The code should look all rows and change situation if the record older than 7 minutes. But it doesn't happened.

Please help me guys.

答:
I think you should check time before 7 minutes not after :</p>

```<code>$BasketLastDate = date('Y-m-d H:i:s',strtotime('-7 minutes'));
</code>```

Body:
I have a problem about strotime() function.

My code like below; (PHP PDO MySQL)

$BasketLastDate = date('Y-m-d H:i:s',strtotime('+7 minutes'));
$BasketLastDate = strtotime($BasketLastDate);
$sepetONAY = 0;
$sg = "SELECT * FROM baskets WHERE approve=1 and checkout=0";
foreach($db->query($sg) as $basketDetails){
$BasketDate = $basketDetails['basket_date'];
$BasketDate = strtotime($BasketDate);
// If the basket older than 7 minutes
if ($BasketLastDate < $BasketDate){
 // code....
}

The code should look all rows and change situation if the record older than 7 minutes. But it doesn't happened.

Please help me guys.

Body:
I think you should check time before 7 minutes not after :

$BasketLastDate = date('Y-m-d H:i:s',strtotime('-7 minutes'));


问:
Springboot Multiple datasources Entityscan
I have two data sources each are dealing with different entities. I have set entity scan packages for entity manager to scan different packages. and also I have configured "hibernate.hbm2ddl.auto" to update. when the application starts, the hibernate is creating tables in both the datasources. My requirement is to create tables mapped to corresponding datasources.</p>

答:
You can create two files schema.sql(your ddl's like create alter drop) and data.sql(your dml's like insert, delete) for each datasource in your resources folder. Then you should put a property in your application.properties to run scripts when the application booting: spring.jpa.hibernate.ddl-auto=none

After that in your Application.java class, create a method to run your scripts:

This is for first ds:

```<code>@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
   DriverManagerDataSource dataSource = new DriverManagerDataSource();
   dataSource.setDriverClassName("org.h2.Driver");
   dataSource.setUrl("ds url");
   dataSource.setUsername("");
   dataSource.setPassword("");

   // schema init
   Resource initSchema = new ClassPathResource("scripts/schema-first.sql");
   Resource initData = new ClassPathResource("scripts/data-first.sql");
   DatabasePopulator databasePopulator = new
   ResourceDatabasePopulator(initSchema, initData);
   DatabasePopulatorUtils.execute(databasePopulator, dataSource);

   return dataSource;
</code>```

}

I think it should work.You can create another method for your second datasource.

Body:
You can create two files schema.sql(your ddl's like create alter drop) and data.sql(your dml's like insert, delete) for each datasource in your resources folder. Then you should put a property in your application.properties to run scripts when the application booting: spring.jpa.hibernate.ddl-auto=none

After that in your Application.java class, create a method to run your scripts:

This is for first ds:

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
   DriverManagerDataSource dataSource = new DriverManagerDataSource();
   dataSource.setDriverClassName("org.h2.Driver");
   dataSource.setUrl("ds url");
   dataSource.setUsername("");
   dataSource.setPassword("");

   // schema init
   Resource initSchema = new ClassPathResource("scripts/schema-first.sql");
   Resource initData = new ClassPathResource("scripts/data-first.sql");
   DatabasePopulator databasePopulator = new
   ResourceDatabasePopulator(initSchema, initData);
   DatabasePopulatorUtils.execute(databasePopulator, dataSource);

   return dataSource;

}

I think it should work.You can create another method for your second datasource.


问:
How to pass an array to a @slot in laravel 5.4?
I am trying to use it in my layout and I'm suddenly bump-up with the idea of using the new features of Laravel 5.4 @slot.

Just wondering if passing an array to a slot possible?

```<code>        @section('SampleSection')

            @component( 'mylayouts.partials.contentheader' )

                @slot('title')
                    Sample Title
                @endslot

                @slot('indexes')
                    Pass array here  // example [ 'a', 'b', 'c' ]
                @endslot

            @endcomponent

        @endsection
</code>```

答:
it's so simple and easy send array into component template without any @slot
in view page

view.blade.php

```<code>@component('components.button',[
  'tooltipTitle'=>'buttorr33',
  'addStyle'=>'pointer',
  ])
  @endcomponent
</code>```

in component php file component\button.php

```<code><div class="block-buttons {{$addStyle or NULL}}"
     {{--if set tooltip, add atributes--}}
     @if (isset($tooltipTitle))...
</code>```

Body:
I am trying to use it in my layout and I'm suddenly bump-up with the idea of using the new features of Laravel 5.4 @slot.

Just wondering if passing an array to a slot possible?

        @section('SampleSection')

            @component( 'mylayouts.partials.contentheader' )

                @slot('title')
                    Sample Title
                @endslot

                @slot('indexes')
                    Pass array here  // example [ 'a', 'b', 'c' ]
                @endslot

            @endcomponent

        @endsection

Body:
it's so simple and easy send array into component template without any @slot
in view page

view.blade.php

@component('components.button',[
  'tooltipTitle'=>'buttorr33',
  'addStyle'=>'pointer',
  ])
  @endcomponent

in component php file component\button.php

<div class="block-buttons {{$addStyle or NULL}}"
     {{--if set tooltip, add atributes--}}
     @if (isset($tooltipTitle))...


问:
Alternative of Unity & SIO2
I am searching for open source free API just like Unity or SIO2 which I can use for commercial purpose. Kindly tell me if there is any API for iPhone 3D games.</p>

答:
AFAIK there are two open source game engines:

irrlicht

oolongengine

I don't know much about irrlicht, but there are some dicussions about it here on stackoverflow.com. I think they support iPhone development for quite a while. oolong seems to have a hard learning curve because there is not much documentation and you have to subscribe to a good old mailing list.

If you are an Indie developer with less than 100k $ / year, Bork 3D engine might be worth to look at - you just have to pay $49. There is one drawback in that you don't have support for blender and you should have to check whether collada files are useful, if you don't use a commercial 3D modelling tool.

Just found this in my bookmarks :-) It's a bit out of date but a good place to start investigations:

iPhone Game Engine Comparison – Open Source

Title: Alternative of Unity & SIO2


问:
Sharing a variable between classes
I have create 2 JFrame in Netbeans(Booking, ConfirmBooking), both there frame are connected to a SQL database. In the Booking class the user chooses a resort form the table displayed by entering a number in a jtextfield. If the user pushes the next button. Class Booking is disposed and ConfirmBooking is opened. I want to access the variable that was entered in Booking in the jtextfield in ConfirmBooking to access the name of the resort the user booked.

Booking Class coding, I want to access the ID that is set to public int above in the class.

```<code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    String x = jTextFieldID.getText();
    ID = Integer.valueOf(x);
    String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = "+ ID;
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {

                try (ResultSet rs = pstmt.executeQuery()) {
                    if (rs.next()) {
                    String resortName = rs.getString("RESORT_NAME");

                    int n =  JOptionPane.showOptionDialog(null,
                    "Do you want to make a booking at "+resortName+"?",
                    "Confirm booking?",
                    JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.INFORMATION_MESSAGE,
                    null,
                    new String[]{"Yes I do", "No I don't"},"default");

                    if (n == JOptionPane.YES_OPTION)
                    {
                        ConfirmBooking CB = new ConfirmBooking();
                        dispose();
                        CB.setLocationRelativeTo(null);
                        CB.setVisible(true);

                    }
                        else if (n == JOptionPane.NO_OPTION)
                    {
            }
        }
    }

}
catch (SQLException ex)
{
Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
}

}
</code>```

ConfirmBooking Class code

```<code>    public void SetUp()
    {
        UserList();

        String sql = "SELECT RESORT_NAME, COST_PER_NIGHT_ZAR FROM LouwDataBase.Resorts WHERE ID = "+ ID;
            try (PreparedStatement pstmt = conn.prepareStatement(sql))
            {
                    try (ResultSet rs = pstmt.executeQuery())
                    {
                        if (rs.next())
                        {
                        String Name1 = rs.getString("RESORT_NAME");
                        double Price = rs.getDouble("COST_PER_NIGHT_ZAR");
                        String Rands = Double.toString(Price);
                        ResortName.setText(Name1);
                        ResortPrice.setText("R "+Rands);
                        }
                    }
            }
            catch (SQLException ex)
            {
                Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
</code>```

答:
you could modify a little the ConfirmBooking class so you can pass that variable in the constructor of the class maybe

and then you can do:

```<code>if (n == JOptionPane.YES_OPTION) {
     ConfirmBooking CB = new ConfirmBooking(ID);
     dispose();
     CB.setLocationRelativeTo(null);
     CB.setVisible(true);
}
</code>```

you store that ID in a member of the ConfirmBooking  and retrieve that in the setUp method whenever you need it!

Title: Sharing a variable between classes

Body:
I have create 2 JFrame in Netbeans(Booking, ConfirmBooking), both there frame are connected to a SQL database. In the Booking class the user chooses a resort form the table displayed by entering a number in a jtextfield. If the user pushes the next button. Class Booking is disposed and ConfirmBooking is opened. I want to access the variable that was entered in Booking in the jtextfield in ConfirmBooking to access the name of the resort the user booked.

Booking Class coding, I want to access the ID that is set to public int above in the class.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    String x = jTextFieldID.getText();
    ID = Integer.valueOf(x);
    String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = "+ ID;
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {

                try (ResultSet rs = pstmt.executeQuery()) {
                    if (rs.next()) {
                    String resortName = rs.getString("RESORT_NAME");

                    int n =  JOptionPane.showOptionDialog(null,
                    "Do you want to make a booking at "+resortName+"?",
                    "Confirm booking?",
                    JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.INFORMATION_MESSAGE,
                    null,
                    new String[]{"Yes I do", "No I don't"},"default");

                    if (n == JOptionPane.YES_OPTION)
                    {
                        ConfirmBooking CB = new ConfirmBooking();
                        dispose();
                        CB.setLocationRelativeTo(null);
                        CB.setVisible(true);

                    }
                        else if (n == JOptionPane.NO_OPTION)
                    {
            }
        }
    }

}
catch (SQLException ex)
{
Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
}

}

ConfirmBooking Class code

    public void SetUp()
    {
        UserList();

        String sql = "SELECT RESORT_NAME, COST_PER_NIGHT_ZAR FROM LouwDataBase.Resorts WHERE ID = "+ ID;
            try (PreparedStatement pstmt = conn.prepareStatement(sql))
            {
                    try (ResultSet rs = pstmt.executeQuery())
                    {
                        if (rs.next())
                        {
                        String Name1 = rs.getString("RESORT_NAME");
                        double Price = rs.getDouble("COST_PER_NIGHT_ZAR");
                        String Rands = Double.toString(Price);
                        ResortName.setText(Name1);
                        ResortPrice.setText("R "+Rands);
                        }
                    }
            }
            catch (SQLException ex)
            {
                Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
            }
    }

Body:
you could modify a little the ConfirmBooking class so you can pass that variable in the constructor of the class maybe

and then you can do:

if (n == JOptionPane.YES_OPTION) {
     ConfirmBooking CB = new ConfirmBooking(ID);
     dispose();
     CB.setLocationRelativeTo(null);
     CB.setVisible(true);
}

you store that ID in a member of the ConfirmBooking  and retrieve that in the setUp method whenever you need it!


答:
You could try something like this:</p>

```<code>ConfirmBooking CB = new ConfirmBooking();
CB.setResortNumber(resortName);
</code>```

Title: Sharing a variable between classes

Body:
You could try something like this:

ConfirmBooking CB = new ConfirmBooking();
CB.setResortNumber(resortName);


答: I am not sure add the namespace see the resukt System.Web.Mvc.Html</p>

Title: Creating an extension method in C#

Body:
I'm trying to create an extension method in C# for the HtmlHelper class. I've read the MSDN page for it, and I'm sure I'm referencing the correct namespaces. I wonder what I could be doing wrong.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; //Correctly referencing the necessary namespaces, right?

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            CategoryRepository categoryRepo = new CategoryRepository();
            var categories = categoryRepo.FindAllCategories();

            foreach (Category c in categories)
            {
                helper.RouteLink(blablabla); //Construct links and return them.
            }

            //helper.RouteLink doesn't show up! C# wipeouuuuuttttt.
            //It's as if 'helper' doesn't have the RouteLink method there.
        }
    }
}

First time that this happens to me when programming in C#. Anyone else encounter this problem?


问:
MySQL Syntax Error, Unrecognized keyword null
MySqli/phpmyadmin query not working - unrecognized keyword 'NULL'

I use

```<code>PHP - mysqli
MySQL + phpMyAdmin
</code>```

Sql :

```<code>update User set name = null;
</code>```

Error :

Unrecognized keyword null

thank for any help !

答:
try something like this:

```<code>UPDATE `User`
SET `name` = NULL;
</code>```

see more information about UPDATE and SET here

But maybe your column doesn´t allow NULL values

Body:
MySqli/phpmyadmin query not working - unrecognized keyword 'NULL'

I use

PHP - mysqli
MySQL + phpMyAdmin

Sql :

update User set name = null;

Error :

Unrecognized keyword null

thank for any help !

Body:
try something like this:

UPDATE `User`
SET `name` = NULL;

see more information about UPDATE and SET here

But maybe your column doesn´t allow NULL values


问:
Android, prevent ImageButton from stretching TableLayout
So, i am trying to make a custom keyboard with ImageButton in the bottom left corner, however the image refuses to scale down, like if i was using wrap_content. wrap_content property is never used.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/bgColor"
  android:weightSum="100">
  <LinearLayout
      android:orientation="vertical"
      android:minWidth="25px"
      android:minHeight="25px"
      android:layout_width="match_parent"
      android:layout_height="0dip"
      android:id="@+id/linearLayout1"
      android:background="@color/orange"
      android:layout_weight="10" />
  <LinearLayout
      android:orientation="vertical"
      android:minWidth="25px"
      android:minHeight="25px"
      android:layout_width="match_parent"
      android:layout_height="0dip"
      android:id="@+id/linearLayout2"
      android:layout_weight="80"
      android:weightSum="100">
      <LinearLayout
          android:orientation="vertical"
          android:minWidth="25px"
          android:minHeight="25px"
          android:layout_width="match_parent"
          android:layout_height="0dip"
          android:layout_weight="40"
          android:id="@+id/linearLayout4"
          android:weightSum="100">
          <LinearLayout
              android:orientation="vertical"
              android:minWidth="25px"
              android:minHeight="25px"
              android:layout_width="match_parent"
              android:layout_height="0dp"
              android:id="@+id/linearLayout6"
              android:layout_weight="15" />
          <LinearLayout
              android:orientation="vertical"
              android:minWidth="25px"
              android:minHeight="25px"
              android:layout_width="match_parent"
              android:layout_height="0dp"
              android:id="@+id/linearLayout7"
              android:layout_weight="70"
              android:weightSum="100">
              <LinearLayout
                  android:orientation="horizontal"
                  android:layout_width="match_parent"
                  android:layout_height="0dp"
                  android:id="@+id/linearLayout9"
                  android:layout_weight="45"
                  android:weightSum="100">
                  <ImageView
                      android:src="@drawable/eurcurrency"
                      android:layout_width="0dp"
                      android:layout_height="match_parent"
                      android:id="@+id/imageView1"
                      android:layout_weight="30"
                      android:scaleType="fitEnd"
                      android:paddingRight="10dp"
                      android:paddingTop="5dp"
                      android:paddingBottom="5dp" />
                  <TextView
                      android:text="0"
                      android:layout_width="0dp"
                      android:layout_height="match_parent"
                      android:id="@+id/textView10"
                      android:layout_weight="70"
                      android:paddingRight="5dp"
                      android:paddingLeft="5dp"
                      android:textColor="@android:color/black"
                      android:gravity="center_vertical"
                      android:textSize="30sp" />
              </LinearLayout>
              <LinearLayout
                  android:orientation="vertical"
                  android:minWidth="25px"
                  android:minHeight="25px"
                  android:layout_width="match_parent"
                  android:layout_height="0dp"
                  android:id="@+id/linearLayout10"
                  android:layout_weight="10" />
              <LinearLayout
                  android:orientation="horizontal"
                  android:layout_width="match_parent"
                  android:layout_height="0dp"
                  android:id="@+id/linearLayout9"
                  android:layout_weight="45"
                  android:weightSum="100">
                  <ImageView
                      android:src="@drawable/btccurrency"
                      android:layout_width="0dp"
                      android:layout_height="match_parent"
                      android:id="@+id/imageView1"
                      android:layout_weight="30"
                      android:scaleType="fitEnd"
                      android:paddingRight="10dp"
                      android:paddingTop="5dp"
                      android:paddingBottom="5dp" />
                  <TextView
                      android:text="0"
                      android:layout_width="0dp"
                      android:layout_height="match_parent"
                      android:id="@+id/textView10"
                      android:layout_weight="70"
                      android:paddingRight="5dp"
                      android:paddingLeft="5dp"
                      android:textColor="@android:color/black"
                      android:gravity="center_vertical"
                      android:textSize="30sp" />
              </LinearLayout>
          </LinearLayout>
          <LinearLayout
              android:orientation="vertical"
              android:minWidth="25px"
              android:minHeight="25px"
              android:layout_width="match_parent"
              android:id="@+id/linearLayout8"
              android:layout_height="0dp"
              android:layout_weight="15" />
      </LinearLayout>
      <LinearLayout
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:id="@+id/linearLayout5"
          android:layout_weight="60"
          android:weightSum="100"
          android:minWidth="25px"
          android:minHeight="25px"
          android:background="@color/orange">
          <TableLayout
              android:id="@+id/tableLayout1"
              android:style="@style/CalculatorTable"
              android:minWidth="25px"
              android:minHeight="25px">
              <TableRow
                  android:id="@+id/tableRow1"
                  android:style="@style/CalculatorRow">
                  <Button
                      android:text="1"
                      android:layout_column="0"
                      android:id="@+id/button2"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="2"
                      android:layout_column="1"
                      android:id="@+id/button6"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="3"
                      android:layout_column="2"
                      android:id="@+id/button3"
                      android:style="@style/CalculatorButton" />
              </TableRow>
              <TableRow
                  android:id="@+id/tableRow2"
                  android:style="@style/CalculatorRow">
                  <Button
                      android:text="4"
                      android:layout_column="0"
                      android:id="@+id/button4"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="5"
                      android:layout_column="1"
                      android:id="@+id/button7"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="6"
                      android:layout_column="2"
                      android:id="@+id/button5"
                      android:style="@style/CalculatorButton" />
              </TableRow>
              <TableRow
                  android:id="@+id/tableRow3"
                  android:style="@style/CalculatorRow">
                  <Button
                      android:text="7"
                      android:layout_column="0"
                      android:id="@+id/button8"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="8"
                      android:layout_column="1"
                      android:id="@+id/button9"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="9"
                      android:layout_column="2"
                      android:id="@+id/button10"
                      android:style="@style/CalculatorButton" />
              </TableRow>
              <TableRow
                  android:id="@+id/tableRow4"
                  android:style="@style/CalculatorRow"
                  android:orientation="horizontal">
                  <Button
                      android:text="00"
                      android:layout_column="0"
                      android:id="@+id/button11"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="0"
                      android:layout_column="1"
                      android:id="@+id/button12"
                      android:style="@style/CalculatorButton" />
                  <ImageButton
                      android:layout_column="2"
                      android:id="@+id/imageButton1"
                      android:style="@style/CalculatorButton"
                      android:src="@drawable/bitcoineuroswap"
                      android:scaleType="fitCenter" />
              </TableRow>
          </TableLayout>
      </LinearLayout>
  </LinearLayout>
  <LinearLayout
      android:orientation="vertical"
      android:minWidth="25px"
      android:minHeight="25px"
      android:layout_width="match_parent"
      android:id="@+id/linearLayout3"
      android:background="@color/orange"
      android:layout_weight="10" />
  </LinearLayout>
</code>```

My styles:

```<code><resources>
  <style name="CalculatorButton" >
    <item name="android:layout_width" >0dp</item>
    <item name="android:layout_weight" >33</item>
    <item name="android:layout_height" >fill_parent</item>
    <item name="android:background">@drawable/CalculatorButtonBackground</item>
  </style>

  <style name ="CalculatorRow">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_weight">25</item>
    <item name="android:layout_height">0dip</item>
    <item name="android:weightSum">99</item>
    <item name="android:gravity">fill_vertical</item>
    <item name="android:divider">@drawable/CalculatorDivider</item>
    <item name="android:dividerPadding">0dp</item>
    <item name="android:showDividers">middle</item>
  </style>

  <style name ="CalculatorTable">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:weightSum">100</item>
    <item name="android:divider">@drawable/CalculatorDivider</item>
    <item name="android:dividerPadding">0dp</item>
    <item name="android:showDividers">middle</item>
    <item name="android:background">@drawable/CalculatorTableBackground</item>
    <item name="android:layout_margin">1dp</item>
  </style>
</resources>
</code>```

Output (what i want - on the left, what i have got - on the right):

答:
Suggestion: To design a keypad, you can very well use just Linearlayout with appropriate values for weightsum and weight attribute.

Wrap your image button inside a layout like this

```<code> <RelativeLayout android:style="@style/CalculatorButton">
                        <ImageButton
                            android:id="@+id/imageButton1"
                            android:layout_centerInParent="true"
                            android:layout_width="20dp"
                            android:layout_height="20dp"
                            android:layout_column="2"
                            android:scaleType="fitCenter"
                            android:src="@drawable/hj" />
                    </RelativeLayout>
</code>```

Original height of the image will be considered. So better give the width and height of the image.

Body:
So, i am trying to make a custom keyboard with ImageButton in the bottom left corner, however the image refuses to scale down, like if i was using wrap_content. wrap_content property is never used.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/bgColor"
  android:weightSum="100">
  <LinearLayout
      android:orientation="vertical"
      android:minWidth="25px"
      android:minHeight="25px"
      android:layout_width="match_parent"
      android:layout_height="0dip"
      android:id="@+id/linearLayout1"
      android:background="@color/orange"
      android:layout_weight="10" />
  <LinearLayout
      android:orientation="vertical"
      android:minWidth="25px"
      android:minHeight="25px"
      android:layout_width="match_parent"
      android:layout_height="0dip"
      android:id="@+id/linearLayout2"
      android:layout_weight="80"
      android:weightSum="100">
      <LinearLayout
          android:orientation="vertical"
          android:minWidth="25px"
          android:minHeight="25px"
          android:layout_width="match_parent"
          android:layout_height="0dip"
          android:layout_weight="40"
          android:id="@+id/linearLayout4"
          android:weightSum="100">
          <LinearLayout
              android:orientation="vertical"
              android:minWidth="25px"
              android:minHeight="25px"
              android:layout_width="match_parent"
              android:layout_height="0dp"
              android:id="@+id/linearLayout6"
              android:layout_weight="15" />
          <LinearLayout
              android:orientation="vertical"
              android:minWidth="25px"
              android:minHeight="25px"
              android:layout_width="match_parent"
              android:layout_height="0dp"
              android:id="@+id/linearLayout7"
              android:layout_weight="70"
              android:weightSum="100">
              <LinearLayout
                  android:orientation="horizontal"
                  android:layout_width="match_parent"
                  android:layout_height="0dp"
                  android:id="@+id/linearLayout9"
                  android:layout_weight="45"
                  android:weightSum="100">
                  <ImageView
                      android:src="@drawable/eurcurrency"
                      android:layout_width="0dp"
                      android:layout_height="match_parent"
                      android:id="@+id/imageView1"
                      android:layout_weight="30"
                      android:scaleType="fitEnd"
                      android:paddingRight="10dp"
                      android:paddingTop="5dp"
                      android:paddingBottom="5dp" />
                  <TextView
                      android:text="0"
                      android:layout_width="0dp"
                      android:layout_height="match_parent"
                      android:id="@+id/textView10"
                      android:layout_weight="70"
                      android:paddingRight="5dp"
                      android:paddingLeft="5dp"
                      android:textColor="@android:color/black"
                      android:gravity="center_vertical"
                      android:textSize="30sp" />
              </LinearLayout>
              <LinearLayout
                  android:orientation="vertical"
                  android:minWidth="25px"
                  android:minHeight="25px"
                  android:layout_width="match_parent"
                  android:layout_height="0dp"
                  android:id="@+id/linearLayout10"
                  android:layout_weight="10" />
              <LinearLayout
                  android:orientation="horizontal"
                  android:layout_width="match_parent"
                  android:layout_height="0dp"
                  android:id="@+id/linearLayout9"
                  android:layout_weight="45"
                  android:weightSum="100">
                  <ImageView
                      android:src="@drawable/btccurrency"
                      android:layout_width="0dp"
                      android:layout_height="match_parent"
                      android:id="@+id/imageView1"
                      android:layout_weight="30"
                      android:scaleType="fitEnd"
                      android:paddingRight="10dp"
                      android:paddingTop="5dp"
                      android:paddingBottom="5dp" />
                  <TextView
                      android:text="0"
                      android:layout_width="0dp"
                      android:layout_height="match_parent"
                      android:id="@+id/textView10"
                      android:layout_weight="70"
                      android:paddingRight="5dp"
                      android:paddingLeft="5dp"
                      android:textColor="@android:color/black"
                      android:gravity="center_vertical"
                      android:textSize="30sp" />
              </LinearLayout>
          </LinearLayout>
          <LinearLayout
              android:orientation="vertical"
              android:minWidth="25px"
              android:minHeight="25px"
              android:layout_width="match_parent"
              android:id="@+id/linearLayout8"
              android:layout_height="0dp"
              android:layout_weight="15" />
      </LinearLayout>
      <LinearLayout
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:id="@+id/linearLayout5"
          android:layout_weight="60"
          android:weightSum="100"
          android:minWidth="25px"
          android:minHeight="25px"
          android:background="@color/orange">
          <TableLayout
              android:id="@+id/tableLayout1"
              android:style="@style/CalculatorTable"
              android:minWidth="25px"
              android:minHeight="25px">
              <TableRow
                  android:id="@+id/tableRow1"
                  android:style="@style/CalculatorRow">
                  <Button
                      android:text="1"
                      android:layout_column="0"
                      android:id="@+id/button2"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="2"
                      android:layout_column="1"
                      android:id="@+id/button6"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="3"
                      android:layout_column="2"
                      android:id="@+id/button3"
                      android:style="@style/CalculatorButton" />
              </TableRow>
              <TableRow
                  android:id="@+id/tableRow2"
                  android:style="@style/CalculatorRow">
                  <Button
                      android:text="4"
                      android:layout_column="0"
                      android:id="@+id/button4"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="5"
                      android:layout_column="1"
                      android:id="@+id/button7"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="6"
                      android:layout_column="2"
                      android:id="@+id/button5"
                      android:style="@style/CalculatorButton" />
              </TableRow>
              <TableRow
                  android:id="@+id/tableRow3"
                  android:style="@style/CalculatorRow">
                  <Button
                      android:text="7"
                      android:layout_column="0"
                      android:id="@+id/button8"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="8"
                      android:layout_column="1"
                      android:id="@+id/button9"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="9"
                      android:layout_column="2"
                      android:id="@+id/button10"
                      android:style="@style/CalculatorButton" />
              </TableRow>
              <TableRow
                  android:id="@+id/tableRow4"
                  android:style="@style/CalculatorRow"
                  android:orientation="horizontal">
                  <Button
                      android:text="00"
                      android:layout_column="0"
                      android:id="@+id/button11"
                      android:style="@style/CalculatorButton" />
                  <Button
                      android:text="0"
                      android:layout_column="1"
                      android:id="@+id/button12"
                      android:style="@style/CalculatorButton" />
                  <ImageButton
                      android:layout_column="2"
                      android:id="@+id/imageButton1"
                      android:style="@style/CalculatorButton"
                      android:src="@drawable/bitcoineuroswap"
                      android:scaleType="fitCenter" />
              </TableRow>
          </TableLayout>
      </LinearLayout>
  </LinearLayout>
  <LinearLayout
      android:orientation="vertical"
      android:minWidth="25px"
      android:minHeight="25px"
      android:layout_width="match_parent"
      android:id="@+id/linearLayout3"
      android:background="@color/orange"
      android:layout_weight="10" />
  </LinearLayout>

My styles:

<resources>

</resources>

Output (what i want - on the left, what i have got - on the right):

Body:
Suggestion: To design a keypad, you can very well use just Linearlayout with appropriate values for weightsum and weight attribute.

Wrap your image button inside a layout like this

 <RelativeLayout android:style="@style/CalculatorButton">
                        <ImageButton
                            android:id="@+id/imageButton1"
                            android:layout_centerInParent="true"
                            android:layout_width="20dp"
                            android:layout_height="20dp"
                            android:layout_column="2"
                            android:scaleType="fitCenter"
                            android:src="@drawable/hj" />
                    </RelativeLayout>

Original height of the image will be considered. So better give the width and height of the image.


问:
How to set thousands separator in Java?
How to set thousands separator in Java?

I have String representation of a BigDecimal that I want to format with a thousands separator and return as String.

答:
For <b>decimals</b>:  </p>

```<code>DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat dfDecimal = new DecimalFormat("###########0.00###");
dfDecimal.setDecimalFormatSymbols(symbols);
dfDecimal.setGroupingSize(3);
dfDecimal.setGroupingUsed(true);
System.out.println(dfDecimal.format(number));
</code>```

Title: How to set thousands separator in Java?

Body:
For decimals:

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat dfDecimal = new DecimalFormat("###########0.00###");
dfDecimal.setDecimalFormatSymbols(symbols);
dfDecimal.setGroupingSize(3);
dfDecimal.setGroupingUsed(true);
System.out.println(dfDecimal.format(number));


问:
Scala: short form of pattern matching that returns Boolean
I found myself writing something like this quite often:

```<code>a match {
  case `b` => // do stuff
  case _ => // do nothing
}
</code>```

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

```<code>if (a matches b) // do stuff
</code>```

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

答:
Patterns can also be used in for expressions. Your code sample

```<code>a match {
  case b => // do stuff
  case _ => // do nothing
}
</code>```

can then be expressed as

```<code>for(b <- Some(a)) //do stuff
</code>```

The trick is to wrap a to make it a valid enumerator. E.g. List(a) would also work, but I think Some(a) is closest to your intended meaning.

Body:
I found myself writing something like this quite often:

a match {
  case `b` => // do stuff
  case _ => // do nothing
}

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

if (a matches b) // do stuff

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

Body:
Patterns can also be used in for expressions. Your code sample

a match {
  case b => // do stuff
  case _ => // do nothing
}

can then be expressed as

for(b <- Some(a)) //do stuff

The trick is to wrap a to make it a valid enumerator. E.g. List(a) would also work, but I think Some(a) is closest to your intended meaning.