问:
What are some good sql databases for home Vista computer?
I have been trying for a long time to get SQL Server Express on my computer to practice my C#/SQL with and I still haven't gotten it to work.

Are there other programs I can use to setup an SQL database to practice with?  If so, which are the best ones for Vista?

EDIT:
To be clear I am not new to SQL programming, I just haven't done any in a while and want to stay fresh.  So I would like something that has most of the features of forms of SQL I would use professionally.

答:
I preferr Firebird its a madure BD and its O.S. very stable btw.

http://www.firebirdsql.org/

and try ibexpert for manager this bd.

http://ibexpert.net/ibe/

OwnerDisplayName: GordonG

LastEditorDisplayName: GordonG

OwnerDisplayName: Kipow


来源: stackexchange

问:
Rails 3 runner not detecting JSON gem?
I'm trying to create Ruby script to run with my Rails 3 environment.

However, whenever I run this rubyscript with Rails Runner, I get this error:

```<code>require 'rubygems'
require 'json'

@payload = {
"message" => "helloworld",
"station" => {"id"=>12345}
}.to_json

puts @payload
</code>```

ERROR:

```<code>/usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require': no such file to load -- json (LoadError)
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:198:in `load_dependency'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:554:in `new_constants_in'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:198:in `load_dependency'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require'
 from createflags.rb:2
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39:in `eval'
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands/runner.rb:47
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39:in `require'
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39
 from script/rails:6:in `require'
 from script/rails:6
</code>```

Can someone please tell me what I can do to fix this?

答: remove require "json" and then try. I believe ActiveSupport already has to_json in built.</p>

ContentLicense: CC BY-SA 2.5

Title: Rails 3 runner not detecting JSON gem?

Body:
I'm trying to create Ruby script to run with my Rails 3 environment.

However, whenever I run this rubyscript with Rails Runner, I get this error:

require 'rubygems'
require 'json'

@payload = {
"message" => "helloworld",
"station" => {"id"=>12345}
}.to_json

puts @payload

ERROR:

/usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require': no such file to load -- json (LoadError)
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:198:in `load_dependency'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:554:in `new_constants_in'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:198:in `load_dependency'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require'
 from createflags.rb:2
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39:in `eval'
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands/runner.rb:47
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39:in `require'
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39
 from script/rails:6:in `require'
 from script/rails:6

Can someone please tell me what I can do to fix this?


问:
How to change textview default color (Theme.AppCompat.Light.DarkActionBar)
I am trying to understand the theming and styling system of Android and basically attempt to do the simplest thing - change the default color of TextView texts.

According to the source code of TextView the default style would be:

```<code><item name="textViewStyle">@style/Widget.TextView</item>
</code>```

Looking at this style I discover the following:

```<code><style name="Widget.TextView">
    <item name="textAppearance">?attr/textAppearanceSmall</item>
    ....
</style>
</code>```

It seems that the default textAppearance is set to textAppearanceSmall (from the theme).

I look into themes.xml for the referenced textAppearanceSmall and find this:

```<code><item name="textAppearanceSmall">@style/TextAppearance.Small</item>
</code>```

Aha - it references this TextAppearance.Small:

```<code><style name="TextAppearance.Small">
    <item name="textSize">14sp</item>
    <item name="textColor">?textColorSecondary</item>
</style>
</code>```

Ok, we are getting somewhere - maybe? By default TextView uses the color "textColorSecondary".

First immediate question: Why is it references so weirdly? (questionmark but not like '?attr/textColorSecondary')?

I go back to the themes.xml file and discover this:

```<code><item name="textColorSecondary">@color/secondary_text_dark</item>
</code>```

At this point I am  pretty sure that I have to override textColorSecondary in my custom AppTheme like so:

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

    <item name="android:textColorPrimary">#00CC00</item>
</style>
</code>```

This does of course not work... the question is - why?

BTW: All the files I am looking at (theme.xml & styles.xml) reside in my Android SDK directory:

```<code>C:\AndroidSDK\platforms\android-26\data\res\values
</code>```

答:
Try this:</p>

```<code><style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
     <item name="android:textColor">@color/white</item>
</style>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to understand the theming and styling system of Android and basically attempt to do the simplest thing - change the default color of TextView texts.

According to the source code of TextView the default style would be:

<item name="textViewStyle">@style/Widget.TextView</item>

Looking at this style I discover the following:

It seems that the default textAppearance is set to textAppearanceSmall (from the theme).

I look into themes.xml for the referenced textAppearanceSmall and find this:

<item name="textAppearanceSmall">@style/TextAppearance.Small</item>

Aha - it references this TextAppearance.Small:

Ok, we are getting somewhere - maybe? By default TextView uses the color "textColorSecondary".

First immediate question: Why is it references so weirdly? (questionmark but not like '?attr/textColorSecondary')?

I go back to the themes.xml file and discover this:

<item name="textColorSecondary">@color/secondary_text_dark</item>

At this point I am  pretty sure that I have to override textColorSecondary in my custom AppTheme like so:

This does of course not work... the question is - why?

BTW: All the files I am looking at (theme.xml & styles.xml) reside in my Android SDK directory:

C:\AndroidSDK\platforms\android-26\data\res\values

Body:
Try this:

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
     <item name="android:textColor">@color/white</item>
</style>


问:
Printing an Object with ngFor
I am pulling object from database:

objects content might be different so we dont know what will come from db.(i mean it might be lemons too)

I am trying to print this using ngfor.If i convert this object to an array i can print it like:

```<code>this.drops = Object.values(monster[this.randommnumber].drops);

<li *ngFor="let drop of drops">
   {{ drop }}
 </li>
</code>```

this will print
3 and 5 without apple and pixi.

what i am trying to do is print them with their names.(i mean apple:3,pixi:5)

i can do that without converting object to an array and just writing

```<code><li *ngFor="let drop of drops">
       Apple:{{ drop.apple }}
       Pixi:{{drop.pixi}}
     </li>
</code>```

but what i am going to do if data has lemons rather than apples?

thanks

答:
You need to use Object.keys()

Write a method to return the property names as you can't use Object.keys directly in the html template

```<code>public getKeys(obj: string[]): any {
      return Object.keys(obj);
}
</code>```

Then, use it to iterate over your object like so,

```<code><ul *ngFor="let key of getKeys(obj)">
  <li> {{key}}: {{obj[key]}} </li>
</ul>
</code>```

Demo

Or, you can also do the below, which is kind of a hack (not recommended)

```<code>_obj: any = Object;
myObj = {
    apples: 2,
    oranges: 3
}
</code>```

And in your html,

```<code><li *ngFor="let key of _obj.keys(y)">
  {{ key }} : {{ myObj[key] }}
</li>
</code>```

Demo

Title: Printing an Object with ngFor

Body:
I am pulling object from database:

objects content might be different so we dont know what will come from db.(i mean it might be lemons too)

I am trying to print this using ngfor.If i convert this object to an array i can print it like:

this.drops = Object.values(monster[this.randommnumber].drops);

   {{ drop }}

this will print
3 and 5 without apple and pixi.

what i am trying to do is print them with their names.(i mean apple:3,pixi:5)

i can do that without converting object to an array and just writing

       Apple:{{ drop.apple }}
       Pixi:{{drop.pixi}}

but what i am going to do if data has lemons rather than apples?

thanks

Body:
You need to use Object.keys()

Write a method to return the property names as you can't use Object.keys directly in the html template

public getKeys(obj: string[]): any {
      return Object.keys(obj);
}

Then, use it to iterate over your object like so,

<ul *ngFor="let key of getKeys(obj)">
  <li> {{key}}: {{obj[key]}} </li>
</ul>

Demo

Or, you can also do the below, which is kind of a hack (not recommended)

_obj: any = Object;
myObj = {
    apples: 2,
    oranges: 3
}

And in your html,

<li *ngFor="let key of _obj.keys(y)">
  {{ key }} : {{ myObj[key] }}
</li>

Demo


问:
React JS editing first item of an array with spread operator
I want to update an item of an array at a given index in my reducer using ES6 spread operator ... Here is what I am doing

```<code>let array = action.payload.items;
return [...array, array[3].id:555]
</code>```

By this way editing works very well, but it also adds an extra item in the array.

Any help???

答:
Use to index to get the item, clone it and change the id with Object#assign.
Create the new array by using Array#slice and spread to insert the updated item to the right place in the new array:

const items = [{ id: 1 }, { id: 2 }, { id: 3 }]; // action.payload.items

const index = 1;

const itemToUpdate = Object.assign({}, items[index], { id: 1000});

const result = [...items.slice(0, index), itemToUpdate, ...items.slice(index + 1)]; // return ...

console.log(result);```

Body:
I want to update an item of an array at a given index in my reducer using ES6 spread operator ... Here is what I am doing

let array = action.payload.items;
return [...array, array[3].id:555]

By this way editing works very well, but it also adds an extra item in the array.

Any help???


问:
Changing the color of only one world in a text view
I am create an android app with android studio that retrieves text from mysqli database using volley library into a text view. I want to check if the text contains "@"  and if to does it it should be coloured red. That Is, I want only the "@" to be changed. Please guys how will I achieve that?</p>

答:
This will change the color of only one word in this case "@"

Esto cambiara el color de una sola letra, en este caso "@"

```<code>String newText = String.valueOf(text.getText()).replace("@","<font color='#fff0000'>@</font>");
        text.setText(Html.fromHtml(newText));
</code>```

Body:
This will change the color of only one word in this case "@"

Esto cambiara el color de una sola letra, en este caso "@"

String newText = String.valueOf(text.getText()).replace("@","<font color='#fff0000'>@</font>");
        text.setText(Html.fromHtml(newText));


问:
How do I shuffle a multidimensional list in Python
I know how to shuffle a simple List in Python by using the shuffle function from the random library shuffle(myList)

But how do I shuffle a multidimensional list?

```<code>myList[][]
</code>```

shuffle(myList) didn't work.

答:
I had this issue with trying to randomise questions and answers while maintaining the parring within the 2D list. At the time of writing this post, I have been learning python for only 3 weeks. My noob-solution was to create a random number, then use this number to pick from the list:

```<code>a_list = [["a4", 4], ["a3", 3],["a2", 2], ["a1", 1]]
a_pick = random.randint(0,3)
a_score = (a_list[a_pick])
</code>```

This method allowed me to get a random selection from my list while keep the pairings I had written

ContentLicense: CC BY-SA 4.0

Body:
I know how to shuffle a simple List in Python by using the shuffle function from the random library shuffle(myList)

But how do I shuffle a multidimensional list?

myList[][]

shuffle(myList) didn't work.

Body:
I had this issue with trying to randomise questions and answers while maintaining the parring within the 2D list. At the time of writing this post, I have been learning python for only 3 weeks. My noob-solution was to create a random number, then use this number to pick from the list:

a_list = [["a4", 4], ["a3", 3],["a2", 2], ["a1", 1]]
a_pick = random.randint(0,3)
a_score = (a_list[a_pick])

This method allowed me to get a random selection from my list while keep the pairings I had written


问:
Anonymous inner classes in C#
I'm in the process of writing a C# Wicket implementation in order to deepen my understanding of C# and Wicket.  One of the issues we're running into is that Wicket makes heavy use of anonymous inner classes, and C# has no anonymous inner classes.

So, for example, in Wicket, you define a Link like this:

```<code>Link link = new Link("id") {
    @Override
    void onClick() {
        setResponsePage(...);
    }
};
</code>```

Since Link is an abstract class, it forces the implementor to implement an onClick method.

However, in C#, since there are no anonymous inner classes, there is no way to do this.  As an alternative, you could use events like this:

```<code>var link = new Link("id");
link.Click += (sender, eventArgs) => setResponsePage(...);
</code>```

Of course, there are a couple of drawbacks with this.  First of all, there can be multiple Click handlers, which might not be cool.  It also does not force the implementor to add a Click handler.

Another option might be to just have a closure property like this:

```<code>var link = new Link("id");
link.Click = () => setResponsePage(...);
</code>```

This solves the problem of having many handlers, but still doesn't force the implementor to add the handler.

So, my question is, how do you emulate something like this in idiomatic C#?

答:
I started this before @meatthew's good answer - I would do almost exactly the same except - except that I would start with an abstract base class - so that if you did not want to go the route of an anonymous implementation you would be free to do that too. </p>

```<code>public abstract class LinkBase
{
    public abstract string Name { get; }
    protected abstract void OnClick(object sender, EventArgs eventArgs);
    //...
}

public class Link : LinkBase
{
    public Link(string name, Action<object, EventArgs> onClick)
    {
        _name = Name;
        _onClick = onClick;
    }

    public override string Name
    {
        get { return _name; }
    }

    protected override void OnClick(object sender, EventArgs eventArgs)
    {
        if (_onClick != null)
        {
            _onClick(sender, eventArgs);
        }
    }

    private readonly string _name;
    private readonly Action<object, EventArgs> _onClick;

}
</code>```

Title: Anonymous inner classes in C#

Body:
I'm in the process of writing a C# Wicket implementation in order to deepen my understanding of C# and Wicket.  One of the issues we're running into is that Wicket makes heavy use of anonymous inner classes, and C# has no anonymous inner classes.

So, for example, in Wicket, you define a Link like this:

Link link = new Link("id") {
    @Override
    void onClick() {
        setResponsePage(...);
    }
};

Since Link is an abstract class, it forces the implementor to implement an onClick method.

However, in C#, since there are no anonymous inner classes, there is no way to do this.  As an alternative, you could use events like this:

var link = new Link("id");
link.Click += (sender, eventArgs) => setResponsePage(...);

Of course, there are a couple of drawbacks with this.  First of all, there can be multiple Click handlers, which might not be cool.  It also does not force the implementor to add a Click handler.

Another option might be to just have a closure property like this:

var link = new Link("id");
link.Click = () => setResponsePage(...);

This solves the problem of having many handlers, but still doesn't force the implementor to add the handler.

So, my question is, how do you emulate something like this in idiomatic C#?

Body:
I started this before @meatthew's good answer - I would do almost exactly the same except - except that I would start with an abstract base class - so that if you did not want to go the route of an anonymous implementation you would be free to do that too.

public abstract class LinkBase
{
    public abstract string Name { get; }
    protected abstract void OnClick(object sender, EventArgs eventArgs);
    //...
}

public class Link : LinkBase
{
    public Link(string name, Action<object, EventArgs> onClick)
    {
        _name = Name;
        _onClick = onClick;
    }

    public override string Name
    {
        get { return _name; }
    }

    protected override void OnClick(object sender, EventArgs eventArgs)
    {
        if (_onClick != null)
        {
            _onClick(sender, eventArgs);
        }
    }

    private readonly string _name;
    private readonly Action<object, EventArgs> _onClick;

}


问:
How to judge unmarshal json interface{} type in golang?
I want to judge json type,but it always return "I don't know about type map[string]interface {}!",How to resolve it.  </p>

<p>=========================================================================</p>

```<code>type getRemoteCardInfo struct {
  Code int
  Msg  string
  Data []*remoteCardInfo
 }
type remoteCardInfo struct {
 Sn            string
 RemoteCardIp  string
 RemoteCardMac string
}
func Get_json_data(url string) (interface{}, error) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    req.Header.Add("X-MYCMDB-Auth-Token", "sPf98SMBWzOZJEJB8KWltbJyKvFYPauu")
    if err != nil {
         return nil, err
    }
    resp, _ := client.Do(req)
    if resp.StatusCode != http.StatusOK {
    resp.Body.Close()
    return nil, fmt.Errorf("query failed: %s", resp.Status)
    }
    var result interface{}
    body, err := ioutil.ReadAll(resp.Body)
    if err := json.Unmarshal(body, &result); err != nil {
        log.Fatalf("JSON unmarshaling failed: %s", err)
    }
    resp.Body.Close()
    fmt.Println(result)
    return result, nil
    }
 func main() {
       jsondata, err := Get_json_data(DHCPURL)
       if err != nil {
         log.Fatal(err)
       }
       switch v := jsondata.(type) {
       case getRemoteCardInfo:
          fmt.Println("aaaa")
       default:
          fmt.Printf("I don't know about type %T!\n", v)
       }
</code>```

答:
The go JSON unmarshaler doesn't know about types, as you can tell by the fact that it stores the result into an interface{} value:

```<code>func Unmarshal(data []byte, v interface{}) error
// "v" can be any type -------^
</code>```

So it's up to you to use the unmarshaler to populate your structure and determine if the result is valid or not.

In your example it looks like you're trying to unmarshal a remoteCardInfo from an HTTP response. To do this you should unmarshal into an empty remoteCardInfo struct and determine if the required fields were populated.

For example, suppose you expect a JSON document like so:

{
  "sn": "123",
  "ip": "0.0.0.0",
  "mac": "ff:ff:ff:ff:ff:ff"
}
```

<p>Then you should define your "remoteCardInfo" struct as below:</p>

```type remoteCardInfo struct {
  Sn            string `json:"sn"`
  RemoteCardIp  string `json:"ip"`
  RemoteCardMac string `json:"mac"`
}
```

<p>And then unmarshal and validate it like so:</p>

```func getRemoteCardInfo(bs []byte) (*remoteCardInfo, error) {
  rci := remoteCardInfo{}
  err := json.Unmarshal(bs, &rci)
  if err != nil {
    return nil, err
  }
  // Validate the expected fields
  if rci.Sn == "" {
    return nil, fmt.Errorf(`missing "sn"`)
  }
  if rci.RemoteCardIp == "" {
    return nil, fmt.Errorf(`missing "ip"`)
  }
  if rci.RemoteCardMac == "" {
    return nil, fmt.Errorf(`missing "mac"`)
  }
  return &rci, nil
}
```

Of course, you can validate the fields any way you like but the main thing to remember is that the unmarshaler only does the job of ensuring that the input byte array is a valid JSON document and populates the fields from the document into the fields defined by the value.

It cannot tell you what "type" of object the JSON document represents.

Body:
I want to judge json type,but it always return "I don't know about type map[string]interface {}!",How to resolve it.

=========================================================================

type getRemoteCardInfo struct {
  Code int
  Msg  string
  Data []*remoteCardInfo
 }
type remoteCardInfo struct {
 Sn            string
 RemoteCardIp  string
 RemoteCardMac string
}
func Get_json_data(url string) (interface{}, error) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    req.Header.Add("X-MYCMDB-Auth-Token", "sPf98SMBWzOZJEJB8KWltbJyKvFYPauu")
    if err != nil {
         return nil, err
    }
    resp, _ := client.Do(req)
    if resp.StatusCode != http.StatusOK {
    resp.Body.Close()
    return nil, fmt.Errorf("query failed: %s", resp.Status)
    }
    var result interface{}
    body, err := ioutil.ReadAll(resp.Body)
    if err := json.Unmarshal(body, &result); err != nil {
        log.Fatalf("JSON unmarshaling failed: %s", err)
    }
    resp.Body.Close()
    fmt.Println(result)
    return result, nil
    }
 func main() {
       jsondata, err := Get_json_data(DHCPURL)
       if err != nil {
         log.Fatal(err)
       }
       switch v := jsondata.(type) {
       case getRemoteCardInfo:
          fmt.Println("aaaa")
       default:
          fmt.Printf("I don't know about type %T!\n", v)
       }

Body:
The go JSON unmarshaler doesn't know about types, as you can tell by the fact that it stores the result into an interface{} value:

func Unmarshal(data []byte, v interface{}) error
// "v" can be any type -------^

So it's up to you to use the unmarshaler to populate your structure and determine if the result is valid or not.

In your example it looks like you're trying to unmarshal a remoteCardInfo from an HTTP response. To do this you should unmarshal into an empty remoteCardInfo struct and determine if the required fields were populated.

For example, suppose you expect a JSON document like so:

{
  "sn": "123",
  "ip": "0.0.0.0",
  "mac": "ff:ff:ff:ff:ff:ff"
}

Then you should define your "remoteCardInfo" struct as below:

type remoteCardInfo struct {
  Sn            string `json:"sn"`
  RemoteCardIp  string `json:"ip"`
  RemoteCardMac string `json:"mac"`
}

And then unmarshal and validate it like so:

func getRemoteCardInfo(bs []byte) (*remoteCardInfo, error) {
  rci := remoteCardInfo{}
  err := json.Unmarshal(bs, &rci)
  if err != nil {
    return nil, err
  }
  // Validate the expected fields
  if rci.Sn == "" {
    return nil, fmt.Errorf(`missing "sn"`)
  }
  if rci.RemoteCardIp == "" {
    return nil, fmt.Errorf(`missing "ip"`)
  }
  if rci.RemoteCardMac == "" {
    return nil, fmt.Errorf(`missing "mac"`)
  }
  return &rci, nil
}

Of course, you can validate the fields any way you like but the main thing to remember is that the unmarshaler only does the job of ensuring that the input byte array is a valid JSON document and populates the fields from the document into the fields defined by the value.

It cannot tell you what "type" of object the JSON document represents.


问:
Error with timezone into Google Forms with Apps Script
I have a Google Forms with a date information like this:

enter image description here

This information I store into Google Spreadsheet along Google Apps Script; however in this spreadsheet, it doesn't store right date, it stores other date.

enter image description here

I use this Javascript code:

```<code> var response = '2017-12-07 08:00'; //Value from Google Form
 var fecha_inicial = Utilities.formatString(response);
 fecha_inicial_Date = new Date(fecha_inicial.substr(0, 10) + "T" +
   fecha_inicial.substr(11, fecha_inicial.length)); //Thu Dec 07 2017 08:00:00 GMT-0500 (EST)
</code>```

This form is executed in a gmail account in Spain.

答:
GMT-0500 is not Spain's time zone.  Spain is plus one.  So there is a 6 hour difference between GMT-0500 and your time zone.  To get your time zone:</p>

```<code>var myTimeZone = Session.getScriptTimeZone();//Get the scripts time zone
</code>```

Body:
I have a Google Forms with a date information like this:

enter image description here

This information I store into Google Spreadsheet along Google Apps Script; however in this spreadsheet, it doesn't store right date, it stores other date.

enter image description here

I use this Javascript code:

 var response = '2017-12-07 08:00'; //Value from Google Form
 var fecha_inicial = Utilities.formatString(response);
 fecha_inicial_Date = new Date(fecha_inicial.substr(0, 10) + "T" +
   fecha_inicial.substr(11, fecha_inicial.length)); //Thu Dec 07 2017 08:00:00 GMT-0500 (EST)

This form is executed in a gmail account in Spain.

Body:
GMT-0500 is not Spain's time zone.  Spain is plus one.  So there is a 6 hour difference between GMT-0500 and your time zone.  To get your time zone:

var myTimeZone = Session.getScriptTimeZone();//Get the scripts time zone


问:
How can I display a nested CDialog within another CDialog?
I have two CDialog classes that I have created. Let's call them MainDialog and ExtraDialog. I want ExtraDialog to be able to be displayed both through doModal and as a nested dialog within MainDialog.

I can already bring it up separately through a Button and doModal. However, I've been stuck about how to place it within MainDialog.

```<code>CWnd* m_pWndStatic = new CWnd;
m_pWndStatic->Create(_T("Something"), _T("Title"), WS_CHILD | WS_VISIBLE, CRect(x, y, xEnd, yEnd), this, idWnd);

CExtraDialog* dlg = new CExtraDialog;
dlg->Create(IDD_NEW_DIALOG, this); //Or second variable can be m_pWndStatic?
//dlg->SetWindowPos(m_pWndStatic, x, y, xEnd, yEnd, SWP_NOZORDER | SWP_NOACTIVATE);
//dlg->Invalidate();
//dlg->ShowWindow(SW_SHOW);
//m_pWndStatic->ShowWindow(SW_SHOW);
</code>```

Above I shared some of the thigns I have tried. I was hoping to create a CWnd and put the dialog inside the CWnd but I feel like I am missing something and I couldn't really find anything helpful online.

Edit: I am basically trying to put multiple CWnds into one CDialog, and having the CWnd's run different functionalities from different classes. Kinda like putting lego blocks together.

Edit2: I found a question that is kinda similar? I hope to make it similar but I just don't want buttons and I want two of them get displayed at once.  Embedding dialogs in main dialog and switching them with button click in MFC

答:
I've been stuck about how to place it within MainDialog.

At the minimum, remove WS_POPUP, WS_CAPTION and WS_SYSMENU styles. Add the WS_CHILD style.

It is highly recommended to add the WS_EX_CONTROLPARENT extended style to enable keyboard navigation into and out of the embedded dialog.

For example, in OnInitDialog() of the parent dialog you could add:

```<code>// Note: Create member variable CExtraDialog, so there is no need for dynamic allocation!
m_extraDlg.Create( IDD_NEW_DIALOG, this );

// Adjust styles. 1st parameter removes, 2nd adds.
m_extraDlg.ModifyStyle( WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME, WS_CHILD );

// Adjust extended styles. 1st parameter removes, 2nd adds.
m_extraDlg.ModifyStyleEx( WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE, WS_EX_CONTROLPARENT );

// As we have changed the frame, we let Windows recalculate the non-client area
// by passing the SWP_FRAMECHANGED flag to SetWindowPos().
m_extraDlg.SetWindowPos( nullptr, 0, 0, 0, 0, SWP_FRAMECHANGED |
     SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE );
</code>```

I was hoping to create a CWnd and put the dialog inside the CWnd

I recommend to always use a CDialog-derived class as the parent of an embedded dialog. This ensures best compatibility with the Windows dialog manager for features like standard keyboard navigation. You will work with the system, not against it.

More to read:

What is the DS_CONTROL style for?

Why doesn’t the TAB key work on controls I’ve marked as WS_TABSTOP?

The dialog manager, part 2: Creating the frame window

Body:
I have two CDialog classes that I have created. Let's call them MainDialog and ExtraDialog. I want ExtraDialog to be able to be displayed both through doModal and as a nested dialog within MainDialog.

I can already bring it up separately through a Button and doModal. However, I've been stuck about how to place it within MainDialog.

CWnd* m_pWndStatic = new CWnd;
m_pWndStatic->Create(_T("Something"), _T("Title"), WS_CHILD | WS_VISIBLE, CRect(x, y, xEnd, yEnd), this, idWnd);

CExtraDialog* dlg = new CExtraDialog;
dlg->Create(IDD_NEW_DIALOG, this); //Or second variable can be m_pWndStatic?
//dlg->SetWindowPos(m_pWndStatic, x, y, xEnd, yEnd, SWP_NOZORDER | SWP_NOACTIVATE);
//dlg->Invalidate();
//dlg->ShowWindow(SW_SHOW);
//m_pWndStatic->ShowWindow(SW_SHOW);

Above I shared some of the thigns I have tried. I was hoping to create a CWnd and put the dialog inside the CWnd but I feel like I am missing something and I couldn't really find anything helpful online.

Edit: I am basically trying to put multiple CWnds into one CDialog, and having the CWnd's run different functionalities from different classes. Kinda like putting lego blocks together.

Edit2: I found a question that is kinda similar? I hope to make it similar but I just don't want buttons and I want two of them get displayed at once.  Embedding dialogs in main dialog and switching them with button click in MFC

Body:
I've been stuck about how to place it within MainDialog.

At the minimum, remove WS_POPUP, WS_CAPTION and WS_SYSMENU styles. Add the WS_CHILD style.

It is highly recommended to add the WS_EX_CONTROLPARENT extended style to enable keyboard navigation into and out of the embedded dialog.

For example, in OnInitDialog() of the parent dialog you could add:

// Note: Create member variable CExtraDialog, so there is no need for dynamic allocation!
m_extraDlg.Create( IDD_NEW_DIALOG, this );

// Adjust styles. 1st parameter removes, 2nd adds.
m_extraDlg.ModifyStyle( WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME, WS_CHILD );

// Adjust extended styles. 1st parameter removes, 2nd adds.
m_extraDlg.ModifyStyleEx( WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE, WS_EX_CONTROLPARENT );

// As we have changed the frame, we let Windows recalculate the non-client area
// by passing the SWP_FRAMECHANGED flag to SetWindowPos().
m_extraDlg.SetWindowPos( nullptr, 0, 0, 0, 0, SWP_FRAMECHANGED |
     SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE );

I was hoping to create a CWnd and put the dialog inside the CWnd

I recommend to always use a CDialog-derived class as the parent of an embedded dialog. This ensures best compatibility with the Windows dialog manager for features like standard keyboard navigation. You will work with the system, not against it.

More to read:

What is the DS_CONTROL style for?

Why doesn’t the TAB key work on controls I’ve marked as WS_TABSTOP?

The dialog manager, part 2: Creating the frame window


问:
RealBASIC opening a program file on the default operating system Console/Terminal
To make my Real Studio application portable, I want to make it open an executable file on Mac, Windows, and Linux with the default Console/Terminal application. I have a string s, which is the filename of the executable file. I have this so far:

```<code>#If TargetMacOS
  DIM sh As new Shell
  sh.Execute "open " + GetFolderItem(s).ShellPath + " -a Terminal"
#EndIf
</code>```

But how can this be done on Windows and Linux? For Linux, could I open the file with gnome-terminal or konsole, and if so how could I figure out which one to open it with?

答:
For linux you could actually use the shell to test and see which one is available using the "which" command. If both are then just pick one (or maybe make it user configurable)

On windows I'm not sure exactly how you'd force it to open in the command prompt.

Body:
To make my Real Studio application portable, I want to make it open an executable file on Mac, Windows, and Linux with the default Console/Terminal application. I have a string s, which is the filename of the executable file. I have this so far:

#If TargetMacOS
  DIM sh As new Shell
  sh.Execute "open " + GetFolderItem(s).ShellPath + " -a Terminal"
#EndIf

But how can this be done on Windows and Linux? For Linux, could I open the file with gnome-terminal or konsole, and if so how could I figure out which one to open it with?


问:
Meteor: Force rendering an element
I have a generic template used several times in my app:

```<code><template name="genericCollapse">
  {{data-1}}
  <a href=# class='collapsed' data-toggle='collapse'
     data-target='#uniqueId'>Show/hide data-2</a>
  <div class='collapse' id='uniqueId'>
    {{data-2}}
  </div>
</template>
</code>```

By clicking somewhere else in the app, data-1 and data-2 change simultaneously (using Session Vars). However, in case the template is already on the screen, only data-1 and data-2 are changing but the collapse status of the div remains (obviously) unchanged. If it was open before, it remains open.

I want to achieve, that whenever data-1/data-2 changes, div as well as a are forced to be in status collapsed again.
I tried to add

```<code><a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})
</code>```

which is not only pretty ugly but also does not help, because the class of div still remains "collapse show" and even with a second helper for div, I can't get rid of "show".

Re-rendering the whole Template would be also acceptable, but I have difficulties to determine the parentNode for calling Blaze.render() - it is never the same - and I'm also not sure where to place such a call correctly.

How is this done?

答:
Many thanks for your help!

@Michel Floyd let me realize that my issue is not caused by anything related to Meteor, but by bootstrap.

@Fred Stark added a nice variation to the solution, he uses autorun which is more Meteor-style and he uses .collapse('hide') instead of .removeClass('show') which gives some nice fade-out effect at least on iOS.

Because I've mixed up several issues, I'll clarify it one by one:

Find a trigger: You could use autorun or observeChanges as suggested, but both is not necessary in the end, because a Meteor helper is always called.
First try:

```<code><a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed"},
})
</code>```

The code in this helper will always run, when something in the template changes. If data-1 or data-2 changes for any reason, code will be excuted, so this is my trigger.

Use helpers properly: The first try doesn't do anything on the html, because the spacebar {{collapsed}} does not change its content. Although the helper code is executed, the return value does not change and therefore has no effect on the html side.
In order to see any change, return value must be different each time.
Second try:

```<code>Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})
</code>```

Ugly as I already said, but at least it sets the correct class for a.

Get rid of "show": And here comes Michel: Because "show" in div is controlled by Bootstrap, you cannot control this with any kind of spacebar/helper - but with javascript.
Third try:

```<code>Template.genericCollapse.helpers({
  collapsed () {
    $('.show').removeClass('show');
    return "collapsed " + Random.Id()},
})
</code>```

This works! It might be necessary to narrow down '.show' in case other elements having class "show" are present, but that's the way to go.

Prettify: Having Random.Id() as a class is still bad. So let's treat a the same way like we treated div. Additionally, we should use the "uniqueId" as identifier for both.
Fourth try:

```<code>Template.genericCollapse.helpers({
  collapsed () {
    $('[data-target="#uniqueId"]').addClass('collapsed');
    $('#uniqueId').removeClass('show');
    return "collapsed"},
})
</code>```

Make it shiny: There is no need for the helper {{collapsed}} to return any value anymore, this is all done with javascript. We just need the trigger functionality, so this is the final code:

```<code><template name="genericCollapse">
  {{data-1}}
  <a href=# class='collapsed' data-toggle='collapse' {{hook}}
     data-target='#uniqueId'>Show/hide data-2</a>
  <div class='collapse' id='uniqueId'>
    {{data-2}}
  </div>
</template>

Template.genericCollapse.helpers({
  hook () {
    $('[data-target="#uniqueId"]').addClass('collapsed');
    $('#uniqueId').removeClass('show');
  }
})
</code>```

Works like a charm.

Title: Meteor: Force rendering an element

Body:
I have a generic template used several times in my app:

<template name="genericCollapse">
  {{data-1}}
  Show/hide data-2

    {{data-2}}

</template>

By clicking somewhere else in the app, data-1 and data-2 change simultaneously (using Session Vars). However, in case the template is already on the screen, only data-1 and data-2 are changing but the collapse status of the div remains (obviously) unchanged. If it was open before, it remains open.

I want to achieve, that whenever data-1/data-2 changes, div as well as a are forced to be in status collapsed again.
I tried to add

<a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})

which is not only pretty ugly but also does not help, because the class of div still remains "collapse show" and even with a second helper for div, I can't get rid of "show".

Re-rendering the whole Template would be also acceptable, but I have difficulties to determine the parentNode for calling Blaze.render() - it is never the same - and I'm also not sure where to place such a call correctly.

How is this done?

Body:
Many thanks for your help!

@Michel Floyd let me realize that my issue is not caused by anything related to Meteor, but by bootstrap.

@Fred Stark added a nice variation to the solution, he uses autorun which is more Meteor-style and he uses .collapse('hide') instead of .removeClass('show') which gives some nice fade-out effect at least on iOS.

Because I've mixed up several issues, I'll clarify it one by one:

Find a trigger: You could use autorun or observeChanges as suggested, but both is not necessary in the end, because a Meteor helper is always called.
First try:

<a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed"},
})

The code in this helper will always run, when something in the template changes. If data-1 or data-2 changes for any reason, code will be excuted, so this is my trigger.

Use helpers properly: The first try doesn't do anything on the html, because the spacebar {{collapsed}} does not change its content. Although the helper code is executed, the return value does not change and therefore has no effect on the html side.
In order to see any change, return value must be different each time.
Second try:

Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})

Ugly as I already said, but at least it sets the correct class for a.

Get rid of "show": And here comes Michel: Because "show" in div is controlled by Bootstrap, you cannot control this with any kind of spacebar/helper - but with javascript.
Third try:

Template.genericCollapse.helpers({
  collapsed () {
    $('.show').removeClass('show');
    return "collapsed " + Random.Id()},
})

This works! It might be necessary to narrow down '.show' in case other elements having class "show" are present, but that's the way to go.

Prettify: Having Random.Id() as a class is still bad. So let's treat a the same way like we treated div. Additionally, we should use the "uniqueId" as identifier for both.
Fourth try:

Template.genericCollapse.helpers({
  collapsed () {
    $('[data-target="#uniqueId"]').addClass('collapsed');
    $('#uniqueId').removeClass('show');
    return "collapsed"},
})

Make it shiny: There is no need for the helper {{collapsed}} to return any value anymore, this is all done with javascript. We just need the trigger functionality, so this is the final code:

<template name="genericCollapse">
  {{data-1}}
  <a href=# class='collapsed' data-toggle='collapse' {{hook}}
     data-target='#uniqueId'>Show/hide data-2</a>
  <div class='collapse' id='uniqueId'>
    {{data-2}}
  </div>
</template>

Template.genericCollapse.helpers({
  hook () {
    $('[data-target="#uniqueId"]').addClass('collapsed');
    $('#uniqueId').removeClass('show');
  }
})

Works like a charm.


问:
Android Studio 3.0.1 does not find device
After I updted Android Studio to 3.0.1 my device was not found anymore (it worked perfectly before).

What I already tryed:

switching usb port and cable (should not be the problem anyway since it worked before)

turn my phone to PTP and back

checking if google usb drivers are installed in sdk

I dont know how I can get it back to work and I dont know if it might be a bug of Android Studio becuase everything worked before.

My Device - OnePlus 3T

My OS on desktop - Windows 10

I hope somebody can help me here.

Thanks!

答:
install  Universal ADB Driver

and configure your device with this tool first and then your device will be found by android studio


问:
How call jQuery function in AngularJS controller?
I have the following html:

```<code><iframe name='iframe1' id="iframe1" src='http://micro.shoretel.com" frameborder='0' width='660' height='450'></iframe>
</code>```

And the jQuery:

```<code>$("iframe").contents().find("element-selector").css("border-color", "blue");
</code>```

I want to do:

```<code>app.controller("myCntrl", function ($scope, angularService, $modal) {

        $scope.deletePrepared = function (itm) {
            var getData = angularService.DeletePrepared(itm.ProductId);
            getData.then(function (msg) {
                GetAllPrepared();
            }, function () {
$("iframe").contents().find("element-selector").css("border-color", "blue");});}});
</code>```

What is the mistake can be?

答:
From the Docs:

To use jQuery, simply ensure it is loaded before the angular.js file. You can also use the ngJq directive to specify that jqlite should be used over jQuery, or to use a specific version of jQuery if multiple versions exist on the page.

—AngularJS angular.element API Reference

Body:
I have the following html:

And the jQuery:

$("iframe").contents().find("element-selector").css("border-color", "blue");

I want to do:

app.controller("myCntrl", function ($scope, angularService, $modal) {

        $scope.deletePrepared = function (itm) {
            var getData = angularService.DeletePrepared(itm.ProductId);
            getData.then(function (msg) {
                GetAllPrepared();
            }, function () {
$("iframe").contents().find("element-selector").css("border-color", "blue");});}});

What is the mistake can be?


问:
Object of class ORM could not be converted to string Using Idiorm
I Want to show a field (bal) from the last insert row from a spefic day.

```<code>$BALdata171201 = ORM::for_table('sys_transactions')->where('date',$data171201)->select('bal')->order_by_desc('id')->limit(1)
</code>```

But I keep getting the error:

Catchable fatal error: Object of class ORM could not be converted to string

How can I make a ORM object transform in a string?

I already have read dozens of answers for this problem but I don't find any solution.

If I use var_dump I get:

```<code>object(IdiormResultSet)#132 (1) {
  ["_results":protected]=>
  array(1) {
    [0]=>
    object(ORM)#131 (22) {
      ["_connection_name":protected]=>
      string(7) "default"
      ["_table_name":protected]=>
      string(16) "sys_transactions"
      ["_table_alias":protected]=>
      NULL
      ["_values":protected]=>
      array(0) {
      }
      ["_result_columns":protected]=>
      array(1) {
        [0]=>
        string(1) "*"
      }
      ["_using_default_result_columns":protected]=>
      bool(true)
      ["_join_sources":protected]=>
      array(0) {
      }
      ["_distinct":protected]=>
      bool(false)
      ["_is_raw_query":protected]=>
      bool(false)
      ["_raw_query":protected]=>
      string(0) ""
      ["_raw_parameters":protected]=>
      array(0) {
      }
      ["_where_conditions":protected]=>
      array(0) {
      }
      ["_limit":protected]=>
      NULL
      ["_offset":protected]=>
      NULL
      ["_order_by":protected]=>
      array(0) {
      }
      ["_group_by":protected]=>
      array(0) {
      }
      ["_having_conditions":protected]=>
      array(0) {
      }
      ["_data":protected]=>
      array(1) {
        ["bal"]=>
        string(7) "1354.00"
      }
      ["_dirty_fields":protected]=>
      array(0) {
      }
      ["_expr_fields":protected]=>
      array(0) {
      }
      ["_is_new":protected]=>
      bool(false)
      ["_instance_id_column":protected]=>
      NULL
    }
  }
}
</code>```

I Already have tried do a $BALdata171201string = $BALdata171201string->_data;
But I got a empty echo.

答:
I have solved my problem.

In front end I was calling using:
{$BALdata171201}

Now I'm using:

```<code>{foreach $BALdata171201 as $b01s} <b>Balanço</b></br>R$ {$b01s['bal']}{/foreach}
</code>```

And work like a charm.

Body:
I Want to show a field (bal) from the last insert row from a spefic day.

$BALdata171201 = ORM::for_table('sys_transactions')->where('date',$data171201)->select('bal')->order_by_desc('id')->limit(1)

But I keep getting the error:

Catchable fatal error: Object of class ORM could not be converted to string

How can I make a ORM object transform in a string?

I already have read dozens of answers for this problem but I don't find any solution.

If I use var_dump I get:

object(IdiormResultSet)#132 (1) {
  ["_results":protected]=>
  array(1) {
    [0]=>
    object(ORM)#131 (22) {
      ["_connection_name":protected]=>
      string(7) "default"
      ["_table_name":protected]=>
      string(16) "sys_transactions"
      ["_table_alias":protected]=>
      NULL
      ["_values":protected]=>
      array(0) {
      }
      ["_result_columns":protected]=>
      array(1) {
        [0]=>
        string(1) "*"
      }
      ["_using_default_result_columns":protected]=>
      bool(true)
      ["_join_sources":protected]=>
      array(0) {
      }
      ["_distinct":protected]=>
      bool(false)
      ["_is_raw_query":protected]=>
      bool(false)
      ["_raw_query":protected]=>
      string(0) ""
      ["_raw_parameters":protected]=>
      array(0) {
      }
      ["_where_conditions":protected]=>
      array(0) {
      }
      ["_limit":protected]=>
      NULL
      ["_offset":protected]=>
      NULL
      ["_order_by":protected]=>
      array(0) {
      }
      ["_group_by":protected]=>
      array(0) {
      }
      ["_having_conditions":protected]=>
      array(0) {
      }
      ["_data":protected]=>
      array(1) {
        ["bal"]=>
        string(7) "1354.00"
      }
      ["_dirty_fields":protected]=>
      array(0) {
      }
      ["_expr_fields":protected]=>
      array(0) {
      }
      ["_is_new":protected]=>
      bool(false)
      ["_instance_id_column":protected]=>
      NULL
    }
  }
}

I Already have tried do a $BALdata171201string = $BALdata171201string->_data;
But I got a empty echo.

Body:
I have solved my problem.

In front end I was calling using:
{$BALdata171201}

Now I'm using:

{foreach $BALdata171201 as $b01s} <b>Balanço</b></br>R$ {$b01s['bal']}{/foreach}

And work like a charm.


问:
The php operator "->" for reference, doesn't work
I've come to a weird problem. When I try to compile this code:

```<code>try{
   throw new Exception("Error Processing Request");
}catch(Exception $e){
    echo $e->getMessage();
}
</code>```

I get this displayed on my web page:

"getMessage(); } ?>"

Everything after the first -> is displayed even the ?> at the end.

But everything seems to be correct, the extension of the file where the code is writed, the <php ?> is there also. There's any ";" left behind. The only suspect thing is that in sublim text 3, the -> is not "recognized". It's working on any other live web application, but not with my WAMP server.

I've tried different solutions like a blackslash -\>, but it doesn't work.

Someone can help? :/

答:
The correct code to start a peace of php code is:

```<code><?php
</code>```

and not

```<code><php
</code>```

See PHP: PHP tags

Body:
I've come to a weird problem. When I try to compile this code:

try{
   throw new Exception("Error Processing Request");
}catch(Exception $e){
    echo $e->getMessage();
}

I get this displayed on my web page:

"getMessage(); } ?>"

Everything after the first -> is displayed even the ?> at the end.

But everything seems to be correct, the extension of the file where the code is writed, the <php ?> is there also. There's any ";" left behind. The only suspect thing is that in sublim text 3, the -> is not "recognized". It's working on any other live web application, but not with my WAMP server.

I've tried different solutions like a blackslash -\>, but it doesn't work.

Someone can help? :/

Body:
The correct code to start a peace of php code is:

<?php

and not

<php

See PHP: PHP tags


问:
Is there a performance penalty when composing spark UDFs (rather than having UDFs as one)?
I'm wondering if there is a performance penalty by composing spark udf. In general, I prefer to compose small functions that do one thing …

Here is a trivial example, given a DataFrame df :

```<code>def inc = udf( (i: Double) => i + 1)
def double = udf( (i: Double) => i * 2)
df.withColumn("r", double(inc($"c")))
</code>```

versus

```<code>def incAndDouble = udf( (i: Double) => (i + 1) * 2)
df.withColumn("r", incAndDouble($"c")
</code>```

From what I've seen, performance are the same on this simple example.

Can you explain why ? How Spark works behind the scene ?

Is it always true ?

[update]

I may have a counterexample when a clever combination (not just a simple function composition) is possible, as in the following example

```<code>def filter = udf((s: Seq[String]) => s.startsWith("A"))
def size = udf((s: Seq[String]) => s.size)

val filterAndSize = udf((s: Seq[String]) => s.count(_.startsWith("A")))
</code>```

So, I guess that filterAndSize is preferable because it will avoid some intermediary collections instantiation.

答:
TL;DR There could be some performance degradation or penalty but it's negligible.

Can you explain why ?

That's quite funny to see your question with "explain" which is exactly the name of the method to use to see what happens under the covers of Spark SQL and how it executes queries :)

So, use Dataset.explain or even its more verbose version Dataset.explain(extended = true) to see all the optimizations (and possible performance degradations).

```<code>def inc = udf( (i: Double) => i + 1)
def double = udf( (i: Double) => i * 2)

val df = Seq(1,2,3).toDF("c")
val q = df.withColumn("r", double(inc($"c")))
</code>```

With the two UDFs composed the plans look as follows.

```<code>scala> q.explain(extended = true)
== Parsed Logical Plan ==
'Project [c#3, UDF(UDF('c)) AS r#10]
+- AnalysisBarrier Project [value#1 AS c#3]

== Analyzed Logical Plan ==
c: int, r: double
Project [c#3, if (isnull(if (isnull(cast(c#3 as double))) null else UDF(cast(c#3 as double)))) null else UDF(if (isnull(cast(c#3 as double))) null else UDF(cast(c#3 as double))) AS r#10]
+- Project [value#1 AS c#3]
   +- LocalRelation [value#1]

== Optimized Logical Plan ==
LocalRelation [c#3, r#10]

== Physical Plan ==
LocalTableScan [c#3, r#10]
</code>```

Let's see how the plans look like with one UDF that's a combination of the two UDFs.

```<code>def incAndDouble = udf( (i: Double) => (i + 1) * 2)
val q = df.withColumn("r", incAndDouble($"c"))
scala> q.explain(extended = true)
== Parsed Logical Plan ==
'Project [c#3, UDF('c) AS r#16]
+- AnalysisBarrier Project [value#1 AS c#3]

== Analyzed Logical Plan ==
c: int, r: double
Project [c#3, if (isnull(cast(c#3 as double))) null else UDF(cast(c#3 as double)) AS r#16]
+- Project [value#1 AS c#3]
   +- LocalRelation [value#1]

== Optimized Logical Plan ==
LocalRelation [c#3, r#16]

== Physical Plan ==
LocalTableScan [c#3, r#16]
</code>```

In this particular case, the difference is none since the physical plan is the same across the queries, i.e. LocalTableScan.

It could be different with other data sources like files or JDBC, but my personal recommendation is to develop UDFs as small as possible as they are black-boxes for Spark optimizer.

Is it always true ?

No, not at all as it heavily depends on what you do in your UDF (but that has more to do with whether to write a UDF in the first place or not).

In the case of the following UDF that is a predicate (i.e. returns a boolean):

```<code>def filter = udf((s: Seq[String]) => s.startsWith("A"))
</code>```

Spark could optimize the use of UDF (if it was not a UDF but a simple filter operation) and push it down to a data source to load less data. That could have a huge impact on the performance.

Body:
I'm wondering if there is a performance penalty by composing spark udf. In general, I prefer to compose small functions that do one thing …

Here is a trivial example, given a DataFrame df :

def inc = udf( (i: Double) => i + 1)
def double = udf( (i: Double) => i * 2)
df.withColumn("r", double(inc($"c")))

versus

def incAndDouble = udf( (i: Double) => (i + 1) * 2)
df.withColumn("r", incAndDouble($"c")

From what I've seen, performance are the same on this simple example.

Can you explain why ? How Spark works behind the scene ?

Is it always true ?

[update]

I may have a counterexample when a clever combination (not just a simple function composition) is possible, as in the following example

def filter = udf((s: Seq[String]) => s.startsWith("A"))
def size = udf((s: Seq[String]) => s.size)

val filterAndSize = udf((s: Seq[String]) => s.count(_.startsWith("A")))

So, I guess that filterAndSize is preferable because it will avoid some intermediary collections instantiation.

Body:
TL;DR There could be some performance degradation or penalty but it's negligible.

Can you explain why ?

That's quite funny to see your question with "explain" which is exactly the name of the method to use to see what happens under the covers of Spark SQL and how it executes queries :)

So, use Dataset.explain or even its more verbose version Dataset.explain(extended = true) to see all the optimizations (and possible performance degradations).

def inc = udf( (i: Double) => i + 1)
def double = udf( (i: Double) => i * 2)

val df = Seq(1,2,3).toDF("c")
val q = df.withColumn("r", double(inc($"c")))

With the two UDFs composed the plans look as follows.

scala> q.explain(extended = true)
== Parsed Logical Plan ==
'Project [c#3, UDF(UDF('c)) AS r#10]
+- AnalysisBarrier Project [value#1 AS c#3]

== Analyzed Logical Plan ==
c: int, r: double
Project [c#3, if (isnull(if (isnull(cast(c#3 as double))) null else UDF(cast(c#3 as double)))) null else UDF(if (isnull(cast(c#3 as double))) null else UDF(cast(c#3 as double))) AS r#10]
+- Project [value#1 AS c#3]
   +- LocalRelation [value#1]

== Optimized Logical Plan ==
LocalRelation [c#3, r#10]

== Physical Plan ==
LocalTableScan [c#3, r#10]

Let's see how the plans look like with one UDF that's a combination of the two UDFs.

def incAndDouble = udf( (i: Double) => (i + 1) * 2)
val q = df.withColumn("r", incAndDouble($"c"))
scala> q.explain(extended = true)
== Parsed Logical Plan ==
'Project [c#3, UDF('c) AS r#16]
+- AnalysisBarrier Project [value#1 AS c#3]

== Analyzed Logical Plan ==
c: int, r: double
Project [c#3, if (isnull(cast(c#3 as double))) null else UDF(cast(c#3 as double)) AS r#16]
+- Project [value#1 AS c#3]
   +- LocalRelation [value#1]

== Optimized Logical Plan ==
LocalRelation [c#3, r#16]

== Physical Plan ==
LocalTableScan [c#3, r#16]

In this particular case, the difference is none since the physical plan is the same across the queries, i.e. LocalTableScan.

It could be different with other data sources like files or JDBC, but my personal recommendation is to develop UDFs as small as possible as they are black-boxes for Spark optimizer.

Is it always true ?

No, not at all as it heavily depends on what you do in your UDF (but that has more to do with whether to write a UDF in the first place or not).

In the case of the following UDF that is a predicate (i.e. returns a boolean):

def filter = udf((s: Seq[String]) => s.startsWith("A"))

Spark could optimize the use of UDF (if it was not a UDF but a simple filter operation) and push it down to a data source to load less data. That could have a huge impact on the performance.


问:
Taking different Inputs in single line of Python
I am trying to take input from a single line in Python but it's not working.

Error:

```<code>Traceback (most recent call last):
File "solution.py", line 4, in <module>
a = int(input())
ValueError: invalid literal for int() with base 10: '1 4'
</code>```

Code:

```<code>q = int(input())
lis = []
for i in range(q) :
  a = int(input())
  print(a)
  if(a==1) :
    b = int(input())
    lis.append(b)
  else :
    print("Do Nothing")
</code>```

In this code for a given integer i.e.,q.

I have to take two inputs and if the first integer is 1 then we have to add the second input to the array.

Form input:

```<code>5
1 4
1 9
</code>```

If input of first line is 1, we have to add 4 to list. I am unable to take input in line 1 as only 1 it is taking both 1 4.

答:
Split the input, then convert to int, then do whatever</p>

```<code>a = input().split()
a=[int(x) for x in a]
#a is now a list of ints
....#do other stuff
</code>```

Body:
I am trying to take input from a single line in Python but it's not working.

Error:

Traceback (most recent call last):
File "solution.py", line 4, in <module>
a = int(input())
ValueError: invalid literal for int() with base 10: '1 4'

Code:

q = int(input())
lis = []
for i in range(q) :
  a = int(input())
  print(a)
  if(a==1) :
    b = int(input())
    lis.append(b)
  else :
    print("Do Nothing")

In this code for a given integer i.e.,q.

I have to take two inputs and if the first integer is 1 then we have to add the second input to the array.

Form input:

5
1 4
1 9

If input of first line is 1, we have to add 4 to list. I am unable to take input in line 1 as only 1 it is taking both 1 4.

Body:
Split the input, then convert to int, then do whatever

a = input().split()
a=[int(x) for x in a]
#a is now a list of ints
....#do other stuff


问:
Windows path with no slash after drive letter and colon - what does it point to?
I have mistyped a path and instead of c:\foo.txt wrote c:foo.txt. I expected it to either fail or to resolve to c:\foo.txt, but instead it seems to be resolved to foo.txt in a current user's home folder.

Powershell returns:

```<code>PS C:\> [System.IO.Path]::GetFullPath("c:\foo.txt")
c:\foo.txt
PS C:\> [System.IO.Path]::GetFullPath("c:foo.txt")
C:\Users\Administrator\foo.txt
PS C:\> [System.IO.Path]::GetFullPath("g:foo.txt")
G:\foo.txt
</code>```

Running explorer.exe from commandline and passing it any of the above results in C:\Users\Administrator\Documents to be opened.

I haven't found any documentation of that and I'm utterly confused, please explain the behaviour.

答:
Here is the documentation/explanation, courtesy of Harry Johnston's comment.

MSDN --> Windows desktop applications --> Develop --> Desktop technologies --> Data Access and Storage --> Local File Systems --> File Management --> About File Management --> Creating, Deleting, and Maintaining Files --> Naming Files, Paths, and Namespaces --> Fully Qualified vs. Relative Paths

For Windows API functions that manipulate files, file names can often
  be relative to the current directory, while some APIs require a fully
  qualified path. A file name is relative to the current directory if it
  does not begin with one of the following:

A UNC name of any format, which always start with two backslash characters ("\"). For more information, see the next section.

A disk designator with a backslash, for example "C:\" or "d:\".

A single backslash, for example, "\directory" or "\file.txt". This is also referred to as an absolute path.

If a file name begins with only a disk designator but not the
  backslash after the colon, it is interpreted as a relative path to the
  current directory on the drive with the specified letter. Note that
  the current directory may or may not be the root directory depending
  on what it was set to during the most recent "change directory"
  operation on that disk. Examples of this format are as follows:

"C:tmp.txt" refers to a file named "tmp.txt" in the current directory on drive C.

"C:tempdir\tmp.txt" refers to a file in a subdirectory to the current directory on drive C.

[...]

Body:
I have mistyped a path and instead of c:\foo.txt wrote c:foo.txt. I expected it to either fail or to resolve to c:\foo.txt, but instead it seems to be resolved to foo.txt in a current user's home folder.

Powershell returns:

PS C:\> [System.IO.Path]::GetFullPath("c:\foo.txt")
c:\foo.txt
PS C:\> [System.IO.Path]::GetFullPath("c:foo.txt")
C:\Users\Administrator\foo.txt
PS C:\> [System.IO.Path]::GetFullPath("g:foo.txt")
G:\foo.txt

Running explorer.exe from commandline and passing it any of the above results in C:\Users\Administrator\Documents to be opened.

I haven't found any documentation of that and I'm utterly confused, please explain the behaviour.


问:
Sonar with Gradle Locally
We are trying to use Sonar for Code Analyzes locally

our plan is to host the project on travis in the future and make Sonar run there with gradle

our problem is that Sonar is always trying to connect to a server

what we have now in our build file is:

```<code>apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'jacoco'
apply plugin: 'sonar'
/* other tasks*/
sonar {

  project {
  name = "Late-Term-Assignment"
  language = "java"
  version = "1.0" // whatever version you want here.
  withProjectProperties { props ->
     props["sonar.jacoco.reportPath"] = "${buildDir}/reports/jacoco/jacoco.exec"}
  }
}
</code>```

the error that we get is:

```<code>* What went wrong:
Executin failed for task ':sonarAnalyze'.
> java.net.ConnectionException: Connection refused: connect
</code>```

Is there any way to get Sonar to run on code that is stored locally?

best wishes and thank you in advance!

答: We have Sonar server and we use SonarLint plugin configured in our IDE (IntelliJ IDEA). This plugin pointed to our Sonar server and in IDE appears warnings for code which have been checked on the fly according rules from our Sonar server.</p>

Title: Sonar with Gradle Locally

Body:
We are trying to use Sonar for Code Analyzes locally

our plan is to host the project on travis in the future and make Sonar run there with gradle

our problem is that Sonar is always trying to connect to a server

what we have now in our build file is:

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'jacoco'
apply plugin: 'sonar'
/* other tasks*/
sonar {

  project {
  name = "Late-Term-Assignment"
  language = "java"
  version = "1.0" // whatever version you want here.
  withProjectProperties { props ->
     props["sonar.jacoco.reportPath"] = "${buildDir}/reports/jacoco/jacoco.exec"}
  }
}

the error that we get is:

* What went wrong:
Executin failed for task ':sonarAnalyze'.
> java.net.ConnectionException: Connection refused: connect

Is there any way to get Sonar to run on code that is stored locally?

best wishes and thank you in advance!


问:
Unable to archive in iTunes Store
When trying to upload my app, I get the error:
"You must supply a CFBundleIdentifier for this request". The identifiers (UTI format) in info.plist, "General Identity", iTunesConnect and App ID (Apple Developer) are all similar.

When getting the CFBundleIdentifier in applicationdidFinishLaunchingWithOptions: I get the same result.

I have changed the project name, maybe it has something to do with that?

Any suggestions? Thanks!

Info.plist

答: For Me It was all about checking Requires Full screen that option for iPad mainly .. and the error happen cause you may checked 3 Orientations for all devices .. but the iPad in multi-tasking is requiring the whole 4 orientations.. </p>

Title: Unable to archive in iTunes Store


问:
Is there any purpose to `bind()` unix domain socket client processes?
When using AF_UNIX (unix domain sockets), is there any application to calling bind() in a process that never calls listen()?

In my systems programming lecture and lab, we are instructed to callbind() on a unix domain socket client processes. Is there any documented, undocumented, or practical application to calling bind on a client-only unix domain socket  process? From my understanding bind() creates the special socket file, which is a responsibility a server process would undertake. Is this correct?

Here is an example code based off of what concepts discussed in class:

server.c

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0, s1;
    struct sockaddr sa0 = {AF_UNIX, "a"};

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);

    bind(s0, &sa0, sizeof(sa0) + sizeof("a"));
    listen(s0, 1);
    for (;;) {
        s1 = accept(s0, NULL, NULL);
        puts("connected!");
        for (;;) {
            char text[1];
            ssize_t n = read(s1, &text, sizeof(text));
            if (n < 1) {
                break;
            }
            putchar(text[0]);
        }
        close(s1);
    }
    close(s0);
    unlink("a");
    return 0;
}
</code>```

client.c

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0;
    struct sockaddr sa0 = {AF_UNIX, "b"};
    struct sockaddr sa1 = {AF_UNIX, "a"};
    socklen_t sa1_len;

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);
    bind(s0, &sa0, sizeof(sa0) + sizeof("b")); // What does this do??
    connect(s0, &sa1, sizeof(sa1) + sizeof("b"));
    for (;;) {
        int c = fgetc(stdin);
        if (c == EOF) {
            break;
        }
        write(s0, &c, sizeof(c));
    }
    close(s0);
    unlink("b");
    return 0;
}
</code>```

答:
man bind gives this answer:

```<code>   When  a  socket  is  created  with socket(2), it exists in a name space
   (address family) but has no address assigned to it.  bind() assigns the
   address  specified  by  addr  to  the  socket  referred  to by the file
   descriptor sockfd.  addrlen  specifies  the  size,  in  bytes,  of  the
   address structure pointed to by addr.  Traditionally, this operation is
   called “assigning a name to a socket”.

   It is normally necessary to assign a local address using bind()  before
   a SOCK_STREAM socket may receive connections (see accept(2)).
</code>```

Body:
When using AF_UNIX (unix domain sockets), is there any application to calling bind() in a process that never calls listen()?

In my systems programming lecture and lab, we are instructed to callbind() on a unix domain socket client processes. Is there any documented, undocumented, or practical application to calling bind on a client-only unix domain socket  process? From my understanding bind() creates the special socket file, which is a responsibility a server process would undertake. Is this correct?

Here is an example code based off of what concepts discussed in class:

server.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0, s1;
    struct sockaddr sa0 = {AF_UNIX, "a"};

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);

    bind(s0, &sa0, sizeof(sa0) + sizeof("a"));
    listen(s0, 1);
    for (;;) {
        s1 = accept(s0, NULL, NULL);
        puts("connected!");
        for (;;) {
            char text[1];
            ssize_t n = read(s1, &text, sizeof(text));
            if (n < 1) {
                break;
            }
            putchar(text[0]);
        }
        close(s1);
    }
    close(s0);
    unlink("a");
    return 0;
}

client.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0;
    struct sockaddr sa0 = {AF_UNIX, "b"};
    struct sockaddr sa1 = {AF_UNIX, "a"};
    socklen_t sa1_len;

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);
    bind(s0, &sa0, sizeof(sa0) + sizeof("b")); // What does this do??
    connect(s0, &sa1, sizeof(sa1) + sizeof("b"));
    for (;;) {
        int c = fgetc(stdin);
        if (c == EOF) {
            break;
        }
        write(s0, &c, sizeof(c));
    }
    close(s0);
    unlink("b");
    return 0;
}

Body:
man bind gives this answer:

   When  a  socket  is  created  with socket(2), it exists in a name space
   (address family) but has no address assigned to it.  bind() assigns the
   address  specified  by  addr  to  the  socket  referred  to by the file
   descriptor sockfd.  addrlen  specifies  the  size,  in  bytes,  of  the
   address structure pointed to by addr.  Traditionally, this operation is
   called “assigning a name to a socket”.

   It is normally necessary to assign a local address using bind()  before
   a SOCK_STREAM socket may receive connections (see accept(2)).


问:
Autosar Acceptance Test Diagnostic Services
I'm currently creating an acceptance test for Diagnostic Services.

How can I write a value to a memory of a DID?

Example Test Step:

[SWC]

Write 0x1A1B1C1D into memory of DID=0xFE88

[SWC] means that this step has to happen in the SWC.

Thank you!

答:
It is the job of the Dcm to do the actual write to the DID. The Dcm has the ability to fetch values from an application software component over a port-based connection, but the software component can never directly write to a DID.

Therefore, you need to define A PortPrototype on the side of the application that feeds the value into a compatible PortPrototype exposed by the Dcm service-component,and the latter needs to be configured to put the received value into the correct DID.


问:
ClassNotFoundException in
I have the following code. I have converted it into a jar

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.SQLContext

case class Student (StudentID: Long,
                                creationdate : java.sql.Timestamp,
                                mark1 : String,
                                mark2 : String
                               )

object Main {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("EMRCustomerApplication")
    conf.set("spark.driver.allowMultipleContexts","true")
    val spark = SparkSession
      .builder()
      .appName("Spark In Action")
      .master("local")
      .enableHiveSupport()
      .getOrCreate()
    System.setProperty("hive.metastore.uris", "thrift://internal-shared-hive-metastore-elb-550897717.us-west-2.elb.amazonaws.com:9083")
    System.setProperty("hive.metastore.execute.setugi", "false")
    System.setProperty("spark.driver.allowMultipleContexts","true")
    val sc = new SparkContext(conf)
    conf.set("spark.driver.allowMultipleContexts","true")
    import spark.implicits._

    val allRecordsDF = spark.sql(""" select * fromstudent """)

  }
}
</code>```

I am getting the below exception. I thought --class option is to mention the main class of the spark jar.This is the command that I executed.

```<code>spark-submit --class "Main" s3://Users/test/test_2.10-1.0.jar
</code>```

I have done that. Can anyone see what is the problem.

```<code>java.lang.ClassNotFoundException: Main
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:229)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:695)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Command exiting with ret '101'
</code>```

答: place the class under a package and try running it prefix the package to the class. </p>

Title: ClassNotFoundException in

Body:
I have the following code. I have converted it into a jar

import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.SQLContext

case class Student (StudentID: Long,
                                creationdate : java.sql.Timestamp,
                                mark1 : String,
                                mark2 : String
                               )

object Main {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("EMRCustomerApplication")
    conf.set("spark.driver.allowMultipleContexts","true")
    val spark = SparkSession
      .builder()
      .appName("Spark In Action")
      .master("local")
      .enableHiveSupport()
      .getOrCreate()
    System.setProperty("hive.metastore.uris", "thrift://internal-shared-hive-metastore-elb-550897717.us-west-2.elb.amazonaws.com:9083")
    System.setProperty("hive.metastore.execute.setugi", "false")
    System.setProperty("spark.driver.allowMultipleContexts","true")
    val sc = new SparkContext(conf)
    conf.set("spark.driver.allowMultipleContexts","true")
    import spark.implicits._

    val allRecordsDF = spark.sql(""" select * fromstudent """)

  }
}

I am getting the below exception. I thought --class option is to mention the main class of the spark jar.This is the command that I executed.

spark-submit --class "Main" s3://Users/test/test_2.10-1.0.jar

I have done that. Can anyone see what is the problem.

java.lang.ClassNotFoundException: Main
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:229)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:695)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Command exiting with ret '101'


问:
wcsncat_s show error assertion string is not null terminated
I want to append char. after succeful compile it show error assertion failure.

L"string is not null terminated. line 124

```<code>    #include <iostream>
    #include <windows.h>
    #include <string>

int main(){
    wchar_t jszProcessName[4096];
    wcsncat_s(jszProcessName, L"iloveyou", 1000);

    wcout << jszProcessName;
return 0;
}
</code>```

答:
Your uninitialized array probably doesn't have a value of 0 which is what the  wcsncat_s function expects. Either zero initialize the array first:

```<code>wchar_t jszProcessName[4096] = {};
</code>```

or set the first element to a null terminator character:

```<code>jszProcessName[0] = L'\0';
</code>```

which is equivalent to an integral value of 0:

```<code>jszProcessName[0] = 0;
</code>```

Without it your wcsncat_s function invokes undefined behavior.

Body:
I want to append char. after succeful compile it show error assertion failure.

L"string is not null terminated. line 124

    #include <iostream>
    #include <windows.h>
    #include <string>

int main(){
    wchar_t jszProcessName[4096];
    wcsncat_s(jszProcessName, L"iloveyou", 1000);

    wcout << jszProcessName;
return 0;
}

Body:
Your uninitialized array probably doesn't have a value of 0 which is what the  wcsncat_s function expects. Either zero initialize the array first:

wchar_t jszProcessName[4096] = {};

or set the first element to a null terminator character:

jszProcessName[0] = L'\0';

which is equivalent to an integral value of 0:

jszProcessName[0] = 0;

Without it your wcsncat_s function invokes undefined behavior.


问:
Database Relationships in Laravel
I have Author model that looks like this:

```<code><?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Author extends Model {
   public $timestamps = false;

   public function role()
   {
    return $this->hasOne('App\Role');
  }
}
</code>```

And Role model that looks like:

```<code><?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Role extends Model {
   public $timestamps = false;
}
</code>```

My AuthorController.php looks like:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Author;

class AuthorController extends Controller
{
  public function index(){
    $role = Author::find(5)->role->pareigos;

    return view('authors', ['role' => $role]);
  }
}
</code>```

But I get error like:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'roles.author_id' in 'where clause' (SQL: select * from roles where
  roles.author_id = 5 and roles.author_id is not null limit 1)

Where does the author_id even come from?

I have two tables in database, first one is authors that has id,firstname,lastname,role_id. Second one is roles that has two rows - id and pareigos. So I use this command:

```<code>$role = Author::find(5)->role->pareigos;
</code>```

To find Author by id (5) and check his role_id in roles table and return pareigos if the ID's matches.

Don't know if I have described the problem clearly - if not, just let me know I eill add more details.

答:
Your relationship is setup incorrectly. The table that has the key pointing to another table, belongs to that other table.

```<code>class Author ...
{
    public function role()
    {
        return $this->belongsTo(Role::class);
    }
    ...
</code>```

This will want to look for a role_id key on authors table.  By default, unless you pass more arguments to override it, Laravel uses the calling function name to decide the name of the foreign key for belongsTo relationships.  [ method is named role, so it knows to look for role_id ... methodname + _id ]

Title: Database Relationships in Laravel

Body:
I have Author model that looks like this:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Author extends Model {
   public $timestamps = false;

   public function role()
   {
    return $this->hasOne('App\Role');
  }
}

And Role model that looks like:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Role extends Model {
   public $timestamps = false;
}

My AuthorController.php looks like:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Author;

class AuthorController extends Controller
{
  public function index(){
    $role = Author::find(5)->role->pareigos;

    return view('authors', ['role' => $role]);
  }
}

But I get error like:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'roles.author_id' in 'where clause' (SQL: select * from roles where
  roles.author_id = 5 and roles.author_id is not null limit 1)

Where does the author_id even come from?

I have two tables in database, first one is authors that has id,firstname,lastname,role_id. Second one is roles that has two rows - id and pareigos. So I use this command:

$role = Author::find(5)->role->pareigos;

To find Author by id (5) and check his role_id in roles table and return pareigos if the ID's matches.

Don't know if I have described the problem clearly - if not, just let me know I eill add more details.

Body:
Your relationship is setup incorrectly. The table that has the key pointing to another table, belongs to that other table.

class Author ...
{
    public function role()
    {
        return $this->belongsTo(Role::class);
    }
    ...

This will want to look for a role_id key on authors table.  By default, unless you pass more arguments to override it, Laravel uses the calling function name to decide the name of the foreign key for belongsTo relationships.  [ method is named role, so it knows to look for role_id ... methodname + _id ]


问:
Remove rows having same value in all columns
I have a pandas dataframe that I'm trying to drop rows based on all columns having exact same value. Here's an example to help understand the idea.

Input:

```<code>index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 1     2  2  2  2  2  2
 2     5  5  5  5  5  5
 3     7  7  6  7  7  7
</code>```

Output:

```<code>index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 3     7  7  6  7  7  7
</code>```

There can be many columns here.

答:
Yet another efficient (well not that fast as @ayhan's solution) way:

```<code>In [17]: df[~df.eq(df.iloc[:, 0], axis=0).all(1)]
Out[17]:
       A  B  C  D  E  F
index
0      1  2  3  1  3  4
3      7  7  6  7  7  7
</code>```

Timing for 40.000 rows DF:

```<code>In [19]: df.shape
Out[19]: (40000, 6)

In [20]: %timeit df[df.std(axis=1) > 0]
5.62 ms ± 162 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [21]: %timeit df[df.nunique(1)>1]
9.87 s ± 104 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [23]: %timeit df[~df.eq(df.iloc[:, 0], axis=0).all(1)]
13 ms ± 86.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

Body:
I have a pandas dataframe that I'm trying to drop rows based on all columns having exact same value. Here's an example to help understand the idea.

Input:

index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 1     2  2  2  2  2  2
 2     5  5  5  5  5  5
 3     7  7  6  7  7  7

Output:

index  A  B  C  D  E  F ....
 0     1  2  3  1  3  4
 3     7  7  6  7  7  7

There can be many columns here.

Body:
Yet another efficient (well not that fast as @ayhan's solution) way:

In [17]: df[~df.eq(df.iloc[:, 0], axis=0).all(1)]
Out[17]:
       A  B  C  D  E  F
index
0      1  2  3  1  3  4
3      7  7  6  7  7  7

Timing for 40.000 rows DF:

In [19]: df.shape
Out[19]: (40000, 6)

In [20]: %timeit df[df.std(axis=1) > 0]
5.62 ms ± 162 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [21]: %timeit df[df.nunique(1)>1]
9.87 s ± 104 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [23]: %timeit df[~df.eq(df.iloc[:, 0], axis=0).all(1)]
13 ms ± 86.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


问:
load different js files for different pages or load together?
I have 3 pages of site.

Page 1: 19 kb of JS

  Page 2: 26 kb of JS

  Page 3: 10 kb of JS

  Total : 55 kb of JS

These javascript files are non repeating, means the JS needed on page 1 is not needed on page 2 and I have expiry headers set 1 month.

Still I would like to know what will be best way to load these files, should I load separate file for each page or I load these all together?

答: 55 kb isn't all that much.  However, it may be harder to update Page 2 when you have to deal with page 1 and 3 code.  Also, have you tried minifying the code that sounds like rather large javascript files.</p>


问:
Access violation freeing library that returns a interface for a class within the dll
I have a dll that contains a class that implements a interface. The dll has an exported method that returns the interface.

I can explicit load the dll succefully, but when I try to use Free Library I get Access Violation. I did not tried use implicit link, because I need use the explicit mode.

If I just load the library and free right after, without geting the interface, everything works fine.

Dll

```<code>library Tef;

uses
  uTTefFacade;

{$R *.res}

exports
  CreateTef;

begin
end.
</code>```

Interface in dll:

```<code>type
  ITefFacade = interface
  ['{77691DD1-C6E9-4F75-951F-BFA1468DC36C}']
    function IniciarTransacao(AParam: TTefIniciarTransacaoParamDTO): TTefIniciarTransacaoResultDTO;
  end;
</code>```

Class in dll:

```<code> type
      TTefFacade = class (TInterfacedObject, ITefFacade)
      private
        function IniciarTransacao(AParam: TTefIniciarTransacaoParamDTO): TTefIniciarTransacaoResultDTO;
      public
        constructor Create;
        destructor Free;
      end;

function CreateTef: ITefFacade; export; stdcall;

function CreateTef: ITefFacade;
begin
  Result := ITefFacade(TTefFacade.Create);
end;
</code>```

Exe:

```<code>procedure TForm1.FormCreate(Sender: TObject);
var
  CreateTef: function: ITefFacade; stdcall;
begin
  try
    FTef := nil;

    FHTef := LoadLibrary('Tef.dll');
    if (FHTef > 0) then
    begin
      @CreateTef := GetProcAddress(FHTef, 'CreateTef');
      if (@CreateTef <> nil) then
        FTef := CreateTef;
    end;

    if (FTef = nil) then
      ShowMessage('Error.');
  except
    on E: Exception do
      ShowMessage('Erro: ' + E.Message);
  end;
end;
</code>```

And here in the calling Free Library, access violation occurs.

```<code>procedure TForm1.FormDestroy(Sender: TObject);
begin
  FreeLibrary(FHTef);
end;
</code>```

答:
You have to nil the FTef reference before releasing the DLL.

The object behind the interface lives in the DLL, you should respect this. If you try to unload the DLL without releasing the interface first, there will be problems when the object is accessed after the unload (such as when Delphi auto-nils the reference when it goes out of scope).

Body:
I have a dll that contains a class that implements a interface. The dll has an exported method that returns the interface.

I can explicit load the dll succefully, but when I try to use Free Library I get Access Violation. I did not tried use implicit link, because I need use the explicit mode.

If I just load the library and free right after, without geting the interface, everything works fine.

Dll

library Tef;

uses
  uTTefFacade;

{$R *.res}

exports
  CreateTef;

begin
end.

Interface in dll:

type
  ITefFacade = interface
  ['{77691DD1-C6E9-4F75-951F-BFA1468DC36C}']
    function IniciarTransacao(AParam: TTefIniciarTransacaoParamDTO): TTefIniciarTransacaoResultDTO;
  end;

Class in dll:

 type
      TTefFacade = class (TInterfacedObject, ITefFacade)
      private
        function IniciarTransacao(AParam: TTefIniciarTransacaoParamDTO): TTefIniciarTransacaoResultDTO;
      public
        constructor Create;
        destructor Free;
      end;

function CreateTef: ITefFacade; export; stdcall;

function CreateTef: ITefFacade;
begin
  Result := ITefFacade(TTefFacade.Create);
end;

Exe:

procedure TForm1.FormCreate(Sender: TObject);
var
  CreateTef: function: ITefFacade; stdcall;
begin
  try
    FTef := nil;

    FHTef := LoadLibrary('Tef.dll');
    if (FHTef > 0) then
    begin
      @CreateTef := GetProcAddress(FHTef, 'CreateTef');
      if (@CreateTef <> nil) then
        FTef := CreateTef;
    end;

    if (FTef = nil) then
      ShowMessage('Error.');
  except
    on E: Exception do
      ShowMessage('Erro: ' + E.Message);
  end;
end;

And here in the calling Free Library, access violation occurs.

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FreeLibrary(FHTef);
end;


问:
VBA to update pivot field
I recorded this:

```<code>With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth")
        .PivotItems("2016-10").Visible = False
        .PivotItems("2017-11").Visible = True
    End With
</code>```

Each month, I run this report as a running 13. This was ran this month. We subtract two months back and then add one month back. I hope that makes sense. Anyway, while this code works for December, it isn't any good going to each month forward. I also need to address that each January the year is different.

I've come up with this:

```<code>Sub Update_Pivots()

Dim thisMonth As Integer
Dim lastMonth As Integer
Dim thisYear As Integer

If Month(Date) = 1 Then
    thisYear = Year(Date) - 1
    thisMonth = Month(Date) - 1
    lastMonth = Month(Date) - 2
Else
    thisYear = Year(Date)
    thisMonth = Month(Date) - 1
    lastMonth = Month(Date) - 2
End If

With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth")
    .PivotItems("[thisYear].&[-]&.[lastMonth]").Visible = False
    .PivotItems("[thisYear].&[-]&.[thisMonth]").Visible = True
End With

With ActiveSheet.PivotTables("PivotTable2").PivotFields("Min Closed Mth")
    .PivotItems("[thisYear].&[-]&.[lastMonth]").Visible = False
    .PivotItems("[thisYear].&[-]&.[thisMonth]").Visible = True
End With

End Sub
</code>```

I get a run-time '1004 error
        Unable to get the PivotItems property of the PivotField class.

Nevermind that while the dates work for January, they don't for February because thisMonth and Year should be current but lastMonth and year should have previous year.

This is my first post. I've been doing a lot of simple stuff with VBA but now because of that, I'm being asked to do more.

Appreciate the help.

答:
Just use DateAdd to calculate the correct months, and then format that as "yyyy-mm":

```<code>Sub Update_Pivots()

    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth")
        .PivotItems(Format(DateAdd("m", -14, Date),"yyyy-mm")).Visible = False
        .PivotItems(Format(DateAdd("m", -1, Date),"yyyy-mm")).Visible = True
    End With

    With ActiveSheet.PivotTables("PivotTable2").PivotFields("Min Closed Mth")
        .PivotItems(Format(DateAdd("m", -14, Date),"yyyy-mm")).Visible = False
        .PivotItems(Format(DateAdd("m", -1, Date),"yyyy-mm")).Visible = True
    End With

End Sub
</code>```

Title: VBA to update pivot field

Body:
I recorded this:

With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth")
        .PivotItems("2016-10").Visible = False
        .PivotItems("2017-11").Visible = True
    End With

Each month, I run this report as a running 13. This was ran this month. We subtract two months back and then add one month back. I hope that makes sense. Anyway, while this code works for December, it isn't any good going to each month forward. I also need to address that each January the year is different.

I've come up with this:

Sub Update_Pivots()

Dim thisMonth As Integer
Dim lastMonth As Integer
Dim thisYear As Integer

If Month(Date) = 1 Then
    thisYear = Year(Date) - 1
    thisMonth = Month(Date) - 1
    lastMonth = Month(Date) - 2
Else
    thisYear = Year(Date)
    thisMonth = Month(Date) - 1
    lastMonth = Month(Date) - 2
End If

With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth")
    .PivotItems("[thisYear].&[-]&.[lastMonth]").Visible = False
    .PivotItems("[thisYear].&[-]&.[thisMonth]").Visible = True
End With

With ActiveSheet.PivotTables("PivotTable2").PivotFields("Min Closed Mth")
    .PivotItems("[thisYear].&[-]&.[lastMonth]").Visible = False
    .PivotItems("[thisYear].&[-]&.[thisMonth]").Visible = True
End With

End Sub

I get a run-time '1004 error
        Unable to get the PivotItems property of the PivotField class.

Nevermind that while the dates work for January, they don't for February because thisMonth and Year should be current but lastMonth and year should have previous year.

This is my first post. I've been doing a lot of simple stuff with VBA but now because of that, I'm being asked to do more.

Appreciate the help.

Body:
Just use DateAdd to calculate the correct months, and then format that as "yyyy-mm":

Sub Update_Pivots()

    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Min Closed Mth")
        .PivotItems(Format(DateAdd("m", -14, Date),"yyyy-mm")).Visible = False
        .PivotItems(Format(DateAdd("m", -1, Date),"yyyy-mm")).Visible = True
    End With

    With ActiveSheet.PivotTables("PivotTable2").PivotFields("Min Closed Mth")
        .PivotItems(Format(DateAdd("m", -14, Date),"yyyy-mm")).Visible = False
        .PivotItems(Format(DateAdd("m", -1, Date),"yyyy-mm")).Visible = True
    End With

End Sub


问:
Printing an Object with ngFor
I am pulling object from database:

objects content might be different so we dont know what will come from db.(i mean it might be lemons too)

I am trying to print this using ngfor.If i convert this object to an array i can print it like:

```<code>this.drops = Object.values(monster[this.randommnumber].drops);

<li *ngFor="let drop of drops">
   {{ drop }}
 </li>
</code>```

this will print
3 and 5 without apple and pixi.

what i am trying to do is print them with their names.(i mean apple:3,pixi:5)

i can do that without converting object to an array and just writing

```<code><li *ngFor="let drop of drops">
       Apple:{{ drop.apple }}
       Pixi:{{drop.pixi}}
     </li>
</code>```

but what i am going to do if data has lemons rather than apples?

thanks

答:
it's pretty simple, just map it as a key value pair

```<code>Component({
  selector: "app-root",
  template: `
  <li *ngFor="let drop of drops">
  {{ drop.key }} : {{drop.value}}
</li>
  `,
  styles: []
})
export class AppComponent {
  drops: any;
  _drops = {
    apples: 5,
    pixies: 6,
    lemons: 7
  };

  constructor() {
    this.drops = Object.keys(this._drops).map(x => { return { key: x, value : this._drops[x] } });

  }
}
</code>```

also try to find more elegant solution. I'm pretty sure you can make it without using an extra field for that.

Title: Printing an Object with ngFor

Body:
I am pulling object from database:

objects content might be different so we dont know what will come from db.(i mean it might be lemons too)

I am trying to print this using ngfor.If i convert this object to an array i can print it like:

this.drops = Object.values(monster[this.randommnumber].drops);

   {{ drop }}

this will print
3 and 5 without apple and pixi.

what i am trying to do is print them with their names.(i mean apple:3,pixi:5)

i can do that without converting object to an array and just writing

       Apple:{{ drop.apple }}
       Pixi:{{drop.pixi}}

but what i am going to do if data has lemons rather than apples?

thanks

Body:
it's pretty simple, just map it as a key value pair

Component({
  selector: "app-root",
  template: `
  <li *ngFor="let drop of drops">
  {{ drop.key }} : {{drop.value}}
</li>
  `,
  styles: []
})
export class AppComponent {
  drops: any;
  _drops = {
    apples: 5,
    pixies: 6,
    lemons: 7
  };

  constructor() {
    this.drops = Object.keys(this._drops).map(x => { return { key: x, value : this._drops[x] } });

  }
}

also try to find more elegant solution. I'm pretty sure you can make it without using an extra field for that.