问:
How to make new decorators available within a class without explicitly importing them?
Is it possible to modify a class so as to make available a certain method decorator, without having to explicitly import it and without having to prefix it (@something.some_decorator):

```<code>class SomeClass:

    @some_decorator
    def some_method(self):
        pass
</code>```

I don't think this is possible with a class decorator, because that is applied too late. The option that seems more promising is using a metaclass, but I am unsure how, my guess is that I would have to have some_decorator be introduced into the namespace of SomeClass.

Thanks to @MartijnPieters for pointing out that staticmethod and classmethod are built-ins. I had expected them to be part of the type machinery.

To be clear, I don't have any explicit use-case for this, I am just curious as to whether this is at all possible.

ADDENDUM, now that the question has been answered. The original reason why I was looking beyond simply importing or defining a decorator locally, was that I had defined a decorator that would only work if a certain container attribute was initialised on an object, and I was looking for a way to tie enforcing this to the availability of the decorator. I ended up checking whether the attribute existed and if not initialising it within the decorator, which may very well be the lesser evil here.

答:
Yes, in Python 3 you can use the metaclass __prepare__ hook. It is expected to return a mapping, and it forms the basis of the local namespace for the class body:

```<code>def some_decorator(f):
    print(f'Decorating {f.__name__}')
    return f

class meta(type):
    @classmethod
    def __prepare__(mcls, name, bases, **kw):
        return {'some_decorator': some_decorator}

class SomeClass(metaclass=meta):
    @some_decorator
    def some_method(self):
        pass
</code>```

Running the above produces

```<code>Decorating some_method
</code>```

However, you should not use this. As the Zen of Python states: Explicit is better than implicit, and introducing magic names into your classes can easily lead to confusion and bugs. Importing a metaclass is no different than importing a decorator, you replaced one name with another.

A class decorator can still apply other decorators to methods on a class after the class body has been created. The @decorator syntax is just syntactic sugar for name = decorator(decorated_object), you can always apply a decorator later on by using name = decorator(name), or in a class context, as cls.name = decorator(cls.name). If you need to pick and choose which methods this should apply to, you could pick criteria like the method name, or attributes set on the method, or the docstring of the method, etc. Or just use the decorator directly on the methods.

Body:
Is it possible to modify a class so as to make available a certain method decorator, without having to explicitly import it and without having to prefix it (@something.some_decorator):

class SomeClass:

    @some_decorator
    def some_method(self):
        pass

I don't think this is possible with a class decorator, because that is applied too late. The option that seems more promising is using a metaclass, but I am unsure how, my guess is that I would have to have some_decorator be introduced into the namespace of SomeClass.

Thanks to @MartijnPieters for pointing out that staticmethod and classmethod are built-ins. I had expected them to be part of the type machinery.

To be clear, I don't have any explicit use-case for this, I am just curious as to whether this is at all possible.

ADDENDUM, now that the question has been answered. The original reason why I was looking beyond simply importing or defining a decorator locally, was that I had defined a decorator that would only work if a certain container attribute was initialised on an object, and I was looking for a way to tie enforcing this to the availability of the decorator. I ended up checking whether the attribute existed and if not initialising it within the decorator, which may very well be the lesser evil here.

Body:
Yes, in Python 3 you can use the metaclass __prepare__ hook. It is expected to return a mapping, and it forms the basis of the local namespace for the class body:

def some_decorator(f):
    print(f'Decorating {f.__name__}')
    return f

class meta(type):
    @classmethod
    def __prepare__(mcls, name, bases, **kw):
        return {'some_decorator': some_decorator}

class SomeClass(metaclass=meta):
    @some_decorator
    def some_method(self):
        pass

Running the above produces

Decorating some_method

However, you should not use this. As the Zen of Python states: Explicit is better than implicit, and introducing magic names into your classes can easily lead to confusion and bugs. Importing a metaclass is no different than importing a decorator, you replaced one name with another.

A class decorator can still apply other decorators to methods on a class after the class body has been created. The @decorator syntax is just syntactic sugar for name = decorator(decorated_object), you can always apply a decorator later on by using name = decorator(name), or in a class context, as cls.name = decorator(cls.name). If you need to pick and choose which methods this should apply to, you could pick criteria like the method name, or attributes set on the method, or the docstring of the method, etc. Or just use the decorator directly on the methods.


来源: stackexchange

问:
Printing certain values using Collections.frequency()
I have an array as follows:

```<code>int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
</code>```

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

```<code>ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);
</code>```

I then used a stream to loop through it and print the values using Collections.frequency.

```<code>dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });
</code>```

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

```<code>int check = Collections.frequency(list, key);
            if (check > 1) {
</code>```

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

答:
The complete example without initialising dup in a loop and calling Collections.frequency for every unique element once:

```<code>Integer[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
List<Integer> list = Arrays.asList(array);
Arrays.stream(array).collect(Collectors.toSet())
  .stream()
  .map(v -> new SimpleEntry<>(v, Collections.frequency(list, v)))
  .filter(v -> v.getValue() > 1)
  .forEach(v -> System.out.println(v.getKey() + ":" + v.getValue()));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array as follows:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);

I then used a stream to loop through it and print the values using Collections.frequency.

dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

int check = Collections.frequency(list, key);
            if (check > 1) {

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

Body:
The complete example without initialising dup in a loop and calling Collections.frequency for every unique element once:

Integer[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
List<Integer> list = Arrays.asList(array);
Arrays.stream(array).collect(Collectors.toSet())
  .stream()
  .map(v -> new SimpleEntry<>(v, Collections.frequency(list, v)))
  .filter(v -> v.getValue() > 1)
  .forEach(v -> System.out.println(v.getKey() + ":" + v.getValue()));


问:
How to get the output in a div when a textarea is modified?
I have used the below method to see the output whena textarea area is modified, it works fine.  But i would like to use the Codemirror as the textarea, when i insert any data in codemirror textarea then the output should appear the div .

```<code><script type="text/javascript">
function updateDisplay() {
document.getElementById("code").innerHTML =      document.getElementById("entry").value;
}
</script>

<textarea onkeyup="updateDisplay();" name="entry" id="entry" cols="1000" rows="500"></textarea>
<div name="code" id="code" ></div>
</code>```

CodeMirror

```<code> <link rel="stylesheet" href="http://codemirror.net/lib/codemirror.css">
<script src="http://codemirror.net/lib/codemirror.js"></script>
<script src="http://codemirror.net/mode/xml/xml.js"></script>
<script src="http://codemirror.net/mode/javascript/javascript.js"></script>
<script src="http://codemirror.net/mode/css/css.js"></script>
<script src="http://codemirror.net/mode/htmlmixed/htmlmixed.js"></script>

<textarea id="code" name="code">
<html style="color: green">
  <!-- this is a comment -->

<style type="text/css">
  h1 {font-family: comic sans; color: #f0f;}
  div {background: yellow !important;}
  body {
    max-width: 50em;
    margin: 1em 2em 1em 5em;
  }
</style>
</head>
 <body>

<script>
  function jsFunc(arg1, arg2) {
    if (arg1 && arg2) document.body.innerHTML = "achoo";
  }
 </script>
 </body>
</html>
</textarea></form>
<script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", tabMode: "indent"});
</script>
</code>```

答:
Following works with Codemirror v5.x

Listen editor's on "change" event, then call save() method to transfer the editor's value into the origin textarea.

```<code><script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", tabMode: "indent"});
  editor.on("change", function(cm){ cm.save() })
</script>
</code>```

Body:
I have used the below method to see the output whena textarea area is modified, it works fine.  But i would like to use the Codemirror as the textarea, when i insert any data in codemirror textarea then the output should appear the div .

<textarea onkeyup="updateDisplay();" name="entry" id="entry" cols="1000" rows="500"></textarea>

CodeMirror

 <link rel="stylesheet" href="http://codemirror.net/lib/codemirror.css">

<textarea id="code" name="code">

</textarea></form>

Body:
Following works with Codemirror v5.x

Listen editor's on "change" event, then call save() method to transfer the editor's value into the origin textarea.

<script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", tabMode: "indent"});
  editor.on("change", function(cm){ cm.save() })
</script>


问:
auto increment id with respect to the rest of the primary key
I have a table that looks like this:

```<code>| PK | Col Name | Type |
|----+----------+------|
| X  | ParentId | int
| X  | Id       | int
</code>```

I tried to set Id to be the identity, and ParentId is set on the parent table. What I was hoping the data would look like would be:

```<code>| ParentId | Id |
|----------+----|
| 1        | 1  |
| 1        | 2  |
| 1        | 3  |
| 2        | 1  |
| 2        | 2  |
| 3        | 1  |
</code>```

but instead it looks like:

```<code>| ParentId | Id |
|----------+----|
| 1        | 1  |
| 1        | 2  |
| 1        | 3  |
| 2        | 4  |
| 2        | 5  |
| 3        | 6  |
</code>```

which makes sense in hindsight. Is the desired effect achievable in some way?

答:
If you want to get the desired output from only the ParentId, i also suggest this, you can use this :

```<code>select ParentId,
ROW_NUMBER() OVER (PARTITION BY parentid order by parentid) as Id
from Foo
</code>```

SQL HERE

But if you still want to use in the table, you can create a INSTEAD OF INSERT trigger on your table, here is the trigger you can use :

```<code>create trigger dbo.trInsertFoo on dbo.Foo instead of insert
as begin
    insert into dbo.Foo
            (ParentId, Id)
    select  ParentId,
            Id =
            isnull( (select max(Id)
                    from    dbo.Foo
                    where   ParentId = i.ParentId), 0) +
            row_number() over (partition by ParentId order by (select 1))
    from    inserted i;
end;
</code>```

Simplified version of the above trigger

```<code>create trigger dbo.trInsertFoo on dbo.Foo instead of insert
as begin
    insert into dbo.Foo
            (ParentId, Id)
    select  ParentId,
            Id =
            (select isnull(max(Id), 0) + 1 from dbo.Foo where ParentId = i.ParentId)
    from    inserted i;
end;
</code>```

But this one will not work for batch insert like :

```<code>INSERT INTO Foo (ParentId) VALUES (1), (1), (1), (2), (2), (3)`
</code>```

Body:
I have a table that looks like this:

| PK | Col Name | Type |
|----+----------+------|
| X  | ParentId | int
| X  | Id       | int

I tried to set Id to be the identity, and ParentId is set on the parent table. What I was hoping the data would look like would be:

| ParentId | Id |
|----------+----|
| 1        | 1  |
| 1        | 2  |
| 1        | 3  |
| 2        | 1  |
| 2        | 2  |
| 3        | 1  |

but instead it looks like:

| ParentId | Id |
|----------+----|
| 1        | 1  |
| 1        | 2  |
| 1        | 3  |
| 2        | 4  |
| 2        | 5  |
| 3        | 6  |

which makes sense in hindsight. Is the desired effect achievable in some way?

Body:
If you want to get the desired output from only the ParentId, i also suggest this, you can use this :

select ParentId,
ROW_NUMBER() OVER (PARTITION BY parentid order by parentid) as Id
from Foo

SQL HERE

But if you still want to use in the table, you can create a INSTEAD OF INSERT trigger on your table, here is the trigger you can use :

create trigger dbo.trInsertFoo on dbo.Foo instead of insert
as begin
    insert into dbo.Foo
            (ParentId, Id)
    select  ParentId,
            Id =
            isnull( (select max(Id)
                    from    dbo.Foo
                    where   ParentId = i.ParentId), 0) +
            row_number() over (partition by ParentId order by (select 1))
    from    inserted i;
end;

Simplified version of the above trigger

create trigger dbo.trInsertFoo on dbo.Foo instead of insert
as begin
    insert into dbo.Foo
            (ParentId, Id)
    select  ParentId,
            Id =
            (select isnull(max(Id), 0) + 1 from dbo.Foo where ParentId = i.ParentId)
    from    inserted i;
end;

But this one will not work for batch insert like :

INSERT INTO Foo (ParentId) VALUES (1), (1), (1), (2), (2), (3)`


问:
Crashlytics : stuck on "Verifying Installation..." step
I want to use Crashlytics on my application. I followed every step but I'm stuck on "Verifying Installation..." step.

What is the problem ?

答: If you're adding a new app you need to be an Admin of your organization but you may just be a User.</p>


问:
Controlling default values in view from model - EF CORE
I've set the default for a Boolean in the model using both

```<code>    [DefaultValue(true)]
</code>```

and

```<code>public bool IsActive { get; set; } = true;
</code>```

and for good measure I've added

```<code>    modelBuilder.Entity<modelName>().Property(p => p.IsActive).HasDefaultValue(true);
</code>```

That all works nicely and my database table has the correct "Default value or binding".   In my Create view I want the default property to be used but can't find out how to use the model's default properties in the view. Using

```<code><input asp-for="IsActive"  class="form-control" checked="checked"/>
</code>```

works, but that's me hardcoding the checked="checked" value myself. How do I read the model's default value in the view?

Edited for requested code, the model is

```<code>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace securitytrials.Models {
    public class CaseType {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int TheID { get; set; }
        [Display(Name = "Active")]
        public bool IsActive { get; set; } = true;
    }
}
</code>```

the action method is the default generated by the template.

```<code>public IActionResult Create() {
    return View();
}
</code>```

Didn't include them as there's not much there but the defaults.
The DbContext.OnModelCreating is just

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity<CaseType>().Property(p => p.IsActive).HasDefaultValue(true);
    }
</code>```

答:
DefaultValue doesn't actually do anything. I can be utilized by code generators in certain situations, but largely in the context of your web application, it's completely meaningless. As the docs detail:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

HasDefaultValue merely sets the DEFAULT for the column, so you may need that as well, if you want the actual table schema to reflect the default, but the only thing that really helps your code is:

```<code>public bool IsActive { get; set; } = true;
</code>```

It's not entirely clear what you're asking. As there should be no issue with that alone in an input displaying that default value. In other words, the following code:

```<code><input asp-for="IsActive" class="form-control" />
</code>```

Will generate:

```<code><input type="textbox" class="form-control" checked="checked" />
</code>```

If it's not, then there's some issue with your model. Either you're confused on which class you've added the default value to, or something else in your code is changing that value before it hits your view. However, without more code to work with, like your action method, it's impossible to say.

Body:
I've set the default for a Boolean in the model using both

    [DefaultValue(true)]

and

public bool IsActive { get; set; } = true;

and for good measure I've added

    modelBuilder.Entity<modelName>().Property(p => p.IsActive).HasDefaultValue(true);

That all works nicely and my database table has the correct "Default value or binding".   In my Create view I want the default property to be used but can't find out how to use the model's default properties in the view. Using

<input asp-for="IsActive"  class="form-control" checked="checked"/>

works, but that's me hardcoding the checked="checked" value myself. How do I read the model's default value in the view?

Edited for requested code, the model is

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace securitytrials.Models {
    public class CaseType {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int TheID { get; set; }
        [Display(Name = "Active")]
        public bool IsActive { get; set; } = true;
    }
}

the action method is the default generated by the template.

public IActionResult Create() {
    return View();
}

Didn't include them as there's not much there but the defaults.
The DbContext.OnModelCreating is just

protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity<CaseType>().Property(p => p.IsActive).HasDefaultValue(true);
    }

Body:
DefaultValue doesn't actually do anything. I can be utilized by code generators in certain situations, but largely in the context of your web application, it's completely meaningless. As the docs detail:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

HasDefaultValue merely sets the DEFAULT for the column, so you may need that as well, if you want the actual table schema to reflect the default, but the only thing that really helps your code is:

public bool IsActive { get; set; } = true;

It's not entirely clear what you're asking. As there should be no issue with that alone in an input displaying that default value. In other words, the following code:

<input asp-for="IsActive" class="form-control" />

Will generate:

<input type="textbox" class="form-control" checked="checked" />

If it's not, then there's some issue with your model. Either you're confused on which class you've added the default value to, or something else in your code is changing that value before it hits your view. However, without more code to work with, like your action method, it's impossible to say.


问:
FInding the webkit version used in Android browser?
Is there a way to tell which version of the webkit software is used in the Android browser on some specific handset?

What would be really great is if there is a URL you can browse to get that information.   But any other way would be good too.   If you know the webkit version, you know how much html5 suport to expect.

答:
Also we can use </p>

```<code>PackageInfo pi = getPackageManager().getPackageInfo("com.google.android.webview", 0);
String version = pi.versionName;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Also we can use

PackageInfo pi = getPackageManager().getPackageInfo("com.google.android.webview", 0);
String version = pi.versionName;


问:
StringFormat in XAML, WPF : Currency Formatting
How can i obtain currency formatting according to my country i.e indian rupee, INR or Rs ??

Please tell me the way to achieve this ??
Right now when i use StringFormat="{}{0:C}", "$" is being used

I have gone through this link and i am able to achieve the desired result but i am worried about using this in my project. Is this code safe ??

What does this line mean in the above link "when you test functionality related to settings change it’s important you start the program directly from a folder window, if you run it from within Visual Studio or any other program you may get incorrect results."

答:
Or you can set your current thread to the right culture, so you will use it everywhere in your application:</p>

```<code>Thread.CurrentThread.CurrentUICulture = new CultureInfo("hi-IN");
</code>```

Body:
Or you can set your current thread to the right culture, so you will use it everywhere in your application:

Thread.CurrentThread.CurrentUICulture = new CultureInfo("hi-IN");


问:
Showing converting error for varchar to numeric
I am getting this error

Msg 8114, Level 16, State 5, Line 13

  Error converting data type varchar to numeric.

This is my code:

```<code>SELECT DISTINCT
                      DI.DealName AS 'Deal Name',
    DI.OfferingType AS 'Offering Type',
    DI.Date AS 'Date',
    DI.ClassName AS 'Class',
    ISNULL(Bench,'-') AS 'BM',
    ISNULL(Guidance,'-') AS 'Guid',
    DI.Industry AS 'Industry',
    CAST( (ISNULL(DI.AverageLife,0)) AS VARCHAR(20)) AS 'WAL',CAST(  ISNULL(DI.ClassSize,0) AS VARCHAR(20)) AS 'Balance',CAST(   REPLACE(ISNULL(DI.Coupon,0),'%','') AS VARCHAR(20)) AS 'Coupon',
       CAST(  CASE WHEN CAST(REPLACE(ISNULL(DI.PX2,0),'%','') AS DECIMAL(18,5)) = 0.00 THEN (CASE WHEN ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) = 0 THEN (CASE WHEN (ISNULL(DI.Coupon,0)+'cpn' = 'cpn' OR ISNULL(DI.Coupon,0)+'cpn' = '0cpn') THEN '-' ELSE (ISNULL(DI.Coupon,0)+'cpn')END)ELSE CAST(ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(15))+'%yld' END) ELSE (ISNULL(DI.PX,0)) END AS VARCHAR(20)) AS 'Spread',  CAST(  ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(20)) AS 'Yield', CAST(  CASE WHEN LTRIM(RTRIM(DI.Dollar_Px)) = '' THEN 0.00 ELSE CAST(ISNULL(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(Dollar_Px)),CHAR(10),''),CHAR(13),''),'-',''),'/',''),' ',''),'%cpn',''),0) AS DECIMAL(18,5)) END AS VARCHAR(20)) AS 'Dollar_Px',  ISNULL(Notes,'') AS Notes,
           CAST((FRM.Rating + '/' + KBRARM.Rating) AS VARCHAR(15)) AS 'Rating'  FROM DI_DealIssuancePost DI
         INNER JOIN DI_CompanyRatingMapping MRM ON MRM.CompanyRatingMappingID = DI.Mdy                   INNER JOIN DI_CompanyRatingMapping SPRM ON SPRM.CompanyRatingMappingID = DI.S_P
         INNER JOIN DI_CompanyRatingMapping FRM ON FRM.CompanyRatingMappingID = DI.Fitch
         INNER JOIN DI_CompanyRatingMapping DBRSRM ON DBRSRM.CompanyRatingMappingID = DI.DBRS                 INNER JOIN DI_CompanyRatingMapping KBRARM ON KBRARM.CompanyRatingMappingID = DI.KBRA

         INNER JOIN DI_WeeklySectors DIWeekly ON DI.Industry = DIWeekly.Sector

        WHERE DI.IsDeleted = 0
          AND MRM.IsDeleted = 0
          AND SPRM.IsDeleted = 0
          AND FRM.IsDeleted = 0
          AND DBRSRM.IsDeleted = 0
          AND KBRARM.IsDeleted = 0
          AND DI.Date IS NOT NULL
          AND (CONVERT(DATETIME,DI.Date ,101) >= CONVERT(DATETIME,@StartDate,101))
          AND (CONVERT(DATETIME,DI.Date ,101) <= CONVERT(DATETIME,@EndDate,101)) AND DI.CurrencyID IN (SELECT * FROM CsvToTable(@Currency)) ORDER BY DI.Date desc
</code>```

Msg 8114, Level 16, State 5, Line 13
Error converting data type varchar to numeric.

And i Can find that here is an error

```<code> CAST(  CASE WHEN CAST(REPLACE(ISNULL(DI.PX2,0),'%','') AS DECIMAL(18,5)) = 0.00 THEN (CASE WHEN ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) = 0 THEN (CASE WHEN (ISNULL(DI.Coupon,0)+'cpn' = 'cpn' OR ISNULL(DI.Coupon,0)+'cpn' = '0cpn') THEN '-' ELSE (ISNULL(DI.Coupon,0)+'cpn')END)ELSE CAST(ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(15))+'%yld' END) ELSE (ISNULL(DI.PX,0)) END AS VARCHAR(20)) AS 'Spread',  CAST(  ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(20)) AS 'Yield', CAST(  CASE WHEN LTRIM(RTRIM(DI.Dollar_Px)) = '' THEN 0.00 ELSE CAST(ISNULL(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(Dollar_Px)),CHAR(10),''),CHAR(13),''),'-',''),'/',''),' ',''),'%cpn',''),0) AS DECIMAL(18,5)) END AS VARCHAR(20)) AS 'Dollar_Px',  ISNULL(Notes,'') AS Notes,
</code>```

some one help to solve this error

答:
Here is an error:

```<code>(ISNULL(DI.Coupon,0)+''cpn'' = ''cpn'' OR ISNULL(DI.Coupon,0)+''cpn'' = ''0c

pn'') THEN
</code>```

Your Coupon is varchar, but if it's NULL you use 0 instead of it.
You should use '0' as it's string, not integer, in your '0cpn'.

So it should be

```<code>(ISNULL(DI.Coupon,''0'')+''cpn'' = ''cpn'' OR ISNULL(DI.Coupon,''0'')+''cpn'' = ''0c

pn'') THEN
</code>```

Body:
I am getting this error

Msg 8114, Level 16, State 5, Line 13

  Error converting data type varchar to numeric.

This is my code:

SELECT DISTINCT
                      DI.DealName AS 'Deal Name',
    DI.OfferingType AS 'Offering Type',
    DI.Date AS 'Date',
    DI.ClassName AS 'Class',
    ISNULL(Bench,'-') AS 'BM',
    ISNULL(Guidance,'-') AS 'Guid',
    DI.Industry AS 'Industry',
    CAST( (ISNULL(DI.AverageLife,0)) AS VARCHAR(20)) AS 'WAL',CAST(  ISNULL(DI.ClassSize,0) AS VARCHAR(20)) AS 'Balance',CAST(   REPLACE(ISNULL(DI.Coupon,0),'%','') AS VARCHAR(20)) AS 'Coupon',
       CAST(  CASE WHEN CAST(REPLACE(ISNULL(DI.PX2,0),'%','') AS DECIMAL(18,5)) = 0.00 THEN (CASE WHEN ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) = 0 THEN (CASE WHEN (ISNULL(DI.Coupon,0)+'cpn' = 'cpn' OR ISNULL(DI.Coupon,0)+'cpn' = '0cpn') THEN '-' ELSE (ISNULL(DI.Coupon,0)+'cpn')END)ELSE CAST(ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(15))+'%yld' END) ELSE (ISNULL(DI.PX,0)) END AS VARCHAR(20)) AS 'Spread',  CAST(  ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(20)) AS 'Yield', CAST(  CASE WHEN LTRIM(RTRIM(DI.Dollar_Px)) = '' THEN 0.00 ELSE CAST(ISNULL(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(Dollar_Px)),CHAR(10),''),CHAR(13),''),'-',''),'/',''),' ',''),'%cpn',''),0) AS DECIMAL(18,5)) END AS VARCHAR(20)) AS 'Dollar_Px',  ISNULL(Notes,'') AS Notes,
           CAST((FRM.Rating + '/' + KBRARM.Rating) AS VARCHAR(15)) AS 'Rating'  FROM DI_DealIssuancePost DI
         INNER JOIN DI_CompanyRatingMapping MRM ON MRM.CompanyRatingMappingID = DI.Mdy                   INNER JOIN DI_CompanyRatingMapping SPRM ON SPRM.CompanyRatingMappingID = DI.S_P
         INNER JOIN DI_CompanyRatingMapping FRM ON FRM.CompanyRatingMappingID = DI.Fitch
         INNER JOIN DI_CompanyRatingMapping DBRSRM ON DBRSRM.CompanyRatingMappingID = DI.DBRS                 INNER JOIN DI_CompanyRatingMapping KBRARM ON KBRARM.CompanyRatingMappingID = DI.KBRA

         INNER JOIN DI_WeeklySectors DIWeekly ON DI.Industry = DIWeekly.Sector

        WHERE DI.IsDeleted = 0
          AND MRM.IsDeleted = 0
          AND SPRM.IsDeleted = 0
          AND FRM.IsDeleted = 0
          AND DBRSRM.IsDeleted = 0
          AND KBRARM.IsDeleted = 0
          AND DI.Date IS NOT NULL
          AND (CONVERT(DATETIME,DI.Date ,101) >= CONVERT(DATETIME,@StartDate,101))
          AND (CONVERT(DATETIME,DI.Date ,101) <= CONVERT(DATETIME,@EndDate,101)) AND DI.CurrencyID IN (SELECT * FROM CsvToTable(@Currency)) ORDER BY DI.Date desc

Msg 8114, Level 16, State 5, Line 13
Error converting data type varchar to numeric.

And i Can find that here is an error

 CAST(  CASE WHEN CAST(REPLACE(ISNULL(DI.PX2,0),'%','') AS DECIMAL(18,5)) = 0.00 THEN (CASE WHEN ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) = 0 THEN (CASE WHEN (ISNULL(DI.Coupon,0)+'cpn' = 'cpn' OR ISNULL(DI.Coupon,0)+'cpn' = '0cpn') THEN '-' ELSE (ISNULL(DI.Coupon,0)+'cpn')END)ELSE CAST(ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(15))+'%yld' END) ELSE (ISNULL(DI.PX,0)) END AS VARCHAR(20)) AS 'Spread',  CAST(  ISNULL(CAST(DI.Yield * 100 AS DECIMAL(18,3)),0) AS VARCHAR(20)) AS 'Yield', CAST(  CASE WHEN LTRIM(RTRIM(DI.Dollar_Px)) = '' THEN 0.00 ELSE CAST(ISNULL(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(Dollar_Px)),CHAR(10),''),CHAR(13),''),'-',''),'/',''),' ',''),'%cpn',''),0) AS DECIMAL(18,5)) END AS VARCHAR(20)) AS 'Dollar_Px',  ISNULL(Notes,'') AS Notes,

some one help to solve this error

Body:
Here is an error:

(ISNULL(DI.Coupon,0)+''cpn'' = ''cpn'' OR ISNULL(DI.Coupon,0)+''cpn'' = ''0c

pn'') THEN

Your Coupon is varchar, but if it's NULL you use 0 instead of it.
You should use '0' as it's string, not integer, in your '0cpn'.

So it should be

(ISNULL(DI.Coupon,''0'')+''cpn'' = ''cpn'' OR ISNULL(DI.Coupon,''0'')+''cpn'' = ''0c

pn'') THEN


问:
EF add-migration throwing System.OutOfMemoryException
When I try to add a migration file through PM I get an out of memory exception. Anyone else had this problem before and happen to know how to fix it? So far I have tried re installing VS 2013 to no avail

Monitoring my memory usage I have 12GB available, and it is using less than 8 while the add migration is running, so should be plenty available. Below is the output

```<code>PM> add-migration test
</code>```

System.OutOfMemoryException: Exception of type
  'System.OutOfMemoryException' was thrown.    at
  System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)

  at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
  runner)    at
  System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String
  migrationName, String language, String rootNamespace, Boolean
  ignoreChanges)    at
  System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name,
  Boolean force, Boolean ignoreChanges)    at
  System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
  at
  System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action
  command) Exception of type 'System.OutOfMemoryException' was thrown.

答: I just had this happen to me.  I slowly retraced my steps, and removed DbSets in the dbContext one-by-one until it worked again.  </p>

Body:
When I try to add a migration file through PM I get an out of memory exception. Anyone else had this problem before and happen to know how to fix it? So far I have tried re installing VS 2013 to no avail

Monitoring my memory usage I have 12GB available, and it is using less than 8 while the add migration is running, so should be plenty available. Below is the output

PM> add-migration test

System.OutOfMemoryException: Exception of type
  'System.OutOfMemoryException' was thrown.    at
  System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)

  at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
  runner)    at
  System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String
  migrationName, String language, String rootNamespace, Boolean
  ignoreChanges)    at
  System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name,
  Boolean force, Boolean ignoreChanges)    at
  System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
  at
  System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action
  command) Exception of type 'System.OutOfMemoryException' was thrown.


问:
Cross-platform high-accuracy time in python
I'm writing a game that should run on several platforms.  I need a good time accuracy on all platforms.

I am not interested in knowing the time of the day, what matters to me is the elapsed time between two calls.

After reading the docs, time.time appears better on Linux and time.clock better on Windows.
I thought of writing something like this:

```<code>import os
import time
__all__ = ['hrtime']

platform = os.name
if platform == 'posix':
    hrtime = time.time
elif platform == 'nt':
    hrtime = time.clock
else:
    # 'os2', 'ce', 'java', 'riscos'
    raise ValueError("I have no idea what I'm doing.")
</code>```

But what about the other platforms?  Does MacOS return {posix}?  What about cygwin, is that a Linux or a Windows?  What is 'ce'?  Should I even care about these platforms at all?

Another option could be to use the SDL time from pygame.  This seems to have a millisecond accuracy on every platform.  Since I'm using SDL for the rendering I don't mind using that.  However, I am working on network code now, and using the SDL time in my network code feels a bit strange.

Question: what would you rather use, and why?

答:
For the best measure of elapsed time (since Python 3.3), use time.perf_counter.

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

Body:
I'm writing a game that should run on several platforms.  I need a good time accuracy on all platforms.

I am not interested in knowing the time of the day, what matters to me is the elapsed time between two calls.

After reading the docs, time.time appears better on Linux and time.clock better on Windows.
I thought of writing something like this:

import os
import time
__all__ = ['hrtime']

platform = os.name
if platform == 'posix':
    hrtime = time.time
elif platform == 'nt':
    hrtime = time.clock
else:
    # 'os2', 'ce', 'java', 'riscos'
    raise ValueError("I have no idea what I'm doing.")

But what about the other platforms?  Does MacOS return {posix}?  What about cygwin, is that a Linux or a Windows?  What is 'ce'?  Should I even care about these platforms at all?

Another option could be to use the SDL time from pygame.  This seems to have a millisecond accuracy on every platform.  Since I'm using SDL for the rendering I don't mind using that.  However, I am working on network code now, and using the SDL time in my network code feels a bit strange.

Question: what would you rather use, and why?


问:
manifest.xml XML Parsing Error: not well-formed
I'm a newbie, I use the android sdk on ubuntu and downloaded a few free android apps, when I tried to load them onto the sdk using eclipse, it gives an XML parser error. I am unable to view the source code of the application too.

If I try opening the xml file using a browser, I get

```<code>XML Parsing Error: not well-formed
Location: file:///home/Downloads/apks/BlueFTP.apk_FILES/AndroidManifest.xml
Line Number 1, Column 1:
</code>```

Has anyone encountered such a problem? Any solutions please?

Content of manifest.xml

```<code>  <    ü      >                        4   @   N   Z   x   ž   ²   À   Ô   æ   ô     6  R  p  Œ  ¤  ¶      $  8  b  n  ˆ  œ  ¬  Ê  Ú    &  j  z  ¼  ô  >  J  T  v  ˆ     ¼    l  ~  Ô  *  >  ˆ  Ô  ê    4  H  j  ¤  à  (  l  Â   v e r s i o n N a m e    v e r s i o n C o d e    i c o n    l a b e l    n a m e
 c o n f i g C h a n g e s    s c r e e n O r i e n t a t i o n    m i m e T y p e    t h e m e    e x p o r t e d    e n a b l e d    v a l u e
 m i n S d k V e r s i o n    t a r g e t S d k V e r s i o n    s m a l l S c r e e n s
 n o r m a l S c r e e n s    l a r g e S c r e e n s
 a n y D e n s i t y    a n d r o i d   * h t t p : / / s c h e m a s . a n d r o i d . c o m / a p k / r e s / a n d r o i d        p a c k a g e    m a n i f e s t    i t . m e d i e v a l . b l u e f t p    2 . 5 0    a p p l i c a t i o n    a c t i v i t y    . A M a i n
 i n t e n t - f i l t e r    a c t i o n    a n d r o i d . i n t e n t . a c t i o n . M A I N    c a t e g o r y     a n d r o i d . i n t e n t . c a t e g o r y . L A U N C H E R    . A S e n d    a n d r o i d . i n t e n t . c a t e g o r y . D E F A U L T    a n d r o i d . i n t e n t . a c t i o n . S E N D   # a n d r o i d . i n t e n t . a c t i o n . S E N D _ M U L T I P L E    d a t a    * / *    . A C o n t a c t P i c k e r    . A A b o u t
 . A S e t t i n g s    . B u g s M e s s a g e   * . b l u e t o o t h _ s e r v e r s . o p p _ s e r v e r . N o t i f y M e x O P P   * . b l u e t o o t h _ s e r v e r s . f t p _ s e r v e r . N o t i f y M e x F T P    s e r v i c e   ) . b l u e t o o t h _ s e r v e r s . o p p _ s e r v e r . O P P _ S e r v i c e   ) . b l u e t o o t h _ s e r v e r s . f t p _ s e r v e r . F T P _ S e r v i c e    r e c e i v e r   # . b l u e t o o t h _ s e r v e r s . S e r v i c e s L a u n c h e r   $ a n d r o i d . i n t e n t . a c t i o n . B O O T _ C O M P L E T E D        m e t a - d a t a    A D M O B _ P U B L I S H E R _ I D    a 1 4 a a e 1 d 0 8 3 a 7 1 0    u s e s - s d k    u s e s - p e r m i s s i o n    a n d r o i d . p e r m i s s i o n . I N T E R N E T    a n d r o i d . p e r m i s s i o n . B L U E T O O T H   " a n d r o i d . p e r m i s s i o n . B L U E T O O T H _ A D M I N     a n d r o i d . p e r m i s s i o n . R E A D _ C O N T A C T S   ) a n d r o i d . p e r m i s s i o n . W R I T E _ E X T E R N A L _ S T O R A G E    s u p p o r t s - s c r e e n s     € P        &     $ p„…†l        ÿÿÿÿ       `      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ                    ÿÿÿÿ            L      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ         ÿÿÿÿ  ,  t      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ                       ÿ
</code>```

答:
Do you have the APK?

try uncompressing it, and paste the content of the Manifest.xml file.

Secondly, where are you getting the errors?
When you run the app in the phone? or in the eclipse? if in eclipse, how did you figure out to create a project out of an APK only? or do you have the full project? if you have the full project, then you might be having the Manifest file as well, so just paste that file's contents here and let us check

Sorry for the outburst of questions, though.

Body:
I'm a newbie, I use the android sdk on ubuntu and downloaded a few free android apps, when I tried to load them onto the sdk using eclipse, it gives an XML parser error. I am unable to view the source code of the application too.

If I try opening the xml file using a browser, I get

XML Parsing Error: not well-formed
Location: file:///home/Downloads/apks/BlueFTP.apk_FILES/AndroidManifest.xml
Line Number 1, Column 1:

Has anyone encountered such a problem? Any solutions please?

Content of manifest.xml

  <    ü      >                        4   @   N   Z   x   ž   ²   À   Ô   æ   ô     6  R  p  Œ  ¤  ¶      $  8  b  n  ˆ  œ  ¬  Ê  Ú    &  j  z  ¼  ô  >  J  T  v  ˆ     ¼    l  ~  Ô  *  >  ˆ  Ô  ê    4  H  j  ¤  à  (  l  Â   v e r s i o n N a m e    v e r s i o n C o d e    i c o n    l a b e l    n a m e
 c o n f i g C h a n g e s    s c r e e n O r i e n t a t i o n    m i m e T y p e    t h e m e    e x p o r t e d    e n a b l e d    v a l u e
 m i n S d k V e r s i o n    t a r g e t S d k V e r s i o n    s m a l l S c r e e n s
 n o r m a l S c r e e n s    l a r g e S c r e e n s
 a n y D e n s i t y    a n d r o i d   * h t t p : / / s c h e m a s . a n d r o i d . c o m / a p k / r e s / a n d r o i d        p a c k a g e    m a n i f e s t    i t . m e d i e v a l . b l u e f t p    2 . 5 0    a p p l i c a t i o n    a c t i v i t y    . A M a i n
 i n t e n t - f i l t e r    a c t i o n    a n d r o i d . i n t e n t . a c t i o n . M A I N    c a t e g o r y     a n d r o i d . i n t e n t . c a t e g o r y . L A U N C H E R    . A S e n d    a n d r o i d . i n t e n t . c a t e g o r y . D E F A U L T    a n d r o i d . i n t e n t . a c t i o n . S E N D   # a n d r o i d . i n t e n t . a c t i o n . S E N D _ M U L T I P L E    d a t a    * / *    . A C o n t a c t P i c k e r    . A A b o u t
 . A S e t t i n g s    . B u g s M e s s a g e   * . b l u e t o o t h _ s e r v e r s . o p p _ s e r v e r . N o t i f y M e x O P P   * . b l u e t o o t h _ s e r v e r s . f t p _ s e r v e r . N o t i f y M e x F T P    s e r v i c e   ) . b l u e t o o t h _ s e r v e r s . o p p _ s e r v e r . O P P _ S e r v i c e   ) . b l u e t o o t h _ s e r v e r s . f t p _ s e r v e r . F T P _ S e r v i c e    r e c e i v e r   # . b l u e t o o t h _ s e r v e r s . S e r v i c e s L a u n c h e r   $ a n d r o i d . i n t e n t . a c t i o n . B O O T _ C O M P L E T E D        m e t a - d a t a    A D M O B _ P U B L I S H E R _ I D    a 1 4 a a e 1 d 0 8 3 a 7 1 0    u s e s - s d k    u s e s - p e r m i s s i o n    a n d r o i d . p e r m i s s i o n . I N T E R N E T    a n d r o i d . p e r m i s s i o n . B L U E T O O T H   " a n d r o i d . p e r m i s s i o n . B L U E T O O T H _ A D M I N     a n d r o i d . p e r m i s s i o n . R E A D _ C O N T A C T S   ) a n d r o i d . p e r m i s s i o n . W R I T E _ E X T E R N A L _ S T O R A G E    s u p p o r t s - s c r e e n s     € P        &     $ p„…†l        ÿÿÿÿ       `      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ                    ÿÿÿÿ            L      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ         ÿÿÿÿ  ,  t      ÿÿÿÿÿÿÿÿ                  ÿÿÿÿ                       ÿ


问:
I'm trying to write a code the takes two dimensional array "Sudoku" and arrange them into blocks
I'm trying to write a code the takes two dimensional array "Sudoku"
(matrix.length * matrix.length) and I should check if the matrix is (n^2 * n^2) and a number (n) and I should arrange the rows into blocks (n * n). Any suggestions?
if any body can do it if 4 "fors" i will be more than happy

```<code>public static int[][] blocks(int[][] matrix, int sqrtN) {
    int [][] returnedMatrix = new int [matrix.length][matrix.length];
    if (matrix.length !=  Math.pow(sqrtN, 2))
            throw new RuntimeException("Matrix length is not" + Math.pow(sqrtN, 2 ));
    for(int i=0 ; i <= matrix.length ;i=i+sqrtN) {
        for(int j=sqrtN; j <= matrix.length;j=j+1) {
            int temporarily =

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

for exsample

```<code>int[][] matrix1 = {{11,12,13,14},
{15,16,17,18},
{19,20,21,22},

{23,24,25,26}} ;

int[][] matBlocks1 = blocks (matrix1, 2) ;
/*
* matBlocks1 = {{11, 12, 15, 16},
* {13, 14, 17, 18},
* {19, 20, 23, 24},
* {21, 22, 25, 26}}
*/
</code>```

答:
The formulas you're looking for are:

```<code>int r = (i/sqrtN)*sqrtN+j/sqrtN;
int c = (i%sqrtN)*sqrtN+j%sqrtN;
returnedMatrix[i][j] = matrix[r][c];
</code>```

Full code with tests:

```<code>public static int[][] blocks(int[][] matrix, int sqrtN) {
    int n = matrix.length;
    if (n != Math.pow(sqrtN, 2))
        throw new RuntimeException("Matrix length is not" + Math.pow(sqrtN, 2));
    int[][] returnedMatrix = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int r = (i/sqrtN)*sqrtN+j/sqrtN;
            int c = (i%sqrtN)*sqrtN+j%sqrtN;
            returnedMatrix[i][j] = matrix[r][c];
        }
    }
    return returnedMatrix;
}

public static void print(int[][] matrix) {
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
    }
    System.out.println();
}

public static void main(String args[]) {
    int[][] matrix4 = {
        {1,1,2,2},
        {1,1,2,2},
        {3,3,4,4},
        {3,3,4,4}
    };
    print(blocks(matrix4, 2));

    int[][] matrix9 = {
        {1,1,1,2,2,2,3,3,3},
        {1,1,1,2,2,2,3,3,3},
        {1,1,1,2,2,2,3,3,3},
        {4,4,4,5,5,5,6,6,6},
        {4,4,4,5,5,5,6,6,6},
        {4,4,4,5,5,5,6,6,6},
        {7,7,7,8,8,8,9,9,9},
        {7,7,7,8,8,8,9,9,9},
        {7,7,7,8,8,8,9,9,9}
    };
    print(blocks(matrix9, 3));
}
</code>```

Output:

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

1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
</code>```

Body:
I'm trying to write a code the takes two dimensional array "Sudoku"
(matrix.length * matrix.length) and I should check if the matrix is (n^2 * n^2) and a number (n) and I should arrange the rows into blocks (n * n). Any suggestions?
if any body can do it if 4 "fors" i will be more than happy

public static int[][] blocks(int[][] matrix, int sqrtN) {
    int [][] returnedMatrix = new int [matrix.length][matrix.length];
    if (matrix.length !=  Math.pow(sqrtN, 2))
            throw new RuntimeException("Matrix length is not" + Math.pow(sqrtN, 2 ));
    for(int i=0 ; i <= matrix.length ;i=i+sqrtN) {
        for(int j=sqrtN; j <= matrix.length;j=j+1) {
            int temporarily =

        }
    }
    return returnedMatrix;
}

for exsample

int[][] matrix1 = {{11,12,13,14},
{15,16,17,18},
{19,20,21,22},

{23,24,25,26}} ;

int[][] matBlocks1 = blocks (matrix1, 2) ;
/*
* matBlocks1 = {{11, 12, 15, 16},
* {13, 14, 17, 18},
* {19, 20, 23, 24},
* {21, 22, 25, 26}}
*/

Body:
The formulas you're looking for are:

int r = (i/sqrtN)*sqrtN+j/sqrtN;
int c = (i%sqrtN)*sqrtN+j%sqrtN;
returnedMatrix[i][j] = matrix[r][c];

Full code with tests:

public static int[][] blocks(int[][] matrix, int sqrtN) {
    int n = matrix.length;
    if (n != Math.pow(sqrtN, 2))
        throw new RuntimeException("Matrix length is not" + Math.pow(sqrtN, 2));
    int[][] returnedMatrix = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int r = (i/sqrtN)*sqrtN+j/sqrtN;
            int c = (i%sqrtN)*sqrtN+j%sqrtN;
            returnedMatrix[i][j] = matrix[r][c];
        }
    }
    return returnedMatrix;
}

public static void print(int[][] matrix) {
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
    }
    System.out.println();
}

public static void main(String args[]) {
    int[][] matrix4 = {
        {1,1,2,2},
        {1,1,2,2},
        {3,3,4,4},
        {3,3,4,4}
    };
    print(blocks(matrix4, 2));

    int[][] matrix9 = {
        {1,1,1,2,2,2,3,3,3},
        {1,1,1,2,2,2,3,3,3},
        {1,1,1,2,2,2,3,3,3},
        {4,4,4,5,5,5,6,6,6},
        {4,4,4,5,5,5,6,6,6},
        {4,4,4,5,5,5,6,6,6},
        {7,7,7,8,8,8,9,9,9},
        {7,7,7,8,8,8,9,9,9},
        {7,7,7,8,8,8,9,9,9}
    };
    print(blocks(matrix9, 3));
}

Output:

1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4

1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9


问:
Choose folders to be ignored during search in VS Code
Right now when I use ⌘+O to search for files, the fuzzy matching appears to operate over all files in the current project. Unfortunately, this includes a number of files from build and vendor directories. So, for instance, if I want to search for all JavaScript files and do ⌘+O and type .js in, the file and symbol results include around 1500 hits and all of them except the two ones are complete noise.

Is there a way to specify certain directories to be ignored for purpose of search?

答:
After you setup the search.exclude and file.exclude mentioned on the previous answers, run the command  "Clear Editor History" (Use the Command Palette to do that - CTRL + SHIFT + P).

Only after that the excluded files will not appear on your quick open menu.

Update: You can run the command "Clear Command History" too. I forgot about that.

ContentLicense: CC BY-SA 4.0


问:
Dynamic SQL Procedure with Pivot displaying counts based on Date Range

I have a table which contains multiple user entries.
I want to pull counts of user entries based on date range passed to a stored procedure.

start date: 11/9/2017
end date: 11/11/2017

However the response needs to be dynamic based on amount of days in the date range.

Here is a desired format:

答:
If you are using SQL Server, you could try it with PIVOT:</p>

```<code>SELECT *
FROM
(SELECT userID, userName, EntryDateTime
 FROM t) src
PIVOT
(COUNT(userID)
 FOR EntryDateTime IN (['2017-11-09'], ['2017-11-10'], ['2017-11-11'])) pvt
</code>```

Body:
If you are using SQL Server, you could try it with PIVOT:

SELECT *
FROM
(SELECT userID, userName, EntryDateTime
 FROM t) src
PIVOT
(COUNT(userID)
 FOR EntryDateTime IN (['2017-11-09'], ['2017-11-10'], ['2017-11-11'])) pvt


问:
Publish .NET Standard to IIS throws 403.14 error
I have published multiple .NET Core projects through VSTS to IIS and had no problems. However when I try to add a .NET Standard project I get a 403.14 - Forbidden error page. If I try and type in a specific route for the API to get a response it throws a 404 - Not Found error page.

I am using .NET Framework 4.6.1 which is also installed on my my IIS 8.0 server.

Is there any way to debug this issue or a way of fixing this issue?

答: I was pointing to the wrong location on the server. I was pointing to the bin folder when I needed to be pointing to the project folder. Thanks for the help.</p>


问:
Outdated UI automation tree
I am trying programming an automated tester application using the new native Microsoft UI Automation interface 3.0 (in VC++ 2010, Win7). The Application Under Test (AUT) is a WPF application.

Almost everything works fine... I can install event handlers, navigate through the tree, search elements using various conditions and control the found elements using their patterns.

But yesterday I found a behaviour that leaves me despaired: The UIA tree of my AUT simply is not updated after switching its GUI main panel by clicking one of its main menu buttons.

After clicking the main menu button, I can see the new widgets in the AUT's GUI but the UIA tree still contains the controls that have been there before clicking the main menu button. The (outdated) UIA tree can be still completely read using search functions or using walker but of course it can not be written since the widgets do not exist anymore.

This exactly looks like there would be an outdated cache... however I do NOT use any caching UIA functions at all. None. Never. Nowhere.

I was not able to make the UIA tree update programatically... neither by calling any UIA functions nor by restarting the tester application nor by switching the AUT's GUI back and forth.
This does not happen every time. Sometimes after clicking the main button the tree seems properly up-to-date and everything works fine. However most of the runs it fails.
There is only one (mysterious) way that updates the UIA tree reliably: Using inspect.exe. When using inspect.exe tool for having a brief look into the AUT's UIA sub tree, the problem is suddenly gone and my tester application can access the actual, updated tree immediately! Of course the problem re-appears after restarting the AUT.

What does inspect.exe do to make the UIA tree (of another application!!!) update? How is it possible at all to access gone elements without using any caching? What did I miss?

I really need help.

Ok, some more findings:

UISpy.exe is able to refresh the UIA tree the same mysterious way inspect.exe does (this is especially strange because inspect.exe uses the same native interface as I do but UISpy.exe uses the .NET interface AFAIK). This means this is a kind of system wide and persistent UIA problem and not a pure native-UIA-problem.

The problem does not happend if I do not access the tree before switching the view. I.e. if my tester application does not access the AUT'S view before switching the view by clicking the main menu button, it sees the new widgets without problems. This strongly indicates some caching problem of the native UIA API - even if I have no idea how this could happen because I do not caching at all. Does someone know if there is some internal caching taking place?

I think this could be a API bug. However considering my current experiences with Microsoft Connect I am kind of lost with that showstopper :-(

Someone any idea?

I also tested the Snoop tool. Using Snoop does NOT heal the problem temporarily like Inspect and UISpy do. Regarding Inspect.exe, there is another detail... it is enough to collapse and expands the AUT's sub-tree to temporarily heal the problem.

答:
I know the question is quite old but I figured out what Inspect.exe does to refresh the UIA tree for other applications: look at the Options menu; there's an item labeled SPI_SCREENREADER flag which is checked by default.

Do the following in your code and you will probably get a fresh UIA tree:

```<code>SystemParametersInfo( SPI_SETSCREENREADER, TRUE, NULL, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);

PostMessage( HWND_BROADCAST, WM_WININICHANGE, SPI_SETSCREENREADER, 0);
</code>```

Title: Outdated UI automation tree

Body:
I know the question is quite old but I figured out what Inspect.exe does to refresh the UIA tree for other applications: look at the Options menu; there's an item labeled SPI_SCREENREADER flag which is checked by default.

Do the following in your code and you will probably get a fresh UIA tree:

SystemParametersInfo( SPI_SETSCREENREADER, TRUE, NULL, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);

PostMessage( HWND_BROADCAST, WM_WININICHANGE, SPI_SETSCREENREADER, 0);


问:
RealmSwift initialize list : Cannot specialize a non-generic definition
Hi I have an exception like "Cannot specialize a non-generic definition"
when i'm trying to initialize List in Realm object. Does anyone know how to fix this issue? swift 3.2</p>

```<code>class Dog: Object {
    @objc dynamic var name = ""
    @objc dynamic var age = 0
}

class Event : Object{
    dynamic var event_id = 0
    dynamic var date : String?
    dynamic var name : String?
    dynamic var remind : Remind?
    dynamic var event_status = 0

    let dogs = List<Dog>()       "Cannot specialize a non-generic definition"

    required convenience init?(map: Map){ self.init() }
}
</code>```

答:
I wanted to give the solution to this question some context. In Swift, namespacing is implicit on a module level. If you have external modules, such as RealmSwift, which has a type List you can still have a type named List in your own module. You can even have multiple external modules with the type List.

My reasoning for the error you presented was as follows

In Realm, what you posted is exactly how you're supposed to declare a list

Your example compiled in the context of my project which already uses Realm Lists

The error indicated suggests that the swift compiler knows that List is a valid type and in fact knows about a function named List.init(), however, the compiler is telling you that the function isn't generic.

The only answer at that point, is to assume the compiler is using a different definition of List than you are intending. The only way this happens is if the scope you're in (your project or another type), has also defined a type List, since internal types take precedence over external types. This precedence is extended further with type nesting. If you'd like to keep Realm's List as the default list, you can nest your List in another structure to provide a namespace of sorts.

The following example is as concise as possible given the complex situation.

```<code>import RealmSwift

let myGlobalDogs = List()
let myGlobalNestedListDogs = MyClass.List()
let globalDogs = RealmSwift.List<Dog>()

class List { }

class MyClass {
    class List { }

    let dogs = RealmSwift.List<Dog>()
    let myNestedListDogs = List() // type: MyModule.MyClass.List
    let myDogs = MyModule.List() // type: MyModule.List
}

class MyOtherClass {

    let dogs = RealmSwift.List<Dog>()
    let myNestedListDogs = MyClass.List() // type: MyModule.MyClass.List
    let myDogs = List() // type: MyModule.List
}
</code>```

Fortunately, types/functions are usually different enough that you can't inadvertently use the wrong one without encountering an error eventually, such as the one you encountered.

Body:
Hi I have an exception like "Cannot specialize a non-generic definition"
when i'm trying to initialize List in Realm object. Does anyone know how to fix this issue? swift 3.2

class Dog: Object {
    @objc dynamic var name = ""
    @objc dynamic var age = 0
}

class Event : Object{
    dynamic var event_id = 0
    dynamic var date : String?
    dynamic var name : String?
    dynamic var remind : Remind?
    dynamic var event_status = 0

    let dogs = List<Dog>()       "Cannot specialize a non-generic definition"

    required convenience init?(map: Map){ self.init() }
}

Body:
I wanted to give the solution to this question some context. In Swift, namespacing is implicit on a module level. If you have external modules, such as RealmSwift, which has a type List you can still have a type named List in your own module. You can even have multiple external modules with the type List.

My reasoning for the error you presented was as follows

In Realm, what you posted is exactly how you're supposed to declare a list

Your example compiled in the context of my project which already uses Realm Lists

The error indicated suggests that the swift compiler knows that List is a valid type and in fact knows about a function named List.init(), however, the compiler is telling you that the function isn't generic.

The only answer at that point, is to assume the compiler is using a different definition of List than you are intending. The only way this happens is if the scope you're in (your project or another type), has also defined a type List, since internal types take precedence over external types. This precedence is extended further with type nesting. If you'd like to keep Realm's List as the default list, you can nest your List in another structure to provide a namespace of sorts.

The following example is as concise as possible given the complex situation.

import RealmSwift

let myGlobalDogs = List()
let myGlobalNestedListDogs = MyClass.List()
let globalDogs = RealmSwift.List<Dog>()

class List { }

class MyClass {
    class List { }

    let dogs = RealmSwift.List<Dog>()
    let myNestedListDogs = List() // type: MyModule.MyClass.List
    let myDogs = MyModule.List() // type: MyModule.List
}

class MyOtherClass {

    let dogs = RealmSwift.List<Dog>()
    let myNestedListDogs = MyClass.List() // type: MyModule.MyClass.List
    let myDogs = List() // type: MyModule.List
}

Fortunately, types/functions are usually different enough that you can't inadvertently use the wrong one without encountering an error eventually, such as the one you encountered.


问:
Issue with using Xrm.Utility.openQuickCreate() from HTML web resource
I'm trying to open an entity's Quick Create form from an HTML web resource from navigation of an entity. I'm using Xrm.Utility.openQuickCreate("entityname", null, null) for a start.

I get an error saying JQueryApi is not defined in the browser's console.

However, other functions like Xrm.Utility.openEntityForm and Xrm.Utility.isActivityType(entityname) does work.

Any suggestions? Thanks.

答:
@Polshgiant - Thank you! I was having this exact issue, and even though I had referenced the parent entity id correctly, I didn't do the same for the openQuickCreate call. I only wish I had found this answer 10 hours ago. Here's my complete code, in case anyone needs it (or can offer suggestions how to improve it):</p>

```<code>function YOURFUNCTIONNAME() {
            var parentContact = {
                entityType: "contact",
                id: window.parent.Xrm.Page.data.entity.getId().substring(1, 37)
            };

            // You can set parameters here to pre-fill the form; I haven't
            var parameters = {

            };

            parent.Xrm.Utility.openQuickCreate("YOURLOGICALENTITYNAME", parentContact, parameters)
                .then(function(lookup) { successCallback(lookup); }, function(error) { errorCallback(error); });

            function successCallback(lookup) {
                alert("lookup: " + lookup.savedEntityReference.id);
                alert("lookup: " + lookup.savedEntityReference.name);
            }

            function errorCallback(e) {
                alert("Error: " + e.errorCode + " " + e.message);
            }
        }
</code>```

Body:
@Polshgiant - Thank you! I was having this exact issue, and even though I had referenced the parent entity id correctly, I didn't do the same for the openQuickCreate call. I only wish I had found this answer 10 hours ago. Here's my complete code, in case anyone needs it (or can offer suggestions how to improve it):

function YOURFUNCTIONNAME() {
            var parentContact = {
                entityType: "contact",
                id: window.parent.Xrm.Page.data.entity.getId().substring(1, 37)
            };

            // You can set parameters here to pre-fill the form; I haven't
            var parameters = {

            };

            parent.Xrm.Utility.openQuickCreate("YOURLOGICALENTITYNAME", parentContact, parameters)
                .then(function(lookup) { successCallback(lookup); }, function(error) { errorCallback(error); });

            function successCallback(lookup) {
                alert("lookup: " + lookup.savedEntityReference.id);
                alert("lookup: " + lookup.savedEntityReference.name);
            }

            function errorCallback(e) {
                alert("Error: " + e.errorCode + " " + e.message);
            }
        }


问:
element-wise multiplication with broadcasting in keras custom layer
I am creating a custom layer with weights that need to be multiplied by element-wise before activation. I can get it to work when the output and input is the same shape. The problem occurs when I have a first order array as input with a second order array as output. tensorflow.multiply supports broadcasting, but when I try to use it in Layer.call(x, self.kernel)
to multiply x by the self.kernel Variable it complains that they are different shapes saying:

```<code>ValueError: Dimensions must be equal, but are 4 and 3 for 'my_layer_1/Mul' (op: 'Mul') with input shapes: [?,4], [4,3].
</code>```

here is my code:

```<code>from keras import backend as K
from keras.engine.topology import Layer
import tensorflow as tf
from keras.models import Sequential
import numpy as np

class MyLayer(Layer):

    def __init__(self, output_dims, **kwargs):
        self.output_dims = output_dims

        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel',
                                      shape=self.output_dims,
                                      initializer='ones',
                                      trainable=True)

        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):
        #multiply wont work here?
        return K.tf.multiply(x, self.kernel)

    def compute_output_shape(self, input_shape):
        return (self.output_dims)

mInput = np.array([[1,2,3,4]])
inShape = (4,)
net = Sequential()
outShape = (4,3)
l1 = MyLayer(outShape, input_shape= inShape)
net.add(l1)
net.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])
p = net.predict(x=mInput, batch_size=1)
print(p)
</code>```

Edit:
Given input shape (4,) and output shape (4,3) the weight matrix should be the same shape as the output and initialized with ones. So in the above code the input is [1,2,3,4], the weight matrix should be [[1,1,1,1],[1,1,1,1],[1,1,1,1]] and the output should look like [[1,2,3,4],[1,2,3,4],[1,2,3,4]]

答:
here is another solution that is based on the answer by Daniel Möller, but uses tf.multiply like the original code.</p>

```<code>class MyLayer(Layer):

    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim

        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        output_shape = self.compute_output_shape(input_shape)
        self.kernel = self.add_weight(name='kernel',
                                      shape=(1,) + output_shape[1:],
                                      initializer='ones',
                                      trainable=True)

        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):

        return K.tf.multiply(x, self.kernel)

    def compute_output_shape(self, input_shape):
        return (input_shape[0],self.output_dim)+input_shape[1:]
</code>```

Body:
I am creating a custom layer with weights that need to be multiplied by element-wise before activation. I can get it to work when the output and input is the same shape. The problem occurs when I have a first order array as input with a second order array as output. tensorflow.multiply supports broadcasting, but when I try to use it in Layer.call(x, self.kernel)
to multiply x by the self.kernel Variable it complains that they are different shapes saying:

ValueError: Dimensions must be equal, but are 4 and 3 for 'my_layer_1/Mul' (op: 'Mul') with input shapes: [?,4], [4,3].

here is my code:

from keras import backend as K
from keras.engine.topology import Layer
import tensorflow as tf
from keras.models import Sequential
import numpy as np

class MyLayer(Layer):

    def __init__(self, output_dims, **kwargs):
        self.output_dims = output_dims

        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel',
                                      shape=self.output_dims,
                                      initializer='ones',
                                      trainable=True)

        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):
        #multiply wont work here?
        return K.tf.multiply(x, self.kernel)

    def compute_output_shape(self, input_shape):
        return (self.output_dims)

mInput = np.array([[1,2,3,4]])
inShape = (4,)
net = Sequential()
outShape = (4,3)
l1 = MyLayer(outShape, input_shape= inShape)
net.add(l1)
net.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])
p = net.predict(x=mInput, batch_size=1)
print(p)

Edit:
Given input shape (4,) and output shape (4,3) the weight matrix should be the same shape as the output and initialized with ones. So in the above code the input is [1,2,3,4], the weight matrix should be [[1,1,1,1],[1,1,1,1],[1,1,1,1]] and the output should look like [[1,2,3,4],[1,2,3,4],[1,2,3,4]]

Body:
here is another solution that is based on the answer by Daniel Möller, but uses tf.multiply like the original code.

class MyLayer(Layer):

    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim

        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        output_shape = self.compute_output_shape(input_shape)
        self.kernel = self.add_weight(name='kernel',
                                      shape=(1,) + output_shape[1:],
                                      initializer='ones',
                                      trainable=True)

        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):

        return K.tf.multiply(x, self.kernel)

    def compute_output_shape(self, input_shape):
        return (input_shape[0],self.output_dim)+input_shape[1:]


问:
Custom ID generator in NHibernate
HI all,

How to do functionality of generator class="assigned" as well as generator class="native" together.

in my case some situation i will have ID another case i dont know the ID.

```<code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Acurus.Capella.Core.DomainObjects" assembly="User">
  <class name="UserLookup, Core" table="User_lookup" lazy="true">
    <id name="Id" column="User_ID">
      <generator class="assigned" />
    </id>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Acurus.Capella.Core.DomainObjects" assembly="User">
  <class name="UserLookup, Core" table="User_lookup" lazy="true">
    <id name="Id" column="User_ID">
      <generator class="native" />
    </id>
</code>```

答:
You can write your own implementation of IIdentifierGenerator using code from both NHibernate.Id.Assigned and whatever concrete implementation of "native" corresponds to your DB, like NHibernate.Id.IdentityGenerator.

However, as Ids should be meaningless, I don't know why you would "have ID" before persisting an entity.

Title: Custom ID generator in NHibernate

Body:
HI all,

How to do functionality of generator class="assigned" as well as generator class="native" together.

in my case some situation i will have ID another case i dont know the ID.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Acurus.Capella.Core.DomainObjects" assembly="User">
  <class name="UserLookup, Core" table="User_lookup" lazy="true">
    <id name="Id" column="User_ID">
      <generator class="assigned" />
    </id>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Acurus.Capella.Core.DomainObjects" assembly="User">
  <class name="UserLookup, Core" table="User_lookup" lazy="true">
    <id name="Id" column="User_ID">
      <generator class="native" />
    </id>


问:
Laravel auto translate $request
I have two table in my database. The first is industry and the second is industry_languages.

Industry's table

```<code>Schema::create('industries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('industry_name', 100);
        $table->integer('language_id')->default(1);
        $table->timestamps();
    });
</code>```

Industry_Languages' table

```<code>Schema::create('industry_languages', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('industry_id');
        $table->string('industry_name', 200);
        $table->integer('language_id');
        $table->timestamps();
    });
</code>```

This is my IndustryController

```<code>public function store(Request $request)
{
    $industry = new Industry();
    $industry->industry_name = $request->industryName;
    $industry->save();

    return response()->json($industry);
}
</code>```

This function will only store data into industry's table with language id = 1, but I also want to store it into industry_languages' table with language id = 2 (because I have a language's table in my database with 2 row data: 'Indonesia', 'English')

Example: If I input 'Halo' in the industry_name field, It will store into my industry's table as 'Halo' in the industry_name field and '1' in the language_id field, then It will also store into my industry_languages' table as 'Hello' in the industry_name field and '2' in the language_id field

I have a problem with translating the request from the industry's table.
I have tried to use Laravel google-translate but, it didn't work

答:
I have tried to use this pakcage

But, it needs Google Translate API key and I think that's not free. So, I have found a package that's not need to generate API KEY: statickidz/php-google-translate-free

Title: Laravel auto translate $request

Body:
I have two table in my database. The first is industry and the second is industry_languages.

Industry's table

Schema::create('industries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('industry_name', 100);
        $table->integer('language_id')->default(1);
        $table->timestamps();
    });

Industry_Languages' table

Schema::create('industry_languages', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('industry_id');
        $table->string('industry_name', 200);
        $table->integer('language_id');
        $table->timestamps();
    });

This is my IndustryController

public function store(Request $request)
{
    $industry = new Industry();
    $industry->industry_name = $request->industryName;
    $industry->save();

    return response()->json($industry);
}

This function will only store data into industry's table with language id = 1, but I also want to store it into industry_languages' table with language id = 2 (because I have a language's table in my database with 2 row data: 'Indonesia', 'English')

Example: If I input 'Halo' in the industry_name field, It will store into my industry's table as 'Halo' in the industry_name field and '1' in the language_id field, then It will also store into my industry_languages' table as 'Hello' in the industry_name field and '2' in the language_id field

I have a problem with translating the request from the industry's table.
I have tried to use Laravel google-translate but, it didn't work


问:
c# Correct way to convert string value to decimal
I need convert the any value in format "101.46" to decimal.

```<code>string s = "101.46";
decimal value = Convert.ToDecimal(s);
</code>```

But the decimal final value is always 10146. I need the format of the output value to be 101.46 as decimal

答:
Your current culture seems to use , as decimal separator, then you could use:

```<code>decimal value = decimal.Parse(s, CultureInfo.InvariantCulture);
</code>```

Body:
I need convert the any value in format "101.46" to decimal.

string s = "101.46";
decimal value = Convert.ToDecimal(s);

But the decimal final value is always 10146. I need the format of the output value to be 101.46 as decimal

Body:
Your current culture seems to use , as decimal separator, then you could use:

decimal value = decimal.Parse(s, CultureInfo.InvariantCulture);


问:
Grape API : Return Location header after a creation
A POST request shall create the resource and return a "Location" header pointing to the created resource.

I'm using grape API with rails and asking myself what is the best way to return the created resource URI.
Is grape offering a way to get a resource URI without setting it manually ?

```<code>resource :blup do
  post '/' do
    blup = Blup.create(first_name: 'Jamie')
    if blup.present?
      header 'Location', 'HERE blup URI'
    end
  end
end
</code>```

答:
Though I do not know what Grape adds to Ruby on Rails API, I had the same problem, and I found the answer here.
To give the location in a header after creation, you can add :

render location: specific_thing_i_am_looking_for_url(@thing)

And you can find specific_thing_i_am_looking_for_url by running

```<code>rake routes
</code>```

Body:
A POST request shall create the resource and return a "Location" header pointing to the created resource.

I'm using grape API with rails and asking myself what is the best way to return the created resource URI.
Is grape offering a way to get a resource URI without setting it manually ?

resource :blup do
  post '/' do
    blup = Blup.create(first_name: 'Jamie')
    if blup.present?
      header 'Location', 'HERE blup URI'
    end
  end
end

Body:
Though I do not know what Grape adds to Ruby on Rails API, I had the same problem, and I found the answer here.
To give the location in a header after creation, you can add :

render location: specific_thing_i_am_looking_for_url(@thing)

And you can find specific_thing_i_am_looking_for_url by running

rake routes


问:
Printing certain values using Collections.frequency()
I have an array as follows:

```<code>int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
</code>```

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

```<code>ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);
</code>```

I then used a stream to loop through it and print the values using Collections.frequency.

```<code>dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });
</code>```

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

```<code>int check = Collections.frequency(list, key);
            if (check > 1) {
</code>```

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

答:
```<code>HashMap<Integer, Integer> hashmap = new HashMap<>();
for (int i : array) {
    if (hashmap.containsKey(i)) {
        hashmap.put(i, hashmap.get(i) + 1);
    } else {
        hashmap.put(i, 1);
    }
}
</code>```

Stores the value and its frequency.

```<code>{48=2, 17=2, 33=1, 18=1, 22=1, 11=4, 29=1, 14=1}
</code>```

EDIT: if you want to print the duplicates;

```<code>hashmap.entrySet().stream().filter((entry) -> ((int) entry.getValue() >= 2)).forEach((entry) -> {
    System.out.println(entry.getKey() + ":" + entry.getValue());
});
</code>```

Gives you:

```<code>48:2
17:2
11:4
</code>```

Body:
I have an array as follows:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};

What I wanted to do was to find the duplicate values, and print them.

So my way of doing this was to convert to ArrayList, then to Set and use a stream on the Set.

ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
}

Set<Integer> dup = new HashSet<>(list);

I then used a stream to loop through it and print the values using Collections.frequency.

dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list, key));
        });

Which will of course print them all, even if the count is one.

I thought adding in if(key > 1) but it's the value I want not the key.

How can I get the value in this instance to print only where value > 2.

I could probably put in:

int check = Collections.frequency(list, key);
            if (check > 1) {

but this then duplicates Collections.frequency(list, key) in the stream and is quite ugly.

Body:
HashMap<Integer, Integer> hashmap = new HashMap<>();
for (int i : array) {
    if (hashmap.containsKey(i)) {
        hashmap.put(i, hashmap.get(i) + 1);
    } else {
        hashmap.put(i, 1);
    }
}

Stores the value and its frequency.

{48=2, 17=2, 33=1, 18=1, 22=1, 11=4, 29=1, 14=1}

EDIT: if you want to print the duplicates;

hashmap.entrySet().stream().filter((entry) -> ((int) entry.getValue() >= 2)).forEach((entry) -> {
    System.out.println(entry.getKey() + ":" + entry.getValue());
});

Gives you:

48:2
17:2
11:4


问:
How to bind <select> ng-model using ng-options inside a ng-repeat
I have a list of tasks:

```<code>[{
    Titel: "Title1",
    Position: "9"
},{
    Titel: "Title2",
    Position: "1"
},{
    Titel: "Title3",
    Position: "5"
},{
    Titel: "Title4",
    Position: "7"
}]
</code>```

I'm trying to create a list of <select>, where each is list.lenght long and has a selected value. The html snippet:

```<code><table cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td class="ms-authoringcontrols"><b>Title</b></td>
        <td class="ms-authoringcontrols"><b>Position</b></td>
    </tr>
    <tr ng-repeat="t in tasks">
        <td>
            <a href="TODO">{{t.Titel}}</a>
        </td>
        <td>
            <select ng-model="t.Position" ng-options="t.Position as tasks.indexOf(i)+1 for i in tasks"></select>
        </td>
    </tr>
</table
</code>```

Output:

What it is missing, is the selected value (position) of each <select>. I Know the value is set by defining the ng-model and ng-model="t.Position" is wrong, but how can I set the Position value of each item to its related select element? The <option>'s of each select should be the length of the tasks and ordered from 1 to n.

答:
If you want to change the order of the item you need to keep track of the positions in a seperate array.

Here's an working example

angular.module("app", []).controller("myCtrl", function($scope){
$scope.tasks =  [{
    Titel: "Title1",
    Position: "9"
},{
    Titel: "Title2",
    Position: "1"
},{
    Titel: "Title3",
    Position: "5"
},{
    Titel: "Title4",
    Position: "7"
}];
$scope.positions = ["1","2","3","4","5","6","7","8","9"];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
  <table cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td class="ms-authoringcontrols"><b>Title</b></td>
        <td class="ms-authoringcontrols"><b>Position</b></td>
    </tr>
    <tr ng-repeat="t in tasks | orderBy: 'Position'">
        <td>
            {{t.Titel}}
        </td>
        <td>
            <select ng-model="t.Position" ng-options="i for i in positions"></select>
        </td>
    </tr>
</table>
</div></code>```

Body:
I have a list of tasks:

[{
    Titel: "Title1",
    Position: "9"
},{
    Titel: "Title2",
    Position: "1"
},{
    Titel: "Title3",
    Position: "5"
},{
    Titel: "Title4",
    Position: "7"
}]

I'm trying to create a list of <select>, where each is list.lenght long and has a selected value. The html snippet:

        Title
        Position

            {{t.Titel}}

            <select ng-model="t.Position" ng-options="t.Position as tasks.indexOf(i)+1 for i in tasks"></select>

</table

Output:

What it is missing, is the selected value (position) of each <select>. I Know the value is set by defining the ng-model and ng-model="t.Position" is wrong, but how can I set the Position value of each item to its related select element? The <option>'s of each select should be the length of the tasks and ordered from 1 to n.

Body:
If you want to change the order of the item you need to keep track of the positions in a seperate array.

Here's an working example

angular.module("app", []).controller("myCtrl", function($scope){
$scope.tasks =  [{
    Titel: "Title1",
    Position: "9"
},{
    Titel: "Title2",
    Position: "1"
},{
    Titel: "Title3",
    Position: "5"
},{
    Titel: "Title4",
    Position: "7"
}];
$scope.positions = ["1","2","3","4","5","6","7","8","9"];
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
  <table cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td class="ms-authoringcontrols"><b>Title</b></td>
        <td class="ms-authoringcontrols"><b>Position</b></td>
    </tr>
    <tr ng-repeat="t in tasks | orderBy: 'Position'">
        <td>
            <a href="TODO">{{t.Titel}}</a>
        </td>
        <td>
            <select ng-model="t.Position" ng-options="i for i in positions"></select>
        </td>
    </tr>
</table>
</div>


问:
Replace backslash when in path but not escape character
We have a larger project where almost all include file paths are written using the "Windows style" backslash syntax, e.g include 'foo\bar.baz'. Now we would like to run the poject on Unix machines as well, however we are (obviously) having trouble regarding the backslashes in the path names.
Unfortunately I cannot replace all backslashes with forward slashes as they are used for creating newlines \n and escaping characters in other parts of the code.

I tried fiddling around with RegEx in order to match the backslash character only when enclosed by quotation marks

```<code>(["'])(?:(?=(\\?))\2.)*?\1
</code>```

and followed by either another backslash or a dot. But the above only find the text within the quotation marks, and I'm stuck on how to get it to only match the slash inside it.

Thanks a lot for your help!

P.S.: I use Atom as an editor if this is of any help

答:
https://regex101.com/r/U0MboP/1

```<code>(["'])(.+)\\\\?(.+)\1
</code>```

This regex

And this replace https://regex101.com/r/U0MboP/2

```<code>\1\2/\3\1
</code>```

Body:
We have a larger project where almost all include file paths are written using the "Windows style" backslash syntax, e.g include 'foo\bar.baz'. Now we would like to run the poject on Unix machines as well, however we are (obviously) having trouble regarding the backslashes in the path names.
Unfortunately I cannot replace all backslashes with forward slashes as they are used for creating newlines \n and escaping characters in other parts of the code.

I tried fiddling around with RegEx in order to match the backslash character only when enclosed by quotation marks

(["'])(?:(?=(\\?))\2.)*?\1

and followed by either another backslash or a dot. But the above only find the text within the quotation marks, and I'm stuck on how to get it to only match the slash inside it.

Thanks a lot for your help!

P.S.: I use Atom as an editor if this is of any help

Body:
https://regex101.com/r/U0MboP/1

(["'])(.+)\\\\?(.+)\1

This regex

And this replace https://regex101.com/r/U0MboP/2

\1\2/\3\1


问:
How to add Images to a dynamically created JTable
I have a JTable which I create dynamically from List<String> objects. I do this probably completely wrong but it works. The only thing I can't get to work is adding Images to some of the cells.

All it does is, it adds the ImageIcon Object name as String to the cells. See my code below.

```<code>private static Image doneImage = getIconImage("doneImage");
private static Image notDoneImage = getIconImage("notDoneImage");

private DefaultTableModel model = new DefaultTableModel(){
    @Override
    public Class<?> getColumnClass(int column){
        if ((column & 1) != 0 ){
            return ImageIcon.class;
        }else{
            return String.class;
        }
    }
};

initTables();

JTable table = new JTable();
table.setModel(model);

private void initTables(){

    model.addRow(new Object[]{});

    int rowsToAdd = 0;
    int rowCount = 0;
    int columnId = 0;

    for(HouseObject aHouse : houses){
        for(RoomObject aRoom : aHouse.getRooms()){

            model.addColumn(null);
            model.addColumn(aRoom.getId());
            model.setValueAt(aRoom.getId(), 0, columnId);

            if (rowCount < aRoom.getEvents().size()){
                rowsToAdd = aRoom.getEvents().size() - model.getRowCount();
                for(int i = 0; i <= rowsToAdd; i++){
                    model.addRow(new Object[]{});
                }
                rowCount = model.getRowCount();
            }

            for(int i = 0; i < aRoom.getEvents().size(); i++){
                model.setValueAt(aRoom.getEvents().get(i).getId(), i+1, columnId);

                for(String houseDone : housesDone){
                    if(aRoom.getEvents().get(i).getId().contains(houseDone)){
                        model.setValueAt(doneImage , i+1, columnId+1); // this does not work
                    }else{
                        model.setValueAt(notDoneImage, i+1, columnId+1);
                    }
                }
            }

            columnId = columnId+2;
        }
    }
}
</code>```

答:
I have a JTable which I create dynamically from List objects.

Well you can't just add Strings to the table since then image will need to be added as an ImageIcon. So you would need a List so you can add String and Icon values.

Then you need to override the getColumnClass(...) method of your TableModel to return Icon.class for the column that contains the Icon. The table will then use the appropriate renderer for the Icon.

See: How to set icon in a column of JTable? for a working example.

Body:
I have a JTable which I create dynamically from List<String> objects. I do this probably completely wrong but it works. The only thing I can't get to work is adding Images to some of the cells.

All it does is, it adds the ImageIcon Object name as String to the cells. See my code below.

private static Image doneImage = getIconImage("doneImage");
private static Image notDoneImage = getIconImage("notDoneImage");

private DefaultTableModel model = new DefaultTableModel(){
    @Override
    public Class<?> getColumnClass(int column){
        if ((column & 1) != 0 ){
            return ImageIcon.class;
        }else{
            return String.class;
        }
    }
};

initTables();

JTable table = new JTable();
table.setModel(model);

private void initTables(){

    model.addRow(new Object[]{});

    int rowsToAdd = 0;
    int rowCount = 0;
    int columnId = 0;

    for(HouseObject aHouse : houses){
        for(RoomObject aRoom : aHouse.getRooms()){

            model.addColumn(null);
            model.addColumn(aRoom.getId());
            model.setValueAt(aRoom.getId(), 0, columnId);

            if (rowCount < aRoom.getEvents().size()){
                rowsToAdd = aRoom.getEvents().size() - model.getRowCount();
                for(int i = 0; i <= rowsToAdd; i++){
                    model.addRow(new Object[]{});
                }
                rowCount = model.getRowCount();
            }

            for(int i = 0; i < aRoom.getEvents().size(); i++){
                model.setValueAt(aRoom.getEvents().get(i).getId(), i+1, columnId);

                for(String houseDone : housesDone){
                    if(aRoom.getEvents().get(i).getId().contains(houseDone)){
                        model.setValueAt(doneImage , i+1, columnId+1); // this does not work
                    }else{
                        model.setValueAt(notDoneImage, i+1, columnId+1);
                    }
                }
            }

            columnId = columnId+2;
        }
    }
}


问:
Nesting Apache Tiles Template
So I found this: http://tiles.apache.org/framework/tutorial/advanced/nesting-extending.html

Here is the example:

```<code><definition name="myapp.homepage" template="/layouts/classic.jsp">
  <put-attribute name="title" value="Tiles tutorial homepage" />
  <put-attribute name="header" value="/tiles/banner.jsp" />
  <put-attribute name="menu" value="/tiles/common_menu.jsp" />
  <put-attribute name="body">
    <definition template="/layouts/three_rows.jsp">
      <put-attribute name="one" value="/tiles/headlines.jsp" />
      <put-attribute name="two" value="/tiles/topics.jsp" />
      <put-attribute name="one" value="/tiles/comments.jsp" />
    </definition>
  </put-attribute>
  <put-attribute name="footer" value="/tiles/credits.jsp" />
</definition>
</code>```

So I defined this:

```<code><definition name="mgmt.base.layout" extends="base.layout">
     <put-attribute name="body">
         <definition template="/WEB-INF/mgmt/config/mgmtBody.jsp"/>
             <put-attribute name="adminLeft"  value="/WEB-INF/mgmt/config/left.jsp"/>
             <put-attribute name="adminRight" value="/tiles/blank.html"/>
         </definition>
     </put-attribute>
</definition>
</code>```

But the funny part is that, even their own documentation is wrong:

2009-05-12 11:20:56,088 [main] ERROR - org.apache.commons.digester.Digester.error(Digester.java:1635): Parse Error at line 17 column 68: Attribute "name" is required and must be specified for element type "definition".  org.xml.sax.SAXParseException: Attribute "name" is required and must be specified for element type "definition".

Even though I define a name for it, it still gives the following error:

2009-05-12 11:35:31,818 [main] ERROR - org.apache.commons.digester.Digester.error(Digester.java:1635): Parse Error at line 21 column 19: The content of element type "put-attribute" must match "null".
 org.xml.sax.SAXParseException: The content of element type "put-attribute" must match "null".

What is this mean?!!!!

答: Changing the DTD version to 2.1 solved my problem!</p>

Title: Nesting Apache Tiles Template

Body:
So I found this: http://tiles.apache.org/framework/tutorial/advanced/nesting-extending.html

Here is the example:

<definition name="myapp.homepage" template="/layouts/classic.jsp">
  <put-attribute name="title" value="Tiles tutorial homepage" />
  <put-attribute name="header" value="/tiles/banner.jsp" />
  <put-attribute name="menu" value="/tiles/common_menu.jsp" />
  <put-attribute name="body">
    <definition template="/layouts/three_rows.jsp">
      <put-attribute name="one" value="/tiles/headlines.jsp" />
      <put-attribute name="two" value="/tiles/topics.jsp" />
      <put-attribute name="one" value="/tiles/comments.jsp" />
    </definition>
  </put-attribute>
  <put-attribute name="footer" value="/tiles/credits.jsp" />
</definition>

So I defined this:

<definition name="mgmt.base.layout" extends="base.layout">
     <put-attribute name="body">
         <definition template="/WEB-INF/mgmt/config/mgmtBody.jsp"/>
             <put-attribute name="adminLeft"  value="/WEB-INF/mgmt/config/left.jsp"/>
             <put-attribute name="adminRight" value="/tiles/blank.html"/>
         </definition>
     </put-attribute>
</definition>

But the funny part is that, even their own documentation is wrong:

2009-05-12 11:20:56,088 [main] ERROR - org.apache.commons.digester.Digester.error(Digester.java:1635): Parse Error at line 17 column 68: Attribute "name" is required and must be specified for element type "definition".  org.xml.sax.SAXParseException: Attribute "name" is required and must be specified for element type "definition".

Even though I define a name for it, it still gives the following error:

2009-05-12 11:35:31,818 [main] ERROR - org.apache.commons.digester.Digester.error(Digester.java:1635): Parse Error at line 21 column 19: The content of element type "put-attribute" must match "null".
 org.xml.sax.SAXParseException: The content of element type "put-attribute" must match "null".

What is this mean?!!!!