问:
Creating Immutable JObject
I am trying to create an extension class of JObject, which is immutable.

If I create a class like below, can it prevent the actual JObject being modified?

```<code>public class ImmutableJObejct: JObject
{
    public readonly JObject JObject;
    public ImmutableJObejct(JObject jObject)
    {
        this.JObject = jObject;
    }
}
</code>```

Which is the right approach?
should I not be expending the code and implement each methods that I need from JOBject?

答:
Basically you could return a new instance of JObject each time.</p>

```<code>public class ImmutableJObejct
{
    private readonly JObject _jObject;

    public ImmutableJObejct(JObject jObject)
    {
        _jObject = jObject;
    }

    public JObject JObject
    {
        get { return new JObject(_jObject); }
    }
}
</code>```

Title: Creating Immutable JObject

Body:
I am trying to create an extension class of JObject, which is immutable.

If I create a class like below, can it prevent the actual JObject being modified?

public class ImmutableJObejct: JObject
{
    public readonly JObject JObject;
    public ImmutableJObejct(JObject jObject)
    {
        this.JObject = jObject;
    }
}

Which is the right approach?
should I not be expending the code and implement each methods that I need from JOBject?

Body:
Basically you could return a new instance of JObject each time.

public class ImmutableJObejct
{
    private readonly JObject _jObject;

    public ImmutableJObejct(JObject jObject)
    {
        _jObject = jObject;
    }

    public JObject JObject
    {
        get { return new JObject(_jObject); }
    }
}


来源: stackexchange

问:
Ionic 2 Events Not Passing Data To Different Page
I'm using Ionic 2 or 3 events in order to pass data from my login page to one of my Providers that's shared between my pages. After the user logs in, I want to send the token to my provider file and lock up all the routes. Essentially I want to write code such as:

if (token) {allow access to routes} else {no access}

```<code>  doLogin() {
    // this.navCtrl.setRoot('MenuPage')
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post(this.apiUrl + 'login', JSON.stringify(this.user), {headers:headers})
      .map(res => res.json())
      .subscribe(data => {
        this.events.publish('token:added', data.token)

        if(data.login === 'yes') {
          this.token = data.token;
          this.navCtrl.setRoot('MenuPage')
        }
        else {
          alert('Bad login cridentials');
        }
      })
  }
</code>```

Provider

```<code>  ionViewDidLoad() {
    console.log("are we here?")
    this.events.subscribe('token:added', (data) => {
      console.log('>>>>>>>>>>>>>>>>> token added is ', data)
    })
  }
</code>```

The interesting thing is, my provider is technically not ever loaded to the screen, so I'm not sure if I should be using ionViewDidLoad. But, just to test if ionViewDidLoad is the problem, I imported the function above in my menu page, but I am still not accessing the token: added data. I can see my "are we here?" string logged, but that's it.

I am getting the token back, users are logging in. I just want to authenticate the users using token that my server is sending to the front end.

Are there any other way to pass data from my login function to my providers w/o using the push method since my provider isn't going to be landed to the screen?

答:
Try this:

```<code>doLogin() {
 // this.navCtrl.setRoot('MenuPage')
 var self = this;
 let headers = new Headers();
 headers.append('Content-Type', 'application/json');

 this.http.post(this.apiUrl + 'login', JSON.stringify(this.user), {headers:headers})
  .map(res => res.json())
  .subscribe(data => {
    self.events.publish('token:added', data.token)

    if(data.login === 'yes') {
      self.token = data.token;
      self.navCtrl.setRoot('MenuPage')
    }
    else {
      alert('Bad login cridentials');
    }
  })
</code>```

}

In subscribe, your scope has changed so you cannot use this to reference to the outside scope. One way is to store your scope into a variable and use that variable as the global scope.

You can also try printing the scopes inside subscribe to get a better understanding.

```<code>console.log(self);
console.log(this);
</code>```

Let me know if this works!

ContentLicense: CC BY-SA 4.0

Body:
I'm using Ionic 2 or 3 events in order to pass data from my login page to one of my Providers that's shared between my pages. After the user logs in, I want to send the token to my provider file and lock up all the routes. Essentially I want to write code such as:

if (token) {allow access to routes} else {no access}

  doLogin() {
    // this.navCtrl.setRoot('MenuPage')
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post(this.apiUrl + 'login', JSON.stringify(this.user), {headers:headers})
      .map(res => res.json())
      .subscribe(data => {
        this.events.publish('token:added', data.token)

        if(data.login === 'yes') {
          this.token = data.token;
          this.navCtrl.setRoot('MenuPage')
        }
        else {
          alert('Bad login cridentials');
        }
      })
  }

Provider

  ionViewDidLoad() {
    console.log("are we here?")
    this.events.subscribe('token:added', (data) => {
      console.log('>>>>>>>>>>>>>>>>> token added is ', data)
    })
  }

The interesting thing is, my provider is technically not ever loaded to the screen, so I'm not sure if I should be using ionViewDidLoad. But, just to test if ionViewDidLoad is the problem, I imported the function above in my menu page, but I am still not accessing the token: added data. I can see my "are we here?" string logged, but that's it.

I am getting the token back, users are logging in. I just want to authenticate the users using token that my server is sending to the front end.

Are there any other way to pass data from my login function to my providers w/o using the push method since my provider isn't going to be landed to the screen?

Body:
Try this:

doLogin() {
 // this.navCtrl.setRoot('MenuPage')
 var self = this;
 let headers = new Headers();
 headers.append('Content-Type', 'application/json');

 this.http.post(this.apiUrl + 'login', JSON.stringify(this.user), {headers:headers})
  .map(res => res.json())
  .subscribe(data => {
    self.events.publish('token:added', data.token)

    if(data.login === 'yes') {
      self.token = data.token;
      self.navCtrl.setRoot('MenuPage')
    }
    else {
      alert('Bad login cridentials');
    }
  })

}

In subscribe, your scope has changed so you cannot use this to reference to the outside scope. One way is to store your scope into a variable and use that variable as the global scope.

You can also try printing the scopes inside subscribe to get a better understanding.

console.log(self);
console.log(this);

Let me know if this works!

ContentLicense: CC BY-SA 3.0


问:
Jupyter Notebook Error Downloading as PDF
I'm getting the error below when I try to download a jupyter notebook as a pdf on my mac.  I installed pandoc and basicTex yesterday, could the issue be that I didn't install latex?  Or is it some other issue?  Can anyone suggest how to fix it?</p>

```<code>Error:

nbconvert failed: PDF creating failed, captured latex output:
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017) (preloaded format=pdflatex)
 restricted \write18 enabled.
entering extended mode
(./notebook.tex
LaTeX2e <2017-04-15>
Babel <3.10> and hyphenation patterns for 22 language(s) loaded.
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/article.cls
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/size11.clo))
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/fontenc.sty
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/t1enc.def))
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/psnfss/palatino.sty)
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/graphicx.sty
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/keyval.sty)
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/graphics.sty
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/trig.sty)
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics-cfg/graphics.cfg)
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics-def/pdftex.def
(/usr/local/texlive/2017basic/texmf-dist/tex/generic/oberdiek/infwarerr.sty)
(/usr/local/texlive/2017basic/texmf-dist/tex/generic/oberdiek/ltxcmds.sty))))
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/caption/caption.sty
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/caption/caption3.sty))

! LaTeX Error: File `adjustbox.sty' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)

Enter file name:
! Emergency stop.
<read *>

l.42     \usepackage
                    {xcolor} % Allow colors to be defined^^M
!  ==> Fatal error occurred, no output PDF file produced!
Transcript written on notebook.log.
</code>```

答: I was able to solve the problem by just doing the full macTex install.</p>

Body:
I'm getting the error below when I try to download a jupyter notebook as a pdf on my mac.  I installed pandoc and basicTex yesterday, could the issue be that I didn't install latex?  Or is it some other issue?  Can anyone suggest how to fix it?

Error:

nbconvert failed: PDF creating failed, captured latex output:
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017) (preloaded format=pdflatex)
 restricted \write18 enabled.
entering extended mode
(./notebook.tex
LaTeX2e <2017-04-15>
Babel <3.10> and hyphenation patterns for 22 language(s) loaded.
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/article.cls
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/size11.clo))
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/fontenc.sty
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/base/t1enc.def))
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/psnfss/palatino.sty)
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/graphicx.sty
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/keyval.sty)
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/graphics.sty
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics/trig.sty)
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics-cfg/graphics.cfg)
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/graphics-def/pdftex.def
(/usr/local/texlive/2017basic/texmf-dist/tex/generic/oberdiek/infwarerr.sty)
(/usr/local/texlive/2017basic/texmf-dist/tex/generic/oberdiek/ltxcmds.sty))))
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/caption/caption.sty
(/usr/local/texlive/2017basic/texmf-dist/tex/latex/caption/caption3.sty))

! LaTeX Error: File `adjustbox.sty' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)

Enter file name:
! Emergency stop.
<read *>

l.42     \usepackage
                    {xcolor} % Allow colors to be defined^^M
!  ==> Fatal error occurred, no output PDF file produced!
Transcript written on notebook.log.


问:
How to treat apostrophe and right single quotation mark as the same character?
My database has stored some text that used the apostrophe and the various single quotation marks carelessly and interchangeably.

I now have to do a search function. What's the trick to match the apostrophe with the apostrophe and the various quotation marks, if not all then at least the right single quotation mark?

答:
You could use REPLACE, e.g.:

```<code>DECLARE @table table (Value varchar(255))

INSERT INTO @table
VALUES ('’'), ('‘'), ('''')

SELECT *
FROM @table
WHERE REPLACE(REPLACE(Value, '’', ''''), '‘', '''') LIKE '%''%'
</code>```

Body:
You could use REPLACE, e.g.:

DECLARE @table table (Value varchar(255))

INSERT INTO @table
VALUES ('’'), ('‘'), ('''')

SELECT *
FROM @table
WHERE REPLACE(REPLACE(Value, '’', ''''), '‘', '''') LIKE '%''%'


问:
pydocumentdb 2.3 x-ms-version header issue
I am using pydocumentdb to connect to the Azure Cosmos DB emulator running locally, all was working fine using pydocumentdb version 2.2.1.  Was advised by my IDE that version 2.3.0 of pydocumentdb was now available, so I upgraded it.  Now when I try to connect to the emulator, I receive the following error:

{"code":"BadRequest","message":"Invalid API version. Ensure a valid x-ms-version header value is passed.\r\nActivityId: 0e0acdab-8e0d-409e-b7fe-efec3bed3044"}

which I am pretty sure should be set to 2017-02-22 but I cannot figure out what changed and/or how to figure out what the client is sending.

答:
I tried to reproduce your issue but failed.

My pydocumentdb version is 2.3.0:

My python code:

```<code>import pydocumentdb;
import pydocumentdb.document_client as document_client

config = {
    'ENDPOINT': 'https://localhost:8081',
    'MASTERKEY': 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==',
    'DOCUMENTDB_DATABASE': 'db',
    'DOCUMENTDB_COLLECTION': 'testcoll'
};

# Initialize the Python DocumentDB client
client = document_client.DocumentClient(config['ENDPOINT'], {'masterKey': config['MASTERKEY']})

results = list(client.QueryDocuments('dbs/db/colls/testcoll', {'query': 'SELECT * FROM server s'}))

print(results)
</code>```

Output results:

It seems that the result is printed correctly.  Is my situation different from yours ? Please post your details of your related code.

In addition , you could use Fiddler to catch the HTTP request messages.

Update Answer :

I test the steps using Python 3.6.2 and it works fine too.

Body:
I tried to reproduce your issue but failed.

My pydocumentdb version is 2.3.0:

My python code:

import pydocumentdb;
import pydocumentdb.document_client as document_client

config = {
    'ENDPOINT': 'https://localhost:8081',
    'MASTERKEY': 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==',
    'DOCUMENTDB_DATABASE': 'db',
    'DOCUMENTDB_COLLECTION': 'testcoll'
};

# Initialize the Python DocumentDB client
client = document_client.DocumentClient(config['ENDPOINT'], {'masterKey': config['MASTERKEY']})

results = list(client.QueryDocuments('dbs/db/colls/testcoll', {'query': 'SELECT * FROM server s'}))

print(results)

Output results:

It seems that the result is printed correctly.  Is my situation different from yours ? Please post your details of your related code.

In addition , you could use Fiddler to catch the HTTP request messages.

Update Answer :

I test the steps using Python 3.6.2 and it works fine too.


问:
Make Mac OS X games with a windows computer. c#, Visual studio
Using a windows computer, is it possible to make a game for mac? With visual studio you can use Xamarin to make ios games, so is a there a way to do the same for mac without having to use a virtual machine?</p>

答:
Using purely visual studio... I don't know!

I know that it is possible to make cross platform games using an engine like unity:

https://unity3d.com/unity/features/multiplatform

Which uses C#, and integrates with visual studio.

There are probably other ways too!

For example, I think there is a way to make web apps with C# - which might be integrated with visual studio... but I haven't played around with it, or know what it's capabilities are.
https://code.msdn.microsoft.com/ASPNET-5-Create-Web-b8a44cce

Web apps should be cross compatible via browsers, I think... again, haven't really played around with it.


问:
Get folder structure along with folder/file sizes in python
After doing my research for this specific task I found at that most of the solution given for this kind of problem either return the list of all the files or the TOTAL size of the folder/file.

What I am trying to achieve is get an output in the CSV file stating the folder structure i.e. folders - sub folders - files (optional) along with the size information for EACH.

There is no specific format for the CSV. I just need to know the tree structure with the size of the folder/sub-folder.

The reason behind this is that we are moving from physical servers to the cloud. In order to verify whether all the data was retained correctly during conversion I need to make a similar list of all SHARED DRIVES which can later be validated.

Looking forward for meaningful insights. Thanks!

答: I believe you will have to use a combination of the solutions that you have already found. Such as 'os.listdir(path)' to get the contents of a directory, 'os.lstat(path).st_size' to get file size, and 'os.path.isdir(path)' and 'os.path.isfile(path)' to determine the type.</p>


问:
Youtube - iPhone - displaying UIWebView of video
I have a script in my app that loads a Youtube link in a section of the UIView, the link is provided by my server (mySQL/using php) and from that it is loaded... this script below works fine..... however...

Here is what I have right now, I was looking to remove the programmatically part (where it gives the dimensions and possibly replace it with a UIWebView) to it, so I could improvise using IB, this will help when my application launches, a quick animation occurs and then I want this youtube link to load and display after viewDidLoad is completed.

.h file:

```<code>- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame;
</code>```

.m file

```<code>//view did load function...

[self embedYouTube:youtubestring frame:CGRectMake(69,72,184,138)];

//after the view did load is closed I have..

- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame {
NSString *embedHTML = @"\
<html><head>\
<style type=\"text/css\">\
body {\
background-color: transparent;\
color: white;\
}\
</style>\
</head><body style=\"margin:0\">\
<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
</body></html>";
NSString *html = [NSString stringWithFormat:embedHTML, urlString, frame.size.width, frame.size.height];
UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];
[videoView loadHTMLString:html baseURL:nil];
[self.view addSubview:videoView];
[videoView release];
}
</code>```

any help would greatly be appreciated!! thanks

答:
Aehm, the iPhone doesn't have Flash. It never had and probably never will have. The only way to open youtube videos on the iPhone is via the youtube app, which plays them back in another format. An example for this is
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.youtube.com /v/oHg5SJYRHA0&f=gdata_videos&c=ytapi-my-clientID&d=nGF83uyVrg8eD4rfEkk22mDOl3qUImVMV6ramM"]];

You can find more detail here: http://apiblog.youtube.com/2009/02/youtube-apis-iphone-cool-mobile-apps.html

Body:
I have a script in my app that loads a Youtube link in a section of the UIView, the link is provided by my server (mySQL/using php) and from that it is loaded... this script below works fine..... however...

Here is what I have right now, I was looking to remove the programmatically part (where it gives the dimensions and possibly replace it with a UIWebView) to it, so I could improvise using IB, this will help when my application launches, a quick animation occurs and then I want this youtube link to load and display after viewDidLoad is completed.

.h file:

- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame;

.m file

//view did load function...

[self embedYouTube:youtubestring frame:CGRectMake(69,72,184,138)];

//after the view did load is closed I have..

- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame {
NSString *embedHTML = @"\
\
\
\
<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
";
NSString *html = [NSString stringWithFormat:embedHTML, urlString, frame.size.width, frame.size.height];
UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];
[videoView loadHTMLString:html baseURL:nil];
[self.view addSubview:videoView];
[videoView release];
}

any help would greatly be appreciated!! thanks

ContentLicense: CC BY-SA 2.5


问:
Advanced Multidimensional PHP JSON Parsing Issue
I have a large multidimensional JSON array that I am trying to parse with PHP (needs to be PHP due to constraints).  I have the below in a variable and then I am doing a

json_decode on this string.  I have tried with and without true to save as an array.

$json = json_decode($result,true);

then I try and reference even something simple like

$json['data']['cfgversion'] and it doesn't work.  I have also tried it without the true and using $json->data->cfgversion

What I am trying to get at is

"port_overrides": [{
            "port_idx": 6,
            "portconf_id": "59d18fe9b6081ed3f75d3355"
        }, {
            "autoneg": true,
            "isolation": false,
            "name": "Port 8",
            "op_mode": "switch",
            "poe_mode": "passthrough",
            "port_idx": 8,
            "portconf_id": "575797d9429272985a1db175",
            "stormctrl_bcast_enabled": false,
            "stormctrl_mcast_enabled": false,
            "stormctrl_ucast_enabled": false
        }],

I want to modify thing like portconf_id in that array and then push it back (this is for a Unifi Switch)

Any ideas would be great.  I have looked at the other JSOn PHP parsing answers and they don't seem to work for me with the below.  thanks in advance.

```<code>{
"data": [{
    "_id": "599cab6084aa6b25d7e356cd",
    "_uptime": 1857874,
    "adopted": true,
    "board_rev": 10,
    "bytes": 1057778283548,
    "cfgversion": "9ef05412066832e5",
    "config_network": {
        "dns1": "10.0.1.1",
        "dns2": "8.8.8.8",
        "gateway": "10.0.1.1",
        "ip": "10.0.1.15",
        "netmask": "255.255.255.0",
        "type": "static"
    },
    "connect_request_ip": "10.0.1.15",
    "connect_request_port": "42723",
    "considered_lost_at": 1510378663,
    "device_id": "599cab6084aa6b25d7e356cd",
    "dhcp_server_table": [],
    "dot1x_portctrl_enabled": false,
    "downlink_table": [{
        "full_duplex": true,
        "mac": "80:2a:a8:53:77:4b",
        "port_idx": 8,
        "speed": 1000
    }],
    "ethernet_table": [{
        "mac": "f0:9f:c2:1e:3c:d1",
        "name": "eth0",
        "num_port": 8
    }, {
        "mac": "f0:9f:c2:1e:3c:d2",
        "name": "srv0"
    }],
    "flowctrl_enabled": false,
    "fw_caps": 7685,
    "general_temperature": 0,
    "guest-num_sta": 0,
    "has_fan": false,
    "inform_authkey": "543fcde7cd54091e622a93686d1b3ecb",
    "inform_ip": "10.0.1.52",
    "inform_url": "http://10.0.1.52:8080/inform",
    "ip": "10.0.1.15",
    "jumboframe_enabled": false,
    "known_cfgversion": "9ef05412066832e5",
    "last_seen": 1510378492,
    "led_override": "default",
    "license_state": "registered",
    "locating": false,
    "mac": "f0:9f:c2:1e:3c:d1",
    "model": "US8",
    "name": "TV Room Switch",
    "next_heartbeat_at": 1510378549,
    "num_sta": 6,
    "overheating": false,
    "port_overrides": [{
        "port_idx": 6,
        "portconf_id": "59d18fe9b6081ed3f75d3355"
    }, {
        "autoneg": true,
        "isolation": false,
        "name": "Port 8",
        "op_mode": "switch",
        "poe_mode": "passthrough",
        "port_idx": 8,
        "portconf_id": "575797d9429272985a1db175",
        "stormctrl_bcast_enabled": false,
        "stormctrl_mcast_enabled": false,
        "stormctrl_ucast_enabled": false
    }],
    "port_table": [{
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 11439,
        "dot1x_mode": "auto",
        "dot1x_status": "authorized",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": true,
        "is_uplink": true,
        "jumbo": false,
        "lldp_table": [{
            "lldp_chassis_id": "80:2A:A8:5D:92:A4",
            "lldp_port_id": "0/15",
            "lldp_system_name": "MainSwitch"
        }],
        "masked": false,
        "media": "GE",
        "name": "Port 1",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 1,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 5988397,
        "rx_bytes": 396387817490,
        "rx_bytes-r": 2372,
        "rx_dropped": 92655,
        "rx_errors": 0,
        "rx_multicast": 8148687,
        "rx_packets": 606001308,
        "speed": 1000,
        "stp_pathcost": 0,
        "stp_state": "forwarding",
        "tx_broadcast": 1142032,
        "tx_bytes": 661390466058,
        "tx_bytes-r": 9066,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 871097,
        "tx_packets": 676585183,
        "up": true
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 2415,
        "dot1x_mode": "auto",
        "dot1x_status": "authorized",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": true,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 2",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 2,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 72457,
        "rx_bytes": 3344218780,
        "rx_bytes-r": 507,
        "rx_dropped": 3542,
        "rx_errors": 0,
        "rx_multicast": 144549,
        "rx_packets": 36641209,
        "speed": 1000,
        "stp_pathcost": 0,
        "stp_state": "forwarding",
        "tx_broadcast": 7058001,
        "tx_bytes": 160950919257,
        "tx_bytes-r": 1907,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 8813991,
        "tx_packets": 125070289,
        "up": true
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 10396,
        "dot1x_mode": "auto",
        "dot1x_status": "authorized",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": true,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 3",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 3,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 77,
        "rx_bytes": 3384400206,
        "rx_bytes-r": 8063,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 4150,
        "rx_packets": 6039069,
        "speed": 100,
        "stp_pathcost": 0,
        "stp_state": "forwarding",
        "tx_broadcast": 7130309,
        "tx_bytes": 3249279910,
        "tx_bytes-r": 2332,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 8954291,
        "tx_packets": 19408520,
        "up": true
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 0,
        "dot1x_mode": "n/a",
        "dot1x_status": "n/a",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": false,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 4",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 4,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 0,
        "rx_bytes": 0,
        "rx_bytes-r": 0,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 0,
        "speed": 0,
        "stp_pathcost": 0,
        "stp_state": "disabled",
        "tx_broadcast": 0,
        "tx_bytes": 0,
        "tx_bytes-r": 0,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 0,
        "tx_packets": 0,
        "up": false
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 0,
        "dot1x_mode": "n/a",
        "dot1x_status": "n/a",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": false,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 5",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 5,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 0,
        "rx_bytes": 0,
        "rx_bytes-r": 0,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 0,
        "speed": 0,
        "stp_pathcost": 0,
        "stp_state": "disabled",
        "tx_broadcast": 0,
        "tx_bytes": 0,
        "tx_bytes-r": 0,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 0,
        "tx_packets": 0,
        "up": false
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 0,
        "dot1x_mode": "n/a",
        "dot1x_status": "n/a",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": false,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 6",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 6,
        "port_poe": false,
        "portconf_id": "59d18fe9b6081ed3f75d3355",
        "rx_broadcast": 0,
        "rx_bytes": 0,
        "rx_bytes-r": 0,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 0,
        "speed": 0,
        "stp_pathcost": 0,
        "stp_state": "disabled",
        "tx_broadcast": 0,
        "tx_bytes": 0,
        "tx_bytes-r": 0,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 0,
        "tx_packets": 0,
        "up": false
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 0,
        "dot1x_mode": "n/a",
        "dot1x_status": "n/a",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": false,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 7",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 7,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 0,
        "rx_bytes": 0,
        "rx_bytes-r": 0,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 0,
        "speed": 0,
        "stp_pathcost": 0,
        "stp_state": "disabled",
        "tx_broadcast": 0,
        "tx_bytes": 0,
        "tx_bytes-r": 0,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 0,
        "tx_packets": 0,
        "up": false
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 2226,
        "dot1x_mode": "auto",
        "dot1x_status": "authorized",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": true,
        "is_uplink": false,
        "isolation": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 8",
        "op_mode": "switch",
        "poe_caps": 8,
        "poe_enable": true,
        "poe_mode": "passthrough",
        "poe_voltage": "48.00",
        "port_idx": 8,
        "port_poe": true,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 1012063,
        "rx_bytes": 655667898453,
        "rx_bytes-r": 362,
        "rx_dropped": 28656,
        "rx_errors": 0,
        "rx_multicast": 630304,
        "rx_packets": 634872135,
        "speed": 1000,
        "stormctrl_bcast_enabled": false,
        "stormctrl_mcast_enabled": false,
        "stormctrl_ucast_enabled": false,
        "stp_pathcost": 0,
        "stp_state": "forwarding",
        "tx_broadcast": 6116174,
        "tx_bytes": 239145629938,
        "tx_bytes-r": 1864,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 8341073,
        "tx_packets": 495246848,
        "up": true
    }],
    "power_source": "poe",
    "power_source_voltage": "48.00",
    "rx_bytes": 661390466058,
    "serial": "F09FC21E3CD1",
    "site_id": "575797d7429272985a1db16c",
    "ssh_session_table": [],
    "stat": {
        "bytes": 3.90939602E8,
        "datetime": "2017-11-11T04:10:00Z",
        "duration": 4950000.0,
        "o": "sw",
        "oid": "f0:9f:c2:1e:3c:d1",
        "port_1-rx_bytes": 6.9195452E7,
        "port_1-rx_dropped": 304.0,
        "port_1-rx_packets": 181516.0,
        "port_1-tx_bytes": 1.16929998E8,
        "port_1-tx_packets": 168689.0,
        "port_2-rx_bytes": 3303986.0,
        "port_2-rx_dropped": 9.0,
        "port_2-rx_packets": 11352.0,
        "port_2-tx_bytes": 1.0588899E7,
        "port_2-tx_packets": 56442.0,
        "port_3-rx_bytes": 8936568.0,
        "port_3-rx_packets": 15892.0,
        "port_3-tx_bytes": 1.1060388E7,
        "port_3-tx_packets": 61268.0,
        "port_8-rx_bytes": 1.04055643E8,
        "port_8-rx_dropped": 89.0,
        "port_8-rx_packets": 140018.0,
        "port_8-tx_bytes": 6.6868668E7,
        "port_8-tx_packets": 164236.0,
        "rx_bytes": 1.85491649E8,
        "rx_crypts": 0.0,
        "rx_dropped": 402.0,
        "rx_errors": 0.0,
        "rx_frags": 0.0,
        "rx_packets": 348778.0,
        "site_id": "575797d7429272985a1db16c",
        "sw": "f0:9f:c2:1e:3c:d1",
        "time": 1510373400000,
        "tx_bytes": 2.05447953E8,
        "tx_dropped": 0.0,
        "tx_errors": 0.0,
        "tx_packets": 450635.0,
        "tx_retries": 0.0
    },
    "state": 1,
    "stp_priority": "32768",
    "stp_version": "rstp",
    "sys_stats": {
        "loadavg_1": "1.26",
        "loadavg_15": "1.41",
        "loadavg_5": "1.31",
        "mem_buffer": 0,
        "mem_total": 262766592,
        "mem_used": 161001472
    },
    "tx_bytes": 396387817490,
    "type": "usw",
    "uplink": {
        "full_duplex": true,
        "ip": "10.0.1.15",
        "mac": "f0:9f:c2:1e:3c:d1",
        "max_speed": 1000,
        "media": "GE",
        "name": "eth0",
        "netmask": "255.255.255.0",
        "num_port": 8,
        "port_idx": 1,
        "rx_bytes": 396387817490,
        "rx_bytes-r": 2372,
        "rx_dropped": 92655,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 606001308,
        "speed": 1000,
        "tx_bytes": 661390466058,
        "tx_bytes-r": 9066,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_packets": 676585183,
        "type": "wire",
        "up": true,
        "uplink_mac": "80:2a:a8:5d:92:a4"
    },
    "uplink_depth": 2,
    "uptime": 1857874,
    "user-num_sta": 6,
    "version": "3.9.3.7537",
    "x_authkey": "543fcde7cd54091e622a93686d1b3ecb",
    "x_fingerprint": "65:06:32:75:3a:af:99:8a:92:14:0e:1d:6d:3f:6b:7b",
    "x_has_ssh_hostkey": true,
    "x_ssh_hostkey_fingerprint": "65:06:32:75:3a:af:99:8a:92:14:0e:1d:6d:3f:6b:7b"
}],
"meta": {
    "rc": "ok"
}
</code>```

}

答:
Lawrence has the correct answer

Its an array, you should be doing $json['data'][0]['cfgversion']

Body:
I have a large multidimensional JSON array that I am trying to parse with PHP (needs to be PHP due to constraints).  I have the below in a variable and then I am doing a

json_decode on this string.  I have tried with and without true to save as an array.

$json = json_decode($result,true);

then I try and reference even something simple like

$json['data']['cfgversion'] and it doesn't work.  I have also tried it without the true and using $json->data->cfgversion

What I am trying to get at is

"port_overrides": [{
            "port_idx": 6,
            "portconf_id": "59d18fe9b6081ed3f75d3355"
        }, {
            "autoneg": true,
            "isolation": false,
            "name": "Port 8",
            "op_mode": "switch",
            "poe_mode": "passthrough",
            "port_idx": 8,
            "portconf_id": "575797d9429272985a1db175",
            "stormctrl_bcast_enabled": false,
            "stormctrl_mcast_enabled": false,
            "stormctrl_ucast_enabled": false
        }],

I want to modify thing like portconf_id in that array and then push it back (this is for a Unifi Switch)

Any ideas would be great.  I have looked at the other JSOn PHP parsing answers and they don't seem to work for me with the below.  thanks in advance.

{
"data": [{
    "_id": "599cab6084aa6b25d7e356cd",
    "_uptime": 1857874,
    "adopted": true,
    "board_rev": 10,
    "bytes": 1057778283548,
    "cfgversion": "9ef05412066832e5",
    "config_network": {
        "dns1": "10.0.1.1",
        "dns2": "8.8.8.8",
        "gateway": "10.0.1.1",
        "ip": "10.0.1.15",
        "netmask": "255.255.255.0",
        "type": "static"
    },
    "connect_request_ip": "10.0.1.15",
    "connect_request_port": "42723",
    "considered_lost_at": 1510378663,
    "device_id": "599cab6084aa6b25d7e356cd",
    "dhcp_server_table": [],
    "dot1x_portctrl_enabled": false,
    "downlink_table": [{
        "full_duplex": true,
        "mac": "80:2a:a8:53:77:4b",
        "port_idx": 8,
        "speed": 1000
    }],
    "ethernet_table": [{
        "mac": "f0:9f:c2:1e:3c:d1",
        "name": "eth0",
        "num_port": 8
    }, {
        "mac": "f0:9f:c2:1e:3c:d2",
        "name": "srv0"
    }],
    "flowctrl_enabled": false,
    "fw_caps": 7685,
    "general_temperature": 0,
    "guest-num_sta": 0,
    "has_fan": false,
    "inform_authkey": "543fcde7cd54091e622a93686d1b3ecb",
    "inform_ip": "10.0.1.52",
    "inform_url": "http://10.0.1.52:8080/inform",
    "ip": "10.0.1.15",
    "jumboframe_enabled": false,
    "known_cfgversion": "9ef05412066832e5",
    "last_seen": 1510378492,
    "led_override": "default",
    "license_state": "registered",
    "locating": false,
    "mac": "f0:9f:c2:1e:3c:d1",
    "model": "US8",
    "name": "TV Room Switch",
    "next_heartbeat_at": 1510378549,
    "num_sta": 6,
    "overheating": false,
    "port_overrides": [{
        "port_idx": 6,
        "portconf_id": "59d18fe9b6081ed3f75d3355"
    }, {
        "autoneg": true,
        "isolation": false,
        "name": "Port 8",
        "op_mode": "switch",
        "poe_mode": "passthrough",
        "port_idx": 8,
        "portconf_id": "575797d9429272985a1db175",
        "stormctrl_bcast_enabled": false,
        "stormctrl_mcast_enabled": false,
        "stormctrl_ucast_enabled": false
    }],
    "port_table": [{
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 11439,
        "dot1x_mode": "auto",
        "dot1x_status": "authorized",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": true,
        "is_uplink": true,
        "jumbo": false,
        "lldp_table": [{
            "lldp_chassis_id": "80:2A:A8:5D:92:A4",
            "lldp_port_id": "0/15",
            "lldp_system_name": "MainSwitch"
        }],
        "masked": false,
        "media": "GE",
        "name": "Port 1",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 1,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 5988397,
        "rx_bytes": 396387817490,
        "rx_bytes-r": 2372,
        "rx_dropped": 92655,
        "rx_errors": 0,
        "rx_multicast": 8148687,
        "rx_packets": 606001308,
        "speed": 1000,
        "stp_pathcost": 0,
        "stp_state": "forwarding",
        "tx_broadcast": 1142032,
        "tx_bytes": 661390466058,
        "tx_bytes-r": 9066,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 871097,
        "tx_packets": 676585183,
        "up": true
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 2415,
        "dot1x_mode": "auto",
        "dot1x_status": "authorized",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": true,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 2",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 2,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 72457,
        "rx_bytes": 3344218780,
        "rx_bytes-r": 507,
        "rx_dropped": 3542,
        "rx_errors": 0,
        "rx_multicast": 144549,
        "rx_packets": 36641209,
        "speed": 1000,
        "stp_pathcost": 0,
        "stp_state": "forwarding",
        "tx_broadcast": 7058001,
        "tx_bytes": 160950919257,
        "tx_bytes-r": 1907,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 8813991,
        "tx_packets": 125070289,
        "up": true
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 10396,
        "dot1x_mode": "auto",
        "dot1x_status": "authorized",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": true,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 3",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 3,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 77,
        "rx_bytes": 3384400206,
        "rx_bytes-r": 8063,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 4150,
        "rx_packets": 6039069,
        "speed": 100,
        "stp_pathcost": 0,
        "stp_state": "forwarding",
        "tx_broadcast": 7130309,
        "tx_bytes": 3249279910,
        "tx_bytes-r": 2332,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 8954291,
        "tx_packets": 19408520,
        "up": true
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 0,
        "dot1x_mode": "n/a",
        "dot1x_status": "n/a",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": false,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 4",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 4,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 0,
        "rx_bytes": 0,
        "rx_bytes-r": 0,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 0,
        "speed": 0,
        "stp_pathcost": 0,
        "stp_state": "disabled",
        "tx_broadcast": 0,
        "tx_bytes": 0,
        "tx_bytes-r": 0,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 0,
        "tx_packets": 0,
        "up": false
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 0,
        "dot1x_mode": "n/a",
        "dot1x_status": "n/a",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": false,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 5",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 5,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 0,
        "rx_bytes": 0,
        "rx_bytes-r": 0,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 0,
        "speed": 0,
        "stp_pathcost": 0,
        "stp_state": "disabled",
        "tx_broadcast": 0,
        "tx_bytes": 0,
        "tx_bytes-r": 0,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 0,
        "tx_packets": 0,
        "up": false
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 0,
        "dot1x_mode": "n/a",
        "dot1x_status": "n/a",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": false,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 6",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 6,
        "port_poe": false,
        "portconf_id": "59d18fe9b6081ed3f75d3355",
        "rx_broadcast": 0,
        "rx_bytes": 0,
        "rx_bytes-r": 0,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 0,
        "speed": 0,
        "stp_pathcost": 0,
        "stp_state": "disabled",
        "tx_broadcast": 0,
        "tx_bytes": 0,
        "tx_bytes-r": 0,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 0,
        "tx_packets": 0,
        "up": false
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 0,
        "dot1x_mode": "n/a",
        "dot1x_status": "n/a",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": false,
        "is_uplink": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 7",
        "op_mode": "switch",
        "poe_caps": 0,
        "port_idx": 7,
        "port_poe": false,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 0,
        "rx_bytes": 0,
        "rx_bytes-r": 0,
        "rx_dropped": 0,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 0,
        "speed": 0,
        "stp_pathcost": 0,
        "stp_state": "disabled",
        "tx_broadcast": 0,
        "tx_bytes": 0,
        "tx_bytes-r": 0,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 0,
        "tx_packets": 0,
        "up": false
    }, {
        "aggregated_by": false,
        "autoneg": true,
        "bytes-r": 2226,
        "dot1x_mode": "auto",
        "dot1x_status": "authorized",
        "enable": true,
        "flowctrl_rx": false,
        "flowctrl_tx": false,
        "full_duplex": true,
        "is_uplink": false,
        "isolation": false,
        "jumbo": false,
        "lldp_table": [],
        "masked": false,
        "media": "GE",
        "name": "Port 8",
        "op_mode": "switch",
        "poe_caps": 8,
        "poe_enable": true,
        "poe_mode": "passthrough",
        "poe_voltage": "48.00",
        "port_idx": 8,
        "port_poe": true,
        "portconf_id": "575797d9429272985a1db175",
        "rx_broadcast": 1012063,
        "rx_bytes": 655667898453,
        "rx_bytes-r": 362,
        "rx_dropped": 28656,
        "rx_errors": 0,
        "rx_multicast": 630304,
        "rx_packets": 634872135,
        "speed": 1000,
        "stormctrl_bcast_enabled": false,
        "stormctrl_mcast_enabled": false,
        "stormctrl_ucast_enabled": false,
        "stp_pathcost": 0,
        "stp_state": "forwarding",
        "tx_broadcast": 6116174,
        "tx_bytes": 239145629938,
        "tx_bytes-r": 1864,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_multicast": 8341073,
        "tx_packets": 495246848,
        "up": true
    }],
    "power_source": "poe",
    "power_source_voltage": "48.00",
    "rx_bytes": 661390466058,
    "serial": "F09FC21E3CD1",
    "site_id": "575797d7429272985a1db16c",
    "ssh_session_table": [],
    "stat": {
        "bytes": 3.90939602E8,
        "datetime": "2017-11-11T04:10:00Z",
        "duration": 4950000.0,
        "o": "sw",
        "oid": "f0:9f:c2:1e:3c:d1",
        "port_1-rx_bytes": 6.9195452E7,
        "port_1-rx_dropped": 304.0,
        "port_1-rx_packets": 181516.0,
        "port_1-tx_bytes": 1.16929998E8,
        "port_1-tx_packets": 168689.0,
        "port_2-rx_bytes": 3303986.0,
        "port_2-rx_dropped": 9.0,
        "port_2-rx_packets": 11352.0,
        "port_2-tx_bytes": 1.0588899E7,
        "port_2-tx_packets": 56442.0,
        "port_3-rx_bytes": 8936568.0,
        "port_3-rx_packets": 15892.0,
        "port_3-tx_bytes": 1.1060388E7,
        "port_3-tx_packets": 61268.0,
        "port_8-rx_bytes": 1.04055643E8,
        "port_8-rx_dropped": 89.0,
        "port_8-rx_packets": 140018.0,
        "port_8-tx_bytes": 6.6868668E7,
        "port_8-tx_packets": 164236.0,
        "rx_bytes": 1.85491649E8,
        "rx_crypts": 0.0,
        "rx_dropped": 402.0,
        "rx_errors": 0.0,
        "rx_frags": 0.0,
        "rx_packets": 348778.0,
        "site_id": "575797d7429272985a1db16c",
        "sw": "f0:9f:c2:1e:3c:d1",
        "time": 1510373400000,
        "tx_bytes": 2.05447953E8,
        "tx_dropped": 0.0,
        "tx_errors": 0.0,
        "tx_packets": 450635.0,
        "tx_retries": 0.0
    },
    "state": 1,
    "stp_priority": "32768",
    "stp_version": "rstp",
    "sys_stats": {
        "loadavg_1": "1.26",
        "loadavg_15": "1.41",
        "loadavg_5": "1.31",
        "mem_buffer": 0,
        "mem_total": 262766592,
        "mem_used": 161001472
    },
    "tx_bytes": 396387817490,
    "type": "usw",
    "uplink": {
        "full_duplex": true,
        "ip": "10.0.1.15",
        "mac": "f0:9f:c2:1e:3c:d1",
        "max_speed": 1000,
        "media": "GE",
        "name": "eth0",
        "netmask": "255.255.255.0",
        "num_port": 8,
        "port_idx": 1,
        "rx_bytes": 396387817490,
        "rx_bytes-r": 2372,
        "rx_dropped": 92655,
        "rx_errors": 0,
        "rx_multicast": 0,
        "rx_packets": 606001308,
        "speed": 1000,
        "tx_bytes": 661390466058,
        "tx_bytes-r": 9066,
        "tx_dropped": 0,
        "tx_errors": 0,
        "tx_packets": 676585183,
        "type": "wire",
        "up": true,
        "uplink_mac": "80:2a:a8:5d:92:a4"
    },
    "uplink_depth": 2,
    "uptime": 1857874,
    "user-num_sta": 6,
    "version": "3.9.3.7537",
    "x_authkey": "543fcde7cd54091e622a93686d1b3ecb",
    "x_fingerprint": "65:06:32:75:3a:af:99:8a:92:14:0e:1d:6d:3f:6b:7b",
    "x_has_ssh_hostkey": true,
    "x_ssh_hostkey_fingerprint": "65:06:32:75:3a:af:99:8a:92:14:0e:1d:6d:3f:6b:7b"
}],
"meta": {
    "rc": "ok"
}

}


问:
how to query select data from table where first 3 character defined
i want to filter dropdownlist by first 3 charater on job code, this is my query</p>

```<code>string result3 = Checked_By.ToString().Substring(0, 3);

SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama]
FROM [Job] WHERE LEFT(Kode, = '" + result3 + "') ORDER BY
Nama ASC", con);

 SqlDataAdapter sda = new SqlDataAdapter(cmd);
 DataTable dt = new DataTable();
 con.Open();
 sda.Fill(dt);
 con.Close();
</code>```

答:
"SELECT [Kode], [Nama]
FROM [Job] WHERE SUBSTR(Kode,1,3) = '" + result3 + "' ORDER BY
Nama ASC"</p>

Body:
i want to filter dropdownlist by first 3 charater on job code, this is my query

string result3 = Checked_By.ToString().Substring(0, 3);

SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama]
FROM [Job] WHERE LEFT(Kode, = '" + result3 + "') ORDER BY
Nama ASC", con);

 SqlDataAdapter sda = new SqlDataAdapter(cmd);
 DataTable dt = new DataTable();
 con.Open();
 sda.Fill(dt);
 con.Close();


问:
System.ArgumentNullException occured in System.Web.Mvc.dll
I have an application where I need to input data and on submit the data gets saved in database. When I checked in database the input is getting saved successfully but I am getting an exception when the page reloads after httppost.
I am getting exception at :

```<code>  @Html.DropDownList("LineID", new SelectList(Model.dropConfig, "LineID", "LineID"), "-- Select LineID --", new { required = true, @class = "form-control" })
</code>```

controller code to get the dropdownlist values, binding with Db:

```<code>   [ActionName("DetailsForm")]
        [HttpGet]
        public ActionResult DetailsForm()
        {
            try
            {
                var model = new DetailsViewModel() { dropConfig = floorService.DropDownList().ToList() };
                return View("DetailsForm", model);

            }
            catch (Exception ex)
            {
                return View("_error");
            }
        }
</code>```

controller code to http post:

```<code> [ActionName("DetailsForm")]
        [HttpPost]

        public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
        {

            DetailsConfiguration detailsConfig = new DetailsConfiguration();

            detailsConfig.LineID = Convert.ToString(form["LineID"]);
            //Similary for other fields
            floorService.SaveDetails(detailsConfig);

            ModelState.Clear();
            ViewBag.message = "Success";

            return View("DetailsForm",model);

        }
</code>```

Snapshot of exception:

答:
Because your view code is using Model.dropConfig to build the SelectList for your dropdown, and you are not setting the dropConfig property value before returning to the view.

Remember, Http is stateless. So even though you set the dropConfig property value in the GET action, It won't be available inside your HttpPost action. When you submit your form, it is a totally new request to the server.

You can fix it by loading dropConfig property again.

```<code>model.dropConfig = floorService.DropDownList().ToList();
return View(model);
</code>```

But ideally you should be following the P-R-G pattern.

P-R-G stands for Post-Redirect-Get. So when you submit your form to an http post action method, you should return a redirect response and the browser will make a new GET call to that action method.

You can use the RedirectToAction method to return a redirect response.

```<code>floorService.SaveDetails(detailsConfig);
return RedirectToAction("DetailsForm");
</code>```

This will send a 302 response back to the browser with the location header set to the url to the DetailsForm action method and the browser will make a new GET request to that.

ViewBag won't work when with redirect response. So you might consider using TempData. TempData can be used to transfer between two requests.

```<code>TempData["message"] = "Success";
return RedirectToAction("DetailsForm");
</code>```

Now you can read TempData["message"] in the DetailsForm action method or the view rendered by that.

For example, you can read it in the view (rendered by DetailsForm GET action method) like this

```<code>@if (TempData["message"]!=null)
{
 <div class="alert alert-success" id="alert">
      <button type="button" class="close" data-dismiss="alert">x</button>
    <strong>Success! </strong>@TempData["message"]
  </div>
}
</code>```

Body:
I have an application where I need to input data and on submit the data gets saved in database. When I checked in database the input is getting saved successfully but I am getting an exception when the page reloads after httppost.
I am getting exception at :

  @Html.DropDownList("LineID", new SelectList(Model.dropConfig, "LineID", "LineID"), "-- Select LineID --", new { required = true, @class = "form-control" })

controller code to get the dropdownlist values, binding with Db:

   [ActionName("DetailsForm")]
        [HttpGet]
        public ActionResult DetailsForm()
        {
            try
            {
                var model = new DetailsViewModel() { dropConfig = floorService.DropDownList().ToList() };
                return View("DetailsForm", model);

            }
            catch (Exception ex)
            {
                return View("_error");
            }
        }

controller code to http post:

 [ActionName("DetailsForm")]
        [HttpPost]

        public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
        {

            DetailsConfiguration detailsConfig = new DetailsConfiguration();

            detailsConfig.LineID = Convert.ToString(form["LineID"]);
            //Similary for other fields
            floorService.SaveDetails(detailsConfig);

            ModelState.Clear();
            ViewBag.message = "Success";

            return View("DetailsForm",model);

        }

Snapshot of exception:

Body:
Because your view code is using Model.dropConfig to build the SelectList for your dropdown, and you are not setting the dropConfig property value before returning to the view.

Remember, Http is stateless. So even though you set the dropConfig property value in the GET action, It won't be available inside your HttpPost action. When you submit your form, it is a totally new request to the server.

You can fix it by loading dropConfig property again.

model.dropConfig = floorService.DropDownList().ToList();
return View(model);

But ideally you should be following the P-R-G pattern.

P-R-G stands for Post-Redirect-Get. So when you submit your form to an http post action method, you should return a redirect response and the browser will make a new GET call to that action method.

You can use the RedirectToAction method to return a redirect response.

floorService.SaveDetails(detailsConfig);
return RedirectToAction("DetailsForm");

This will send a 302 response back to the browser with the location header set to the url to the DetailsForm action method and the browser will make a new GET request to that.

ViewBag won't work when with redirect response. So you might consider using TempData. TempData can be used to transfer between two requests.

TempData["message"] = "Success";
return RedirectToAction("DetailsForm");

Now you can read TempData["message"] in the DetailsForm action method or the view rendered by that.

For example, you can read it in the view (rendered by DetailsForm GET action method) like this

@if (TempData["message"]!=null)
{
 <div class="alert alert-success" id="alert">
      <button type="button" class="close" data-dismiss="alert">x</button>
    <strong>Success! </strong>@TempData["message"]
  </div>
}


问:
Ostream causing issue with file i/o
I omitted much of my code and much of my original input file just to make it easier and simpler to read, and to focus on one specific problem.

Each time I try and compile this code:

```<code>#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

void readExpression(ostream &fin, double operand1, char oepratr, double operand2);

int main()
{
    double operand1,
           operand2;

    char operatr;

    ifstream fin;
    fin.open("inp.txt");

    readExpression(fin, operand1, operatr, operand2);

    fin.close();

    return 0;
}

void readExpression(ostream &fin, double operand1, char operatr, double operand2)
{
    cin >> operand1 >> operatr >> operand2;
}
</code>```

This is the input file:

```<code>2.0 + 2.0
</code>```

I always get the error that I have

```<code>error: invalid initialization of reference of type 'std::ostream& {aka std::basic_ostream<char>&}' from expression of type 'std::ifstream {aka std::basic_ifstream<char>}'|
</code>```

I'm not sure what I'm doing wrong. I've been at this for hours and still haven't found a solution, after countless hours of researching. I am fairly new to cpp and only have experience in other language, which is why I am struggling with what seems like an elementary concept. Any help is greatly appreciated.

答:
You seem to have mixed information about streams. You correctly created an ifstream object in main() that will be binded to a file, but your function signature:

```<code>void readExpression(ostream &fin, double operand1, char oepratr, double operand2);
</code>```

uses std::ostream& - the output stream, not the input stream. std::ifstream inherits from std::istream, which is used for reading from, not writing to. What you want to do, is change it to:

```<code>void readExpression(istream &fin, double operand1, char oepratr, double operand2);
</code>```

Besides that, your function body is also incorrect. You do not use the argument fin, but you are always reading from std::cin. Thus you need to change the cin >> ... to fin >> .... Your complete function would look like:

```<code>void readExpression(istream &fin, double operand1, char operatr, double operand2)
{
    fin >> operand1 >> operatr >> operand2;
}
</code>```

You might be interested in reading this question and answers to it.

Title: Ostream causing issue with file i/o

Body:
I omitted much of my code and much of my original input file just to make it easier and simpler to read, and to focus on one specific problem.

Each time I try and compile this code:

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

void readExpression(ostream &fin, double operand1, char oepratr, double operand2);

int main()
{
    double operand1,
           operand2;

    char operatr;

    ifstream fin;
    fin.open("inp.txt");

    readExpression(fin, operand1, operatr, operand2);

    fin.close();

    return 0;
}

void readExpression(ostream &fin, double operand1, char operatr, double operand2)
{
    cin >> operand1 >> operatr >> operand2;
}

This is the input file:

2.0 + 2.0

I always get the error that I have

error: invalid initialization of reference of type 'std::ostream& {aka std::basic_ostream<char>&}' from expression of type 'std::ifstream {aka std::basic_ifstream<char>}'|

I'm not sure what I'm doing wrong. I've been at this for hours and still haven't found a solution, after countless hours of researching. I am fairly new to cpp and only have experience in other language, which is why I am struggling with what seems like an elementary concept. Any help is greatly appreciated.

Body:
You seem to have mixed information about streams. You correctly created an ifstream object in main() that will be binded to a file, but your function signature:

void readExpression(ostream &fin, double operand1, char oepratr, double operand2);

uses std::ostream& - the output stream, not the input stream. std::ifstream inherits from std::istream, which is used for reading from, not writing to. What you want to do, is change it to:

void readExpression(istream &fin, double operand1, char oepratr, double operand2);

Besides that, your function body is also incorrect. You do not use the argument fin, but you are always reading from std::cin. Thus you need to change the cin >> ... to fin >> .... Your complete function would look like:

void readExpression(istream &fin, double operand1, char operatr, double operand2)
{
    fin >> operand1 >> operatr >> operand2;
}

You might be interested in reading this question and answers to it.


问:
Are there any advantages to having a defer in a simple, no return, non-panicking function?
Going through the standard library, I see a lot functions similar to the following:

```<code>// src/database/sql/sql.go
func (dc *driverConn) removeOpenStmt(ds *driverStmt) {
    dc.Lock()
    defer dc.Unlock()
    delete(dc.openStmt, ds)
}
...

func (db *DB) addDep(x finalCloser, dep interface{}) {
    //println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep))
    db.mu.Lock()
    defer db.mu.Unlock()
    db.addDepLocked(x, dep)
}
// src/expvar/expvar.go
func (v *Map) addKey(key string) {
    v.keysMu.Lock()
    defer v.keysMu.Unlock()
    v.keys = append(v.keys, key)
    sort.Strings(v.keys)
}
// etc...
</code>```

I.e.: simple functions with no returns and presumably no way to panic that are still deferring the unlock of their mutex. As I understand it, the overhead of a defer has been improved (and perhaps is still in the process of being improved), but that being said: Is there any reason to include a defer in functions like these?  Couldn't these types of defers end up slowing down a high traffic function?

答:
Always deferring things like Mutex.Unlock() and WaitGroup.Done() at the top of the function makes debugging and maintenance easier, since you see immediately that those pieces are handled correctly so you know that those important pieces are taken care of, and can quickly move on to other issues.

It's not a big deal in 3 line functions, but consistent-looking code is also just easier to read in general. Then as the code grows, you don't have to worry about adding an expression that may panic, or complicated early return logic, because the pre-existing defers will always work correctly.

Body:
Going through the standard library, I see a lot functions similar to the following:

// src/database/sql/sql.go
func (dc *driverConn) removeOpenStmt(ds *driverStmt) {
    dc.Lock()
    defer dc.Unlock()
    delete(dc.openStmt, ds)
}
...

func (db *DB) addDep(x finalCloser, dep interface{}) {
    //println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep))
    db.mu.Lock()
    defer db.mu.Unlock()
    db.addDepLocked(x, dep)
}
// src/expvar/expvar.go
func (v *Map) addKey(key string) {
    v.keysMu.Lock()
    defer v.keysMu.Unlock()
    v.keys = append(v.keys, key)
    sort.Strings(v.keys)
}
// etc...

I.e.: simple functions with no returns and presumably no way to panic that are still deferring the unlock of their mutex. As I understand it, the overhead of a defer has been improved (and perhaps is still in the process of being improved), but that being said: Is there any reason to include a defer in functions like these?  Couldn't these types of defers end up slowing down a high traffic function?


问:
XAMPP can't run my Manage Server
I am totally new in the web development, I am using Mac OSX. and I am using XAMPP version 5.6.32. I just want to follow along the tutorial, but the I am stuck at the very first step.

I have tried to tap the 'Start All' button, but it is not running, MySQL Database, ProFTPD and Apache Web Server always stop.

when I open phpMyAdmin, it is said

what should I do ? I have no idea. Thanks in advance

答: Try updating XAMPP to the newest version (reinstall)... If it still doesn't work check what the Application log tab on the right says.</p>

Title: XAMPP can't run my Manage Server


问:
How do I specify the name of a joiner table in an EF many to many relationship?
I am using EF Code First 6.2 With Dev Express XAF
In DevExpress.Persistent.BaseImpl.EF  the Event class has a many to many relationship with the Resource class.

If I make a new project using the Dev Express Wizard with Code First then the joiner table will be called ResourceEvents

However somehow in some migration my joiner table got renamed to be EventResources.

How do I set it back to what it should be?
I tried adding  the following to the DBContext

```<code>        modelBuilder.Entity<Event>().HasMany(x => x.Resources).WithMany(x => x.Events)
            .Map(
                x =>
                {
                    x.MapLeftKey("Event_ID");
                    x.MapRightKey("Resource_Key");
                    x.ToTable("ResourceEvents");
                });
</code>```

this causes a migration to want to create

```<code>  public partial class ev : DbMigration
    {
  public override void Up()
    {
        DropPrimaryKey("dbo.ResourceEvents");
        AddPrimaryKey("dbo.ResourceEvents", new[] { "Event_ID", "Resource_Key" });
    }

    public override void Down()
    {
        DropPrimaryKey("dbo.ResourceEvents");
        AddPrimaryKey("dbo.ResourceEvents", new[] { "Resource_Key", "Event_ID" });
    }
</code>```

}

Running the migration causes an error

```<code>Cannot find the object "dbo.ResourceEvents" because it does not exist or you do not have permissions.
</code>```

答:
The trick was to add code to the migration to rename the table

```<code>RenameTable(name: "dbo.EventResources", newName: "ResourceEvents");
</code>```

Having the fluent API seems important in letting EF know what the name of the table should be.

Body:
I am using EF Code First 6.2 With Dev Express XAF
In DevExpress.Persistent.BaseImpl.EF  the Event class has a many to many relationship with the Resource class.

If I make a new project using the Dev Express Wizard with Code First then the joiner table will be called ResourceEvents

However somehow in some migration my joiner table got renamed to be EventResources.

How do I set it back to what it should be?
I tried adding  the following to the DBContext

        modelBuilder.Entity<Event>().HasMany(x => x.Resources).WithMany(x => x.Events)
            .Map(
                x =>
                {
                    x.MapLeftKey("Event_ID");
                    x.MapRightKey("Resource_Key");
                    x.ToTable("ResourceEvents");
                });

this causes a migration to want to create

  public partial class ev : DbMigration
    {
  public override void Up()
    {
        DropPrimaryKey("dbo.ResourceEvents");
        AddPrimaryKey("dbo.ResourceEvents", new[] { "Event_ID", "Resource_Key" });
    }

    public override void Down()
    {
        DropPrimaryKey("dbo.ResourceEvents");
        AddPrimaryKey("dbo.ResourceEvents", new[] { "Resource_Key", "Event_ID" });
    }

}

Running the migration causes an error

Cannot find the object "dbo.ResourceEvents" because it does not exist or you do not have permissions.

Body:
The trick was to add code to the migration to rename the table

RenameTable(name: "dbo.EventResources", newName: "ResourceEvents");

Having the fluent API seems important in letting EF know what the name of the table should be.


问:
How do I concatenate strings within an array of objects nested inside another array of objects?
Here's the JSON object I'm working with:

```<code>var object = {
    "units": [
        { "unitNum": "1", "fuels": [{ "fuelDesc": "Coal" }] },
        { "unitNum": "2", "fuels": [{ "fuelDesc": "Pipeline Natural Gas" }] }
    ]
}
</code>```

What's the most performative way of concatenating all of the fuelDesc strings into one string, separated by ,?

NOTE: I've simplified the object here. The actual objects is a lot larger so I'm concerned with performance. Also, the fuels array can have more than one item.

The result would be "Coal,Pipeline Natural Gas".

I did this:

```<code>var fuelsStr = "";
for (i = 0; i < units.length; i += 1) {
    var mergedFuels = [].concat.apply([], units[i].fuels)
    var unitFuelStr = mergedFuels.map(function (mergedFuels) {
        return mergedFuels["fuelDesc"];
    }).join(",");
    fuelsStr += unitFuelStr;
}
</code>```

答:
For JSON string, the JSON.parse reviver can be used:

a = [], j = '{"units":[{"unitNum":"1","fuels":[{"fuelDesc":"Coal"}]},{"unitNum":"2","fuels":[{"fuelDesc":"Pipeline Natural Gas"}]}]}'

JSON.parse(j, (k, v) => k === "fuelDesc" ? a.push(v) : 0)

console.log(a + '')```
</div>
</div>
</p>

<p>For JavaScript object, the <code>JSON.stringify</code> replacer :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>a = [], o = {"units":[{"unitNum":"1","fuels":[{"fuelDesc":"Coal"}]},{"unitNum":"2","fuels":[{"fuelDesc":"Pipeline Natural Gas"}]}]}

JSON.stringify(o, (k, v) => k === "fuelDesc" ? a.push(v) : v)

console.log(a + '')</code>```

Body:
Here's the JSON object I'm working with:

var object = {
    "units": [
        { "unitNum": "1", "fuels": [{ "fuelDesc": "Coal" }] },
        { "unitNum": "2", "fuels": [{ "fuelDesc": "Pipeline Natural Gas" }] }
    ]
}

What's the most performative way of concatenating all of the fuelDesc strings into one string, separated by ,?

NOTE: I've simplified the object here. The actual objects is a lot larger so I'm concerned with performance. Also, the fuels array can have more than one item.

The result would be "Coal,Pipeline Natural Gas".

I did this:

var fuelsStr = "";
for (i = 0; i < units.length; i += 1) {
    var mergedFuels = [].concat.apply([], units[i].fuels)
    var unitFuelStr = mergedFuels.map(function (mergedFuels) {
        return mergedFuels["fuelDesc"];
    }).join(",");
    fuelsStr += unitFuelStr;
}

Body:
For JSON string, the JSON.parse reviver can be used:

a = [], j = '{"units":[{"unitNum":"1","fuels":[{"fuelDesc":"Coal"}]},{"unitNum":"2","fuels":[{"fuelDesc":"Pipeline Natural Gas"}]}]}'

JSON.parse(j, (k, v) => k === "fuelDesc" ? a.push(v) : 0)

console.log(a + '')

For JavaScript object, the JSON.stringify replacer :

a = [], o = {"units":[{"unitNum":"1","fuels":[{"fuelDesc":"Coal"}]},{"unitNum":"2","fuels":[{"fuelDesc":"Pipeline Natural Gas"}]}]}

JSON.stringify(o, (k, v) => k === "fuelDesc" ? a.push(v) : v)

console.log(a + '')


问:
Proper Setup of Tab Indents
Using Emacs with C source code, I want pressing the tab key to insert a tab character, and have it show a tab as being 2 spaces wide. So this is what I put in my ~/.emacs:

(setq c-default-style "linux")

(setq-default c-basic-offset 2

tab-width 2)

However it does not count a tab as one column, but 2 in this case, and it causes a problem when I want to, for instance, jump to the spot that gcc specifies in an error message.

```<code>int main()
{
    if(1)
    {
        if(2)
        {
            error
        }
    }
}
</code>```

With this error:

```<code>test.c:7:5 error: `error` undeclared (first use in this function)
</code>```

So when I select the error it jumps to the wrong spot. Is there any way to fix this?

答: Have you tried setting c-syntactic-indentation to nil?

Title: Proper Setup of Tab Indents

Body:
Using Emacs with C source code, I want pressing the tab key to insert a tab character, and have it show a tab as being 2 spaces wide. So this is what I put in my ~/.emacs:

(setq c-default-style "linux")

(setq-default c-basic-offset 2

tab-width 2)

However it does not count a tab as one column, but 2 in this case, and it causes a problem when I want to, for instance, jump to the spot that gcc specifies in an error message.

int main()
{
    if(1)
    {
        if(2)
        {
            error
        }
    }
}

With this error:

test.c:7:5 error: `error` undeclared (first use in this function)

So when I select the error it jumps to the wrong spot. Is there any way to fix this?


问:
Fastest Way To Query SQL with Loop
I have an issue to looping SQL Query using VBA, its take a long time to run.
Total looping is 115 times in 15 minutes. Is there any way reduce the query time?
Here's is my code :</p>

```<code>    Dim Conn As New ADODB.Connection
    Dim mrs As New ADODB.Recordset
    x = 1
    DBPath = ThisWorkbook.FullName
    sconnect = "Provider=SQLOLEDB;SERVER=DWSQL\BCAPP;Database=TEST;Uid=admin;Pwd=admin;"
    Conn.Open sconnect
    Do
        If Sheets("Foil (+)").Cells(12, 12) <> "" And Sheets("Data").Cells(x, 3).Value Like "E*" Then
            sSqlSting = "SELECT *FROM [TEST].[dbo].[process_details] where pos_no = '" & Sheets("Data").Cells(x, 3) & "' and scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'"
        Else
            Sheets("Data").Cells(x, 3).Value = "E" & Sheets("Data").Cells(x, 3).Value
            sSqlSting = "SELECT *FROM [TEST].[dbo].[process_details] where pos_no = '" & Sheets("Data").Cells(x, 3) & "' and scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'"
        End If

        mrs.Open sSqlSting, Conn, adOpenForwardOnly
        If Sheets("Data").Cells(1, 18) = "" Then
            Sheets("Data").Cells(1, 18).CopyFromRecordset mrs
        Else
            Sheets("Data").Cells(Rows.Count, 18).End(xlUp).Offset(1, 0).CopyFromRecordset mrs
        End If
        mrs.Close
        x = x + 1
    Loop Until Sheets("Data").Cells(x, 3) = ""
    Conn.Close
</code>```

答:
Some thoughts...

Since your code works, and there isn't a lot you can do to speed up the actual processing of data within the worksheet (115 iterations is nothing), my guess is the bulk of the time is spent communicating with the database.

On that note, 15 minutes for 115 loops is extraordinary.

If you haven't already, make sure you have an index on:

```<code>scan_type, status, returned, pos_no
</code>```

I'd recommend this all as a single index.

This is a band-aid.  You are doing 115 scans of the same table, and this only makes each scan more efficient -- it's like making 115 trips to the grocery store for 115 items and driving car instead of walking.

Parameterize your query.  Instead of passing literals, set up a parameter and send that with each loop.

This is also a band-aid and has more to do with decorum than performance, although there will be a performance impact, as you are compiling a statement once and executing it 115 times rather than compiling and executing 115 times.

Better yet, do a single scan of the table.  Execute your query one time, store the results in a data structure (a Dictionary object might do nicely) and then loop and apply those results.

If the results of this:

```<code>scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'
</code>```

Are sufficiently small (< 5000 or so records), I'd just run that up front and store it in a Dictionary, then loop through your spreadsheet.

If it's really large, then scan the spreadsheet first, run the query against just those 115 items, and then loop through the spreadsheet a second time to assign the values.  Passing an in-list as a parameter probably isn't possible (it is in PostgreSQL by the way), so your dynamic SQL approach is probably sufficient.

If you reach a point where you have thousands of items in the list, the best approach would be to load these into a temp table and then do a join against the table.

Title: Fastest Way To Query SQL with Loop

Body:
I have an issue to looping SQL Query using VBA, its take a long time to run.
Total looping is 115 times in 15 minutes. Is there any way reduce the query time?
Here's is my code :

    Dim Conn As New ADODB.Connection
    Dim mrs As New ADODB.Recordset
    x = 1
    DBPath = ThisWorkbook.FullName
    sconnect = "Provider=SQLOLEDB;SERVER=DWSQL\BCAPP;Database=TEST;Uid=admin;Pwd=admin;"
    Conn.Open sconnect
    Do
        If Sheets("Foil (+)").Cells(12, 12) <> "" And Sheets("Data").Cells(x, 3).Value Like "E*" Then
            sSqlSting = "SELECT *FROM [TEST].[dbo].[process_details] where pos_no = '" & Sheets("Data").Cells(x, 3) & "' and scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'"
        Else
            Sheets("Data").Cells(x, 3).Value = "E" & Sheets("Data").Cells(x, 3).Value
            sSqlSting = "SELECT *FROM [TEST].[dbo].[process_details] where pos_no = '" & Sheets("Data").Cells(x, 3) & "' and scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'"
        End If

        mrs.Open sSqlSting, Conn, adOpenForwardOnly
        If Sheets("Data").Cells(1, 18) = "" Then
            Sheets("Data").Cells(1, 18).CopyFromRecordset mrs
        Else
            Sheets("Data").Cells(Rows.Count, 18).End(xlUp).Offset(1, 0).CopyFromRecordset mrs
        End If
        mrs.Close
        x = x + 1
    Loop Until Sheets("Data").Cells(x, 3) = ""
    Conn.Close

Body:
Some thoughts...

Since your code works, and there isn't a lot you can do to speed up the actual processing of data within the worksheet (115 iterations is nothing), my guess is the bulk of the time is spent communicating with the database.

On that note, 15 minutes for 115 loops is extraordinary.

If you haven't already, make sure you have an index on:

scan_type, status, returned, pos_no

I'd recommend this all as a single index.

This is a band-aid.  You are doing 115 scans of the same table, and this only makes each scan more efficient -- it's like making 115 trips to the grocery store for 115 items and driving car instead of walking.

Parameterize your query.  Instead of passing literals, set up a parameter and send that with each loop.

This is also a band-aid and has more to do with decorum than performance, although there will be a performance impact, as you are compiling a statement once and executing it 115 times rather than compiling and executing 115 times.

Better yet, do a single scan of the table.  Execute your query one time, store the results in a data structure (a Dictionary object might do nicely) and then loop and apply those results.

If the results of this:

scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'

Are sufficiently small (< 5000 or so records), I'd just run that up front and store it in a Dictionary, then loop through your spreadsheet.

If it's really large, then scan the spreadsheet first, run the query against just those 115 items, and then loop through the spreadsheet a second time to assign the values.  Passing an in-list as a parameter probably isn't possible (it is in PostgreSQL by the way), so your dynamic SQL approach is probably sufficient.

If you reach a point where you have thousands of items in the list, the best approach would be to load these into a temp table and then do a join against the table.


问:
how to get innerHtml of body without an iframe with jquery
I have page with html something like this

```<code><body><iframe ></iframe><div id="menu">......</div>.....</body>
</code>```

I want to get the innerHTML of the body but without the iframe? How can i do that in jquery?

答:
I have found another way to do it

```<code>var page = $('body').html();
page = $('<div>' + page + '</div>');
var html = $(page).find('iframe').remove().end().html();
</code>```

html variable contains the html without the iframe.

And it works with IE, since jquery.clone() did not work on my page may be because of malformed html as @lonesomeday suggestted

Body:
I have page with html something like this

......
.....

I want to get the innerHTML of the body but without the iframe? How can i do that in jquery?

Body:
I have found another way to do it

var page = $('body').html();
page = $('<div>' + page + '</div>');
var html = $(page).find('iframe').remove().end().html();

html variable contains the html without the iframe.

And it works with IE, since jquery.clone() did not work on my page may be because of malformed html as @lonesomeday suggestted


问:
How do I fix a mistake in a git branch merge before I push it?
I have gone through the process of merging my branch into the master. It had conflicts that I fixed, and I completed the merge with --continue.

Before pushing the merge, I realised that I made a mistake in the conflict resolution. I haven't pushed the commit yet, so I should be able to fix it, but I don't want to go through the entire merge process again because it was a lot of work.

I have been thinking about a couple of options:

Amend the commit, however I have heard that this is dangerous due to the evil merge.

Reset --soft the merge and modify it and then re-commit. However, this will then be a new set of changes and not a branch commit (so it won't have both parents).

How can I fix my merge commit without going through the entire conflict resolution process again?

答:
Since the merged commit has not pushed to remote repo, both amend the commit and reset (with hard option) options are ok.

Option 1: Amend the merged cimmit

Commands used as below:

```<code>#Change the conflict file again
git add .
git commit --amend -m 'message'
git push
</code>```

Option 2: Reset the merged commit with --hard option

If you want to keep the merge history, I suggest to use git reset --hard option and then merge again.

First, let's illustrate by graphs why git reset --soft or git reset --mixed options are not recommend.

Assume the commit history for now as below (merged dev branch into master branch with commit M):

```<code>...---A---B---C---M  master
       \         /
        D---E---F    dev
</code>```

If you use git reset --soft HEAD~ or git reset [--mixed] HEAD~, the HEAD will point to commit C, and the working directory has staged changes (for --soft option) or modifies changes (for --mixed option).

After you change the file and commit again, the commit history will be:

```<code>...---A---B---C---M'  master
       \
        D---E---F     dev
</code>```

There will show the commit M', and from the commit history, commit M' is not a default merged commit (you can not find dev branch merged into master branch with default manners).

While for git reset --hard HEAD~ it will change the HEAD to commit C and keep the working tree clean. The commit history will be:

```<code>...---A---B---C     master
       \
        D---E---F   dev
</code>```

Then you can merge dev branch into master branch again (git merge dev). After that, the commit history will be:

```<code>...---A---B---C---M''   master
       \         /
        D---E---F       dev
</code>```

And if you want to merge dev branch based on the first time merged result, you can use below commands:

```<code>git merge dev
#There has conflicts
git checkout <commit id for M> -- .
#Now the conflicts resolution is get as the first time merged
#Changes files based on the conflicts resolution
git add .
git commit
git push
</code>```

Body:
Since the merged commit has not pushed to remote repo, both amend the commit and reset (with hard option) options are ok.

Option 1: Amend the merged cimmit

Commands used as below:

#Change the conflict file again
git add .
git commit --amend -m 'message'
git push

Option 2: Reset the merged commit with --hard option

If you want to keep the merge history, I suggest to use git reset --hard option and then merge again.

First, let's illustrate by graphs why git reset --soft or git reset --mixed options are not recommend.

Assume the commit history for now as below (merged dev branch into master branch with commit M):

...---A---B---C---M  master
       \         /
        D---E---F    dev

If you use git reset --soft HEAD~ or git reset [--mixed] HEAD~, the HEAD will point to commit C, and the working directory has staged changes (for --soft option) or modifies changes (for --mixed option).

After you change the file and commit again, the commit history will be:

...---A---B---C---M'  master
       \
        D---E---F     dev

There will show the commit M', and from the commit history, commit M' is not a default merged commit (you can not find dev branch merged into master branch with default manners).

While for git reset --hard HEAD~ it will change the HEAD to commit C and keep the working tree clean. The commit history will be:

...---A---B---C     master
       \
        D---E---F   dev

Then you can merge dev branch into master branch again (git merge dev). After that, the commit history will be:

...---A---B---C---M''   master
       \         /
        D---E---F       dev

And if you want to merge dev branch based on the first time merged result, you can use below commands:

git merge dev
#There has conflicts
git checkout <commit id for M> -- .
#Now the conflicts resolution is get as the first time merged
#Changes files based on the conflicts resolution
git add .
git commit
git push


问:
How to adjust slideshow and enable people to click?
I am really bad with Javascript and is still learning. Recently, I have the idea of using an image slider for the website I am designing and I tried the Image Slider code from W3school. I tested the code, and tried the demo on the website.

In the website, I was able to click on the grey dots to move between pictures, however, when I pasted the code on my page, I was unable to move the images through clicking(the grey button cannot be clicked), and the only way the image is able to change is through its own animation time. I do not know what is wrong with it and I hope someone will be able to help me and tell me what's wrong.

Below is my Javascript code:

```<code>var slideIndex = 0;
showSlides();

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("dot");
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex > slides.length) {
        slideIndex = 1
    }
    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
    }
    slides[slideIndex - 1].style.display = "block";
    dots[slideIndex - 1].className += " active";
    setTimeout(showSlides, 5000); // Change image every 2 seconds
}
</code>```

My HTML Slider code:

```<code> <div class="jumbotron" style="background:transparent !important;">
    <div class="slideshow-container">

        <div class="mySlides fade">
            <div class="numbertext">1 / 3</div>
            <img src="Images/Bulldog.jpg" style="width:100%;height: 300px">
            <div class="text"><h2>Bulldog</h2></div>
        </div>

        <div class="mySlides fade">
            <div class="numbertext">2 / 3</div>
            <img src="Images/Corgeek.jpg" style="width:100%;height: 300px">
            <div class="text"><h2>Corgi</h2></div>
        </div>

        <div class="mySlides fade">
            <div class="numbertext">3 / 3</div>
            <img src="Images/HairyDog.jpg" style="width:100%;height: 300px;">
            <div class="text"><h2>Furry Dog</h2></div>
        </div>
    </div>
</div>
</code>```

Also, is there any better way to create a slideshow? If there is, it would be appreciated if there are links or solutions for me to see. Thank you.

答:
I could be wrong, but you are using a jumbotron class, which indicates you are already loading Bootstrap.  If this is the case, you already have a slideshow available to you.

You can read about the slideshow(carousel) here: https://getbootstrap.com/docs/4.0/components/carousel/

It will likely be easier to use, and less error prone than what you are currently working with.

Body:
I am really bad with Javascript and is still learning. Recently, I have the idea of using an image slider for the website I am designing and I tried the Image Slider code from W3school. I tested the code, and tried the demo on the website.

In the website, I was able to click on the grey dots to move between pictures, however, when I pasted the code on my page, I was unable to move the images through clicking(the grey button cannot be clicked), and the only way the image is able to change is through its own animation time. I do not know what is wrong with it and I hope someone will be able to help me and tell me what's wrong.

Below is my Javascript code:

var slideIndex = 0;
showSlides();

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("dot");
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex > slides.length) {
        slideIndex = 1
    }
    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
    }
    slides[slideIndex - 1].style.display = "block";
    dots[slideIndex - 1].className += " active";
    setTimeout(showSlides, 5000); // Change image every 2 seconds
}

My HTML Slider code:

1 / 3

Bulldog

2 / 3

Corgi

3 / 3

Furry Dog

Also, is there any better way to create a slideshow? If there is, it would be appreciated if there are links or solutions for me to see. Thank you.


答:
This is straightforward fix. First, fix SQL syntax error (SQL LEFT function takes 2 parameter, a string and a number. LEFT('abcdef', 3) returns abc), next rewrite using parameters. Something like this.

```<code>string result3 = Checked_By.ToString().Substring(0, 3);

SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama] FROM [Job] WHERE LEFT(Kode, 3) = @result3 ORDER BY Nama", con); //ASC is OK but not required as it is default option
cmd.Parameters.Add("@result3", SqlDbType.Char, 3).Value = result3;

 SqlDataAdapter sda = new SqlDataAdapter(cmd);
 DataTable dt = new DataTable();
 //con.Open(); //not necessary. SqlDataAdapter.Fill opens connection if it needs
 sda.Fill(dt);
 //con.Close(); //and closed if it wasn't open before .Fill
</code>```

Title: how to query select data from table where first 3 character defined

Body:
i want to filter dropdownlist by first 3 charater on job code, this is my query

string result3 = Checked_By.ToString().Substring(0, 3);

SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama]
FROM [Job] WHERE LEFT(Kode, = '" + result3 + "') ORDER BY
Nama ASC", con);

 SqlDataAdapter sda = new SqlDataAdapter(cmd);
 DataTable dt = new DataTable();
 con.Open();
 sda.Fill(dt);
 con.Close();

Body:
This is straightforward fix. First, fix SQL syntax error (SQL LEFT function takes 2 parameter, a string and a number. LEFT('abcdef', 3) returns abc), next rewrite using parameters. Something like this.

string result3 = Checked_By.ToString().Substring(0, 3);

SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama] FROM [Job] WHERE LEFT(Kode, 3) = @result3 ORDER BY Nama", con); //ASC is OK but not required as it is default option
cmd.Parameters.Add("@result3", SqlDbType.Char, 3).Value = result3;

 SqlDataAdapter sda = new SqlDataAdapter(cmd);
 DataTable dt = new DataTable();
 //con.Open(); //not necessary. SqlDataAdapter.Fill opens connection if it needs
 sda.Fill(dt);
 //con.Close(); //and closed if it wasn't open before .Fill


问:
Is this empty loop executing infinitely?
I have this code right here:

```<code>#include <iostream>
using namespace std;

int main() {
  int counter = 0;
  int sum = 0;
  while(counter < 10);
  {
    sum += ++ counter;
  }
  cout << sum << endl;
}
</code>```

I was wondering if the line while(counter < 10); is an infinite loop which results in the rest of the code not being executed.

Another side question, since the while is delimited with ;, that block of code under it is just an inner scope of code?

答:
Yes, as the initial value of counter is 0 then the statement

```<code>while (counter < 10);
</code>```

which is implicitly

```<code>while (counter < 10) {}
</code>```

is an infinite loop.  And yes, due to the terminating semi-colon on the while statement, the subsequent braced block is just another scope.

Body:
I have this code right here:

#include <iostream>
using namespace std;

int main() {
  int counter = 0;
  int sum = 0;
  while(counter < 10);
  {
    sum += ++ counter;
  }
  cout << sum << endl;
}

I was wondering if the line while(counter < 10); is an infinite loop which results in the rest of the code not being executed.

Another side question, since the while is delimited with ;, that block of code under it is just an inner scope of code?

Body:
Yes, as the initial value of counter is 0 then the statement

while (counter < 10);

which is implicitly

while (counter < 10) {}

is an infinite loop.  And yes, due to the terminating semi-colon on the while statement, the subsequent braced block is just another scope.


问:
Convert dataframe column into integers from within loop
I'm trying loop through a folder of csv's and put them into a dataframe, change certain columns into an integer, before passing them through a Django model. Here is my code:

```<code>import glob
import pandas as pd
path = 'DIV1FCS_2017/*/*'

for fname in glob.glob(path):
    df = pd.read_csv(fname)
    df['Number'].apply(pd.to_numeric)
</code>```

I am receiving the following: ValueError: Unable to parse string

Does anybody know if I can convert a column of strings into integers using pd.to_numeric from within a loop? Outside of the loop it seems to work properly.

答:
I think you probably have some non-numbers data stored in your dataframe, and that's what's casuing the error.
You can examine your data and make sure everything's fine. In the meantime, you can also do pd.to_numeric(errors="ignore") to ignore errors for now.</p>

Body:
I'm trying loop through a folder of csv's and put them into a dataframe, change certain columns into an integer, before passing them through a Django model. Here is my code:

import glob
import pandas as pd
path = 'DIV1FCS_2017/*/*'

for fname in glob.glob(path):
    df = pd.read_csv(fname)
    df['Number'].apply(pd.to_numeric)

I am receiving the following: ValueError: Unable to parse string

Does anybody know if I can convert a column of strings into integers using pd.to_numeric from within a loop? Outside of the loop it seems to work properly.