问:
Can't restore a dump backup file for Postgres using pg_restore
I generated a dump backup file for my Postgres 9.3.4 using this:

```<code>pg_dump table_name -U myusername -h localhost -O > backup.dump
</code>```

Now I'm trying to backup the old database using:

```<code>pg_restore -U myusername -n public -d table_name  backup.dump
</code>```

But I keep getting this error:

```<code>pg_restore: [archiver] input file appears to be a text format dump. Please use psql.
</code>```

Please note that the file is not plain sql file since I generated it using pg_dump.

I used the follwoing command:

```<code>psql perchwell -U myusername -f backup.dump -v ON_ERROR_STOP=1
</code>```

and start receiving the following error:

```<code>SET
SET
SET
SET
SET
SET
psql:backup.dump:16: ERROR:  schema "propertydir" already exists
</code>```

答:
Your bug: pg_restore: [archiver] input file appears to be a text format dump. Please use psql

Bug indicate use psql command to import database.

```<code>cat your-dump-pg-file.dump | psql -d your-database
</code>```

This way, you can easily restore file

In additionally if you set character set UTF-8, will make better import too.

Body:
I generated a dump backup file for my Postgres 9.3.4 using this:

pg_dump table_name -U myusername -h localhost -O > backup.dump

Now I'm trying to backup the old database using:

pg_restore -U myusername -n public -d table_name  backup.dump

But I keep getting this error:

pg_restore: [archiver] input file appears to be a text format dump. Please use psql.

Please note that the file is not plain sql file since I generated it using pg_dump.

I used the follwoing command:

psql perchwell -U myusername -f backup.dump -v ON_ERROR_STOP=1

and start receiving the following error:

SET
SET
SET
SET
SET
SET
psql:backup.dump:16: ERROR:  schema "propertydir" already exists

Body:
Your bug: pg_restore: [archiver] input file appears to be a text format dump. Please use psql

Bug indicate use psql command to import database.

cat your-dump-pg-file.dump | psql -d your-database

This way, you can easily restore file

In additionally if you set character set UTF-8, will make better import too.


来源: stackexchange

问:
Create Drawable with specific height
I want to create a drawable object with a width equal to the screen's width and display 3 images inside the drawable. I know the last part can be done using a LayerDrawable object, but I don't know how to set the drawable sizes. What would be the best way to do this?

Thank you and best regards

答:
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html

i hope this help..

ContentLicense: CC BY-SA 2.5

Title: Create Drawable with specific height


问:
Disable all local Windows accounts
I need to make a batch script that disable all local user accounts of a computer or a way to list all the users, one below another.

I try to generate a file with the command:

```<code>net user > %systemroot%\users.txt | findstr /I adm
</code>```

but the command returns me all users in the same line.

If someone knows how to generate every user in a separate line, it helps me too.

答:
here is the code that solved to me:</p>

```<code>for /f "delims=" %%a in ('net user ^| findstr -V "Contas de usu" ^| findstr -V "Comando conc" ^| findstr -V "\-" ^| findstr -V "User accounts" ^| findstr -V "The command"') do (
   for %%b in (%%a) do (
      if not "%%b" == "Administrador" (
         if not "%%b" == "Administrator" (
            if not "%%b" == "Convidado" (
               Net user %%b /active:no
            ) else (
               for /f "delims=" %%c in ('ver ^| findstr /i "5\.1\."') do (
                  set version=%%c
               )
               if not {"!version!"} == {""} (
                  Net user "Convidado" /active:yes
               ) else (
                  Net user "Convidado" /active:no
               )

            )
         ) else (
            Net user "Administrator" /active:yes
         )
      ) else (
         Net user "Administrador" /active:yes
      )
   )
)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Disable all local Windows accounts

Body:
I need to make a batch script that disable all local user accounts of a computer or a way to list all the users, one below another.

I try to generate a file with the command:

net user > %systemroot%\users.txt | findstr /I adm

but the command returns me all users in the same line.

If someone knows how to generate every user in a separate line, it helps me too.

Body:
here is the code that solved to me:

for /f "delims=" %%a in ('net user ^| findstr -V "Contas de usu" ^| findstr -V "Comando conc" ^| findstr -V "\-" ^| findstr -V "User accounts" ^| findstr -V "The command"') do (
   for %%b in (%%a) do (
      if not "%%b" == "Administrador" (
         if not "%%b" == "Administrator" (
            if not "%%b" == "Convidado" (
               Net user %%b /active:no
            ) else (
               for /f "delims=" %%c in ('ver ^| findstr /i "5\.1\."') do (
                  set version=%%c
               )
               if not {"!version!"} == {""} (
                  Net user "Convidado" /active:yes
               ) else (
                  Net user "Convidado" /active:no
               )

            )
         ) else (
            Net user "Administrator" /active:yes
         )
      ) else (
         Net user "Administrador" /active:yes
      )
   )
)


答:
You could use a hash table for the reference to the same parents.

var parent = [{ SNO: "869", Name: "ABC" }, { SNO: "800", Name: "CCC" }],
    cost = [{ NO: "869", Amnt: 100 }, { NO: "800", Amnt: 200 }, { NO: "800", Amnt: 560 }],
    hash = Object.create(null),
    result = { Parent: parent.map(function (a) { return hash[a.SNO] = a; }) };

cost.forEach(function (a) {
    (hash[a.NO].Cost = hash[a.NO].Cost || []).push(a);
});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: JSON object format/merge

Body:
I have these two variables below:

var parent: [{
  "SNO": "869",
  "Name": "ABC"
}, {
  "SNO": "800",
  "Name": "CCC"
}]
var Cost = [{
  "NO": "869",
  "Amnt": 100
}, {
  "NO": "800",
  "Amnt": 200
}, {
  "NO": "800",
  "Amnt": 560
}]

and the end updated result I want something like.
{
  "parent": [{
      "SNO": "869",
      "Name": "ABC",
      "Cost": [{
          "NO": "869",
          "Amnt": 100
        },
        {
          "NO": "869",
          "Amnt": 200
        },
        {
          "NO": "869",
          "Amnt": 560
        }
      ]
    },
    {
      "SNO": "800",
      "Name": "XYZ",
      "Cost": [{
          "NO": "800",
          "Amnt": 100
        },
        {
          "NO": "800",
          "Amnt": 200
        },
        {
          "NO": "800",
          "Amnt": 560
        }
      ]
    }
  ]
}

Can someone suggest me how to make it possible.

Body:
You could use a hash table for the reference to the same parents.

var parent = [{ SNO: "869", Name: "ABC" }, { SNO: "800", Name: "CCC" }],
    cost = [{ NO: "869", Amnt: 100 }, { NO: "800", Amnt: 200 }, { NO: "800", Amnt: 560 }],
    hash = Object.create(null),
    result = { Parent: parent.map(function (a) { return hash[a.SNO] = a; }) };

cost.forEach(function (a) {
    (hash[a.NO].Cost = hash[a.NO].Cost || []).push(a);
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
adding an onchange event to select
I have the following js code:

```<code>function createConBox() {
   var charDiv = document.getElementById("characterList");  // reference to "characterList" div
   header = document.createElement("p");  // creates the <p> tag
   charDiv.appendChild(header);  // adds the <p> tag to the parent node
   title = document.createTextNode("Show Only Lines By:");  // creates the text string
   header.appendChild(title); // adds the text string to the parent node

   // create select box and add elements
   selectBox = document.createElement("select");
   selectBox.setAttribute("id", "cList");
   charDiv.appendChild(selectBox);

   charNames = uniqueElemText("h3");   // array of character names
   newOption = document.createElement("option");
   selectBox.appendChild(newOption);
   newOptionTitle = document.createTextNode("Show All Lines");
   newOption.appendChild(newOptionTitle);
   for (i = 0; i < charNames.length; i++) {
      newOption = document.createElement("option");
      selectBox.appendChild(newOption);
      newOptionTitle = document.createTextNode(charNames[i]);
      newOption.appendChild(newOptionTitle);
   }

}

function showLines() {
   alert("The Box has been changed");
}
</code>```

Every time the option in the box is changed, I want it to call 'showLines()'. However, every time I try to implement an event, I can only get it to trigger when the page loads, and never again thereafter.

答:
When I pass dynamically id in case then what I do:</p>

```<code>var selectcell = tablerow.insertCell(1);
var selectelmt = document.createElement('select');
selectelmt.name = 'Select';
selectelmt.value = 'select';
selectelmt.classList = 'form-control input-sm cobclass';
selectelmt.onchange= onselectchange(i);
selectelmt.id = 'cobselect' + i;
selectelmt.options[0] = new Option('select');
selectcell.appendChild(selectelmt);
// ddrbind(i);
show();
i++;`
</code>```

ContentLicense: CC BY-SA 4.0

Title: adding an onchange event to select

Body:
I have the following js code:

function createConBox() {
   var charDiv = document.getElementById("characterList");  // reference to "characterList" div
   header = document.createElement("p");  // creates the
 tag
   charDiv.appendChild(header);  // adds the
 tag to the parent node
   title = document.createTextNode("Show Only Lines By:");  // creates the text string
   header.appendChild(title); // adds the text string to the parent node

   // create select box and add elements
   selectBox = document.createElement("select");
   selectBox.setAttribute("id", "cList");
   charDiv.appendChild(selectBox);

   charNames = uniqueElemText("h3");   // array of character names
   newOption = document.createElement("option");
   selectBox.appendChild(newOption);
   newOptionTitle = document.createTextNode("Show All Lines");
   newOption.appendChild(newOptionTitle);
   for (i = 0; i < charNames.length; i++) {
      newOption = document.createElement("option");
      selectBox.appendChild(newOption);
      newOptionTitle = document.createTextNode(charNames[i]);
      newOption.appendChild(newOptionTitle);
   }

}

function showLines() {
   alert("The Box has been changed");
}

Every time the option in the box is changed, I want it to call 'showLines()'. However, every time I try to implement an event, I can only get it to trigger when the page loads, and never again thereafter.

Body:
When I pass dynamically id in case then what I do:

var selectcell = tablerow.insertCell(1);
var selectelmt = document.createElement('select');
selectelmt.name = 'Select';
selectelmt.value = 'select';
selectelmt.classList = 'form-control input-sm cobclass';
selectelmt.onchange= onselectchange(i);
selectelmt.id = 'cobselect' + i;
selectelmt.options[0] = new Option('select');
selectcell.appendChild(selectelmt);
// ddrbind(i);
show();
i++;`


问:
What is Android's google app theme?
I am building an Android app and need to make it look like Android's stock google app (the one with the "G" icon) or google maps app. What theme are these google apps using?

The TripAdvisor app, for instance, has a very similar look and feel as the default google app. Is it possible to achieve the same look and feel like the stock google apps?

Would someone please let me know? Thanks!

答:
You're referring to "Material Design".

Its a design language which google rolled out on Android in 2015.

It aims to streamline the UI and provide a consistent experience across all user experiences on a device, so apps fee native.

More details at:

https://material.io/guidelines

https://design.google.com/resources/

Title: What is Android's google app theme?


问:
C# how to Regex.Replace "\r\n" (the actual characters, not the line break)
I've got some horrible text that I'm cleaning up using several c# regular expressions. One issue that has me stumped is there are a number of '\r\n' strings in the text, the actual characters not the line breaks.

I've tried:

```<code>content = Regex.Replace(content, "\\r\\n", "");
</code>```

and:

```<code>content = Regex.Replace(content, "\r\n", "");
</code>```

but neither of them work. In the end I had to use:

```<code>content = content.Replace("\\r\\n", "\r\n");
</code>```

to get the project finished, but not being able to do it in a regex annoys me.

答:
It is a good idea to get into the habit of using a verbatim string literals (@"example") when writing regular expressions in C#. In this case you needed this:

```<code>content = Regex.Replace(content, @"\\r\\n", "\r\n");
</code>```

Otherwise you have to escape each backslash twice: once to escape it in the C# string, and then a second time to escape them for the regular expression. So a single backslash would become four backslashes with a standard string literal.

Body:
I've got some horrible text that I'm cleaning up using several c# regular expressions. One issue that has me stumped is there are a number of '\r\n' strings in the text, the actual characters not the line breaks.

I've tried:

content = Regex.Replace(content, "\\r\\n", "");

and:

content = Regex.Replace(content, "\r\n", "");

but neither of them work. In the end I had to use:

content = content.Replace("\\r\\n", "\r\n");

to get the project finished, but not being able to do it in a regex annoys me.

Body:
It is a good idea to get into the habit of using a verbatim string literals (@"example") when writing regular expressions in C#. In this case you needed this:

content = Regex.Replace(content, @"\\r\\n", "\r\n");

Otherwise you have to escape each backslash twice: once to escape it in the C# string, and then a second time to escape them for the regular expression. So a single backslash would become four backslashes with a standard string literal.


问:
swift UIImage blue square
I have a project where any image I try to call using .setImage shows a blue square instead of the image.

```<code>sender.setImage(UIImage(named: "o.png"), for: [])
print(sender.tag)
</code>```

any help is greatly appreciated

Edit: I forgot to mention this is setting an image for a button inside of an IBAction

答:
You should set UIControlState instead of [].

So for example, if you want to change the image for normal state of UIButton,

then should use .normal instead of [].

ex: sender.setImage(UIImage(named: "o.png"), for: .normal)

You can just use .selected, .highlighted, something like that.

Just refer to this url please.
https://developer.apple.com/reference/uikit/uicontrolstate

Title: swift UIImage blue square

Body:
I have a project where any image I try to call using .setImage shows a blue square instead of the image.

sender.setImage(UIImage(named: "o.png"), for: [])
print(sender.tag)

any help is greatly appreciated

Edit: I forgot to mention this is setting an image for a button inside of an IBAction


问:
Disable multiple numbers after zero in input type="number"
This is my HTML:

```<code><input type="number" min="0" oninput="validity.valid||(value='');" step="0.1"/>
</code>```

However, I can still type something like:

0000 or 000111 or 00223, etc.

in my input field. How can I limit it only to one 0?

Is there a way to do this in HTML only?

Thanks.

答:
Check if your input starts with zero and override next digits with only 0.

function checkZero(){
  var val = document.getElementById("num").value;
  if(val.startsWith("0")){
     document.getElementById("num").value = "0";
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="num" type="number" min="0" oninput="checkZero()" step="0.1"/></code>```

Body:
This is my HTML:

<input type="number" min="0" oninput="validity.valid||(value='');" step="0.1"/>

However, I can still type something like:

0000 or 000111 or 00223, etc.

in my input field. How can I limit it only to one 0?

Is there a way to do this in HTML only?

Thanks.

Body:
Check if your input starts with zero and override next digits with only 0.

function checkZero(){
  var val = document.getElementById("num").value;
  if(val.startsWith("0")){
     document.getElementById("num").value = "0";
  }

}

<input id="num" type="number" min="0" oninput="checkZero()" step="0.1"/>


问:
Create a stacked bar using a frequency table
Actually I'm working with two frequency tables who have got the name: identified_modification_table and unidentified_modifications_table

The structure of these files are something like that:

identified_modification_table

```<code>Modifications   | Frequency
MOD:42123       | 12
MOD:1234        | 7
MOD:7618        | 36
MOD:411232      | 51
</code>```

unidentified_modifications_table

```<code>Modifications   | Frequency
MOD:42123       | 12
MOD:12          | 20
MOD:7618        | 36
MOD:411232      | 51
</code>```

I would like to merge these files and create this output in order to create a stacked barplot like this example.

```<code>Modifications   | Frequency.1 | Frequency.2
MOD:42123       | 12          | 12
MOD:1234        | 7           | NA
MOD:12          | NA          | 20
MOD:7618        | 36          | 36
MOD:411232      | 51          | 51
</code>```

I was trying to use this code to merge tables and add NA where the value doesn't exist.

```<code>df_final <- cbind.data.frame(df1, df2[match(df1$modifications, df2$modifications), ]);
</code>```

But this doesn't work properly and I don't know why.

After this I think I should just use melt and ggplot2 stacked bar:

```<code>df_barplot <- melt(df,measure.vars = names(df))

ggplot((df_barplot), aes(x = value, fill = variable)) +
    geom_bar(stat = "count", position = "dodge") +
    theme(axis.text.x = element_text(angle = 20, hjust = 0.5, vjust = -0.1)) +
    guides(fill=FALSE)+
    labs("Barplot") +
    xlab("Values")+
    ylab("Frequency")+
    theme(text = element_text(size=18), axis.text.x = element_text(angle = 90, hjust = 1, size = 15), axis.text.y=element_text(size = 15))
</code>```

Does anyone know how I could do this?

Here you are and a reproducible example:

```<code>df1 <- data.frame(modifications=c("MOD:214", "MOD:3","MOD:24","MOD:44","MOD:123", "MOD:123", "MOD:212"), Frequency=c(1,41,616,727,828,8993,383))

  df2 <- data.frame(modifications=c("MOD:214", "MOD:3","MOD:24","MOD:445","MOD:12", "MOD:123", "MOD:212"), Frequency=c(1,43,64,77,88,893,38))
</code>```

Thank you

答:
I think this does what you want

```<code>df3<-merge(df1,df2, by = "modifications",all = T)

library(reshape2)
df3<- melt(df3)
df3$variable<-factor(df3$variable,labels = c("modifications1","modifications2"))

library(ggplot2)
ggplot(df3, aes(x = modifications, y = value, fill = variable)) +
  geom_bar(stat = "identity",position = "dodge")
</code>```

edit: added all = T to keep all frequencies that occur in either table

Body:
Actually I'm working with two frequency tables who have got the name: identified_modification_table and unidentified_modifications_table

The structure of these files are something like that:

identified_modification_table

Modifications   | Frequency
MOD:42123       | 12
MOD:1234        | 7
MOD:7618        | 36
MOD:411232      | 51

unidentified_modifications_table

Modifications   | Frequency
MOD:42123       | 12
MOD:12          | 20
MOD:7618        | 36
MOD:411232      | 51

I would like to merge these files and create this output in order to create a stacked barplot like this example.

Modifications   | Frequency.1 | Frequency.2
MOD:42123       | 12          | 12
MOD:1234        | 7           | NA
MOD:12          | NA          | 20
MOD:7618        | 36          | 36
MOD:411232      | 51          | 51

I was trying to use this code to merge tables and add NA where the value doesn't exist.

df_final <- cbind.data.frame(df1, df2[match(df1$modifications, df2$modifications), ]);

But this doesn't work properly and I don't know why.

After this I think I should just use melt and ggplot2 stacked bar:

df_barplot <- melt(df,measure.vars = names(df))

ggplot((df_barplot), aes(x = value, fill = variable)) +
    geom_bar(stat = "count", position = "dodge") +
    theme(axis.text.x = element_text(angle = 20, hjust = 0.5, vjust = -0.1)) +
    guides(fill=FALSE)+
    labs("Barplot") +
    xlab("Values")+
    ylab("Frequency")+
    theme(text = element_text(size=18), axis.text.x = element_text(angle = 90, hjust = 1, size = 15), axis.text.y=element_text(size = 15))

Does anyone know how I could do this?

Here you are and a reproducible example:

df1 <- data.frame(modifications=c("MOD:214", "MOD:3","MOD:24","MOD:44","MOD:123", "MOD:123", "MOD:212"), Frequency=c(1,41,616,727,828,8993,383))

  df2 <- data.frame(modifications=c("MOD:214", "MOD:3","MOD:24","MOD:445","MOD:12", "MOD:123", "MOD:212"), Frequency=c(1,43,64,77,88,893,38))

Thank you

Body:
I think this does what you want

df3<-merge(df1,df2, by = "modifications",all = T)

library(reshape2)
df3<- melt(df3)
df3$variable<-factor(df3$variable,labels = c("modifications1","modifications2"))

library(ggplot2)
ggplot(df3, aes(x = modifications, y = value, fill = variable)) +
  geom_bar(stat = "identity",position = "dodge")

edit: added all = T to keep all frequencies that occur in either table


答:
\r, and \n have special meaning in Regex, too, so the backslash needs to be escaped. Then, these backslashes needs to be escaped for the c# string, leading to

```<code>content = Regex.Replace(content, "\\\\r\\\\n", "");
</code>```

or

```<code>content = Regex.Replace(content, @"\\r\\n", "");
</code>```

Title: C# how to Regex.Replace "\r\n" (the actual characters, not the line break)

Body:
\r, and \n have special meaning in Regex, too, so the backslash needs to be escaped. Then, these backslashes needs to be escaped for the c# string, leading to

content = Regex.Replace(content, "\\\\r\\\\n", "");

or

content = Regex.Replace(content, @"\\r\\n", "");


问:
How to make absolutely positioned element take full screen width when it is inside fixed width container?
Html:

```<code><div id='id1'>
  <div id='id2'>

  </div>
</div>
</code>```

Css:

```<code>#id1 {
  width: 300px;
  height: 200px;
  margin: 0 auto;
  background: red;
  position: relative;
}
#id2 {
  position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto;
  width: 100%; top: 20px; background: green; height: 30px;
}
</code>```

I want #id2 to take full screen width. I can specify left: -Npx and right: -Npx, but this will work only for some screen sizes.

id2 must not go beyond screen, so I can not specify left: -9999px;

Related fiddle: https://jsfiddle.net/aLubmd4a/

答:
It is a partial solution, I've changed the position of the #id2 element from position:absolute; to position:fixed;

Updated your fiddle example: https://jsfiddle.net/aLubmd4a/2/

If I understand you correctly, what you want to achieve is not really possible. An element's size AND positioning have to be in relation to some context.

In your example, you want it to take the width of the body, but be positioned (vertically) in relation to your #id1 element, right? If so, you should pick a side, and either take the inner div (#id2) out of #id1, or make sure that you update the top/left of the inner #id2 accordingly.

Body:
Html:

Css:

#id1 {
  width: 300px;
  height: 200px;
  margin: 0 auto;
  background: red;
  position: relative;
}
#id2 {
  position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto;
  width: 100%; top: 20px; background: green; height: 30px;
}

I want #id2 to take full screen width. I can specify left: -Npx and right: -Npx, but this will work only for some screen sizes.

id2 must not go beyond screen, so I can not specify left: -9999px;

Related fiddle: https://jsfiddle.net/aLubmd4a/


问:
Integrating Facebook and Twitter in Xcode Scenes Swift iOS
I have developed a game in Xcode using sprite kit, and scenes. Now I am trying to integrate the functionality to post high scores to twitter and Facebook. I've looked around, and most people say to use SLComposeServiceViewController which is fine, until I try and present it. Because my app really only uses scenes, they never have the member function "presentViewController(....)". Thus, I am unable to ever present it. Anyone know any way around this?</p>

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch:UITouch = touches.first!
    let touchLocation = touch.location(in: self)
    let touchedNode = self.atPoint(touchLocation)

    if (touchedNode.name == "tryAgain") {
        let nextScene = Scene_LiveGame(size: self.scene!.size)
        nextScene.scaleMode = self.scaleMode
        self.view?.presentScene(nextScene, transition: SKTransition.fade(withDuration: 0.5))
    }
    else if (touchedNode.name == "share") {

        if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {

        let fShare = SLComposeViewController(forServiceType: SLServiceTypeFacebook)

        self.presentViewController(fShare!, animated: true, completion: nil)
         //^This is where my problem is. Xcode is telling me that self has no member function presentViewController which I totally understand, because its a scene and thus doesn't share those functions. But every resource online has shown me this is the only way to do it

        }

    }
</code>```

答:
Your are getting this error because you need to present a UIViewController from another UIViewController. So

```<code>self.presentViewController(...)
</code>```

will not work because self (SKScene) is not a UIViewController. To present from a SKScene you would have to say this

```<code>view?.window?.rootViewController?.presentViewController(fShare!, animated: true, completion: nil)
</code>```

I would recommend that you do not use those APIs anymore. Its better to use a UIActivityViewController for your sharing needs. This way you only need one share button in your app and you can share to all sorts of services (email, Twitter, Facebook, iMessage, WhatsApp etc).

Create a new Swift file and add this code.

```<code>enum ShareMenu {

    static func open(text: String, image: UIImage?, appStoreURL: String?, from viewController: UIViewController?) {
        guard let viewController = viewController, let view = viewController.view else { return }

    // Activity items
    var activityItems = [Any]()

    // Text
    activityItems.append(text)

    // Image
    if let image = image {
        activityItems.append(image)
    }

    /// App url
    if let appStoreURL = appStoreURL {
        let items = ActivityControllerItems(appStoreURL: appStoreURL)
        activityItems.append(items)
    }

    // Activity controller
    let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)

    // iPad settings
    if UIDevice.current.userInterfaceIdiom == .pad {
        activityController.modalPresentationStyle = .popover
        activityController.popoverPresentationController?.sourceView = view
        activityController.popoverPresentationController?.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
        activityController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
    }

    // Excluded activity types
    activityController.excludedActivityTypes = [
        .airDrop,
        .print,
        .assignToContact,
        .addToReadingList,
    ]

    // Present
    DispatchQueue.main.async {
        viewController.present(activityController, animated: true)
    }

    // Completion handler
    activityController.completionWithItemsHandler = { (activity, success, items, error) in
        guard success else {
            if let error = error {
                print(error.localizedDescription)
            }
            return
        }

            // do something if needed
       }
   }
}
// MARK: - Activity Controller Items

/**
 ActivityControllerItems
 */
private final class ActivityControllerItems: NSObject {

    // MARK: - Properties

    /// App name
    fileprivate let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? "-"

    /// App store web url
    fileprivate let appStoreURL: String

    // MARK: - Init

    /// Init
    fileprivate init(appStoreURL: String) {
        self.appStoreURL = appStoreURL
        super.init()
    }
}

// MARK: - UIActivityItemSource

/// UIActivityItemSource
extension ActivityControllerItems: UIActivityItemSource {

    /// Getting data items

    /// Placeholder item
    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return ""
    }

    /// Item for actity type
    func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType) -> Any? {
        return URL(string: appStoreURL) ?? appName
    }

    /// Provide info about data items

    /// Subject field for services such as email
    func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivityType?) -> String {
        return appName
    }
}
</code>```

Than when the share button is pressed you can call it like so

```<code> ShareMenu.open(
     text: "Can you beat my score?",
     image: UIImage(...),  // set to nil if unused
     appStoreURL: "your iTunes app store URL",  // set to nil if unused
     from: view?.window?.rootViewController
 )
</code>```

Bear in mind that the image and appStoreURL will not show up everywhere, it depends on the sharing service.

You can also use your score value from your scene and add it to the text e.g

```<code>ShareMenu.open(
     text: "Can you beat my score \(self.score)?",
     ...
)
</code>```

Hope this helps

Body:
I have developed a game in Xcode using sprite kit, and scenes. Now I am trying to integrate the functionality to post high scores to twitter and Facebook. I've looked around, and most people say to use SLComposeServiceViewController which is fine, until I try and present it. Because my app really only uses scenes, they never have the member function "presentViewController(....)". Thus, I am unable to ever present it. Anyone know any way around this?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch:UITouch = touches.first!
    let touchLocation = touch.location(in: self)
    let touchedNode = self.atPoint(touchLocation)

    if (touchedNode.name == "tryAgain") {
        let nextScene = Scene_LiveGame(size: self.scene!.size)
        nextScene.scaleMode = self.scaleMode
        self.view?.presentScene(nextScene, transition: SKTransition.fade(withDuration: 0.5))
    }
    else if (touchedNode.name == "share") {

        if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {

        let fShare = SLComposeViewController(forServiceType: SLServiceTypeFacebook)

        self.presentViewController(fShare!, animated: true, completion: nil)
         //^This is where my problem is. Xcode is telling me that self has no member function presentViewController which I totally understand, because its a scene and thus doesn't share those functions. But every resource online has shown me this is the only way to do it

        }

    }

Body:
Your are getting this error because you need to present a UIViewController from another UIViewController. So

self.presentViewController(...)

will not work because self (SKScene) is not a UIViewController. To present from a SKScene you would have to say this

view?.window?.rootViewController?.presentViewController(fShare!, animated: true, completion: nil)

I would recommend that you do not use those APIs anymore. Its better to use a UIActivityViewController for your sharing needs. This way you only need one share button in your app and you can share to all sorts of services (email, Twitter, Facebook, iMessage, WhatsApp etc).

Create a new Swift file and add this code.

enum ShareMenu {

    static func open(text: String, image: UIImage?, appStoreURL: String?, from viewController: UIViewController?) {
        guard let viewController = viewController, let view = viewController.view else { return }

    // Activity items
    var activityItems = [Any]()

    // Text
    activityItems.append(text)

    // Image
    if let image = image {
        activityItems.append(image)
    }

    /// App url
    if let appStoreURL = appStoreURL {
        let items = ActivityControllerItems(appStoreURL: appStoreURL)
        activityItems.append(items)
    }

    // Activity controller
    let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)

    // iPad settings
    if UIDevice.current.userInterfaceIdiom == .pad {
        activityController.modalPresentationStyle = .popover
        activityController.popoverPresentationController?.sourceView = view
        activityController.popoverPresentationController?.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
        activityController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
    }

    // Excluded activity types
    activityController.excludedActivityTypes = [
        .airDrop,
        .print,
        .assignToContact,
        .addToReadingList,
    ]

    // Present
    DispatchQueue.main.async {
        viewController.present(activityController, animated: true)
    }

    // Completion handler
    activityController.completionWithItemsHandler = { (activity, success, items, error) in
        guard success else {
            if let error = error {
                print(error.localizedDescription)
            }
            return
        }

            // do something if needed
       }
   }
}
// MARK: - Activity Controller Items

/**
 ActivityControllerItems
 */
private final class ActivityControllerItems: NSObject {

    // MARK: - Properties

    /// App name
    fileprivate let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? "-"

    /// App store web url
    fileprivate let appStoreURL: String

    // MARK: - Init

    /// Init
    fileprivate init(appStoreURL: String) {
        self.appStoreURL = appStoreURL
        super.init()
    }
}

// MARK: - UIActivityItemSource

/// UIActivityItemSource
extension ActivityControllerItems: UIActivityItemSource {

    /// Getting data items

    /// Placeholder item
    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return ""
    }

    /// Item for actity type
    func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType) -> Any? {
        return URL(string: appStoreURL) ?? appName
    }

    /// Provide info about data items

    /// Subject field for services such as email
    func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivityType?) -> String {
        return appName
    }
}

Than when the share button is pressed you can call it like so

 ShareMenu.open(
     text: "Can you beat my score?",
     image: UIImage(...),  // set to nil if unused
     appStoreURL: "your iTunes app store URL",  // set to nil if unused
     from: view?.window?.rootViewController
 )

Bear in mind that the image and appStoreURL will not show up everywhere, it depends on the sharing service.

You can also use your score value from your scene and add it to the text e.g

ShareMenu.open(
     text: "Can you beat my score \(self.score)?",
     ...
)

Hope this helps


问:
Which way is better to call a function static way or object way ?
Hi

 I'm new to OOPS, Can you guys suggest me which way is better to call a function of a class in PHP and why? the scenario is as follows.

```<code>class A
{
     function B (){}
}
</code>```

Which method will take less resource to call the function B

```<code>1. A::B();
</code>```

or

```<code>2. $obj = new A();
   $obj->B();
</code>```

答:
Firstly in PHP 7 calling non-static methods statically is deprecated so you will get an error.
Secondly it is better to call the method object way so code will be backward compatible.</p>

Body:
Hi

 I'm new to OOPS, Can you guys suggest me which way is better to call a function of a class in PHP and why? the scenario is as follows.

class A
{
     function B (){}
}

Which method will take less resource to call the function B

1. A::B();

or

2. $obj = new A();
   $obj->B();


问:
How to get the content of a textblock and show it multiple times?
I am trying to make a program that helps me with checking on which lines there are errors on an arma 3 server. It currently looks like this:

I have a few problems. Every time I mark a "bug" and press the show button it comes up with this:

How do i get the content of the textbox? This is my code:

```<code>public partial class MainWindow : Window
{
    public double output = 0;
    public string test1 = "";
    public MainWindow()
    {
        InitializeComponent();
        textOutput.Text = output.ToString();
        textBugs.Text = test1;
    }

    private void buttonDecrease_Click(object sender, RoutedEventArgs e)
    {
        output--;
        textOutput.Text = output.ToString();
    }

    private void buttonIncrease_Click(object sender, RoutedEventArgs e)
    {
        output++;
        textOutput.Text = output.ToString();
    }

    private void buttonReset_Click(object sender, RoutedEventArgs e)
    {
        output = 0;
        test1 = "N/A";
        textOutput.Text = output.ToString();
        textBugs.Text = test1;
    }

    private void buttonBug_Click(object sender, RoutedEventArgs e)
    {
        test1 += textBugs.ContentStart.ToString();
    }

    private void buttonShow_Click(object sender, RoutedEventArgs e)
    {
        textBugs.Text = test1;
    }
}
</code>```

答: A few things need to be addressed. What is in the output function that is causing the behavioral error? The other is consider changing the textbox to have an assignment of an int. That way you can increment the variable by only one and then assign it to the textbox afterward. In any case, the labelName.Text = is correct way to change the display in your windows form.

Body:
I am trying to make a program that helps me with checking on which lines there are errors on an arma 3 server. It currently looks like this:

I have a few problems. Every time I mark a "bug" and press the show button it comes up with this:

How do i get the content of the textbox? This is my code:

public partial class MainWindow : Window
{
    public double output = 0;
    public string test1 = "";
    public MainWindow()
    {
        InitializeComponent();
        textOutput.Text = output.ToString();
        textBugs.Text = test1;
    }

    private void buttonDecrease_Click(object sender, RoutedEventArgs e)
    {
        output--;
        textOutput.Text = output.ToString();
    }

    private void buttonIncrease_Click(object sender, RoutedEventArgs e)
    {
        output++;
        textOutput.Text = output.ToString();
    }

    private void buttonReset_Click(object sender, RoutedEventArgs e)
    {
        output = 0;
        test1 = "N/A";
        textOutput.Text = output.ToString();
        textBugs.Text = test1;
    }

    private void buttonBug_Click(object sender, RoutedEventArgs e)
    {
        test1 += textBugs.ContentStart.ToString();
    }

    private void buttonShow_Click(object sender, RoutedEventArgs e)
    {
        textBugs.Text = test1;
    }
}


问:
server:run Exception There are no commands defined in the "server" namespace
When I run the server using php bin/console server:run I get the following error.
There are no commands defined in the "server" namespace.

When I run php bin/console command I egt the following output. Which does't show any server: commands.

```<code>Symfony 3.3.0-DEV (kernel: app, env: dev, debug: true)

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -e, --env=ENV         The environment name [default: "dev"]
      --no-debug        Switches off debug mode
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  about                                   Displays information about the current project
  help                                    Displays help for a command
  list                                    Lists commands
 app
  app:download-beameemail                 download beame emails.
  app:download-businessunits              download businessunits.
  app:download-drivers                    download drivers.
  app:download-fleets                     download fleets.
  app:download-fmpositions                download fm_positions.
  app:download-fmtrips                    download fm_trips.
  app:download-fmunits                    download fm_units.
  app:download-skypositions               download skytrack_positions.
  app:download-skyunits                   download skytrack_units.
  app:download-vehicles                   download vehicles.
 assets
  assets:install                          Installs bundles web assets under a public web directory
 cache
  cache:clear                             Clears the cache
  cache:pool:clear                        Clears cache pools
  cache:warmup                            Warms up an empty cache
 config
  config:dump-reference                   Dumps the default configuration for an extension
 debug
  debug:config                            Dumps the current configuration for an extension
  debug:container                         Displays current services for an application
  debug:event-dispatcher                  Displays configured listeners for an application
  debug:router                            Displays current routes for an application
  debug:swiftmailer                       [swiftmailer:debug] Displays current mailers for an application
  debug:translation                       Displays translation messages information
  debug:twig                              Shows a list of twig functions, filters, globals and tests
 doctrine
  doctrine:cache:clear-collection-region  Clear a second-level cache collection region.
  doctrine:cache:clear-entity-region      Clear a second-level cache entity region.
  doctrine:cache:clear-metadata           Clears all metadata cache for an entity manager
  doctrine:cache:clear-query              Clears all query cache for an entity manager
  doctrine:cache:clear-query-region       Clear a second-level cache query region.
  doctrine:cache:clear-result             Clears result cache for an entity manager
  doctrine:database:create                Creates the configured database
  doctrine:database:drop                  Drops the configured database
  doctrine:database:import                Import SQL file(s) directly to Database.
  doctrine:ensure-production-settings     Verify that Doctrine is properly configured for a production environment.
  doctrine:generate:crud                  [generate:doctrine:crud] Generates a CRUD based on a Doctrine entity
  doctrine:generate:entities              [generate:doctrine:entities] Generates entity classes and method stubs from your mapping information
  doctrine:generate:entity                [generate:doctrine:entity] Generates a new Doctrine entity inside a bundle
  doctrine:generate:form                  [generate:doctrine:form] Generates a form type class based on a Doctrine entity
  doctrine:mapping:convert                [orm:convert:mapping] Convert mapping information between supported formats.
  doctrine:mapping:import                 Imports mapping information from an existing database
  doctrine:mapping:info
  doctrine:query:dql                      Executes arbitrary DQL directly from the command line.
  doctrine:query:sql                      Executes arbitrary SQL directly from the command line.
  doctrine:schema:create                  Executes (or dumps) the SQL needed to generate the database schema
  doctrine:schema:drop                    Executes (or dumps) the SQL needed to drop the current database schema
  doctrine:schema:update                  Executes (or dumps) the SQL needed to update the database schema to match the current mapping metadata.
  doctrine:schema:validate                Validate the mapping files.
 fos
  fos:js-routing:debug                    Displays currently exposed routes for an application
  fos:js-routing:dump                     Dumps exposed routes to the filesystem
 generate
  generate:bundle                         Generates a bundle
  generate:command                        Generates a console command
  generate:controller                     Generates a controller
 lint
  lint:twig                               Lints a template and outputs encountered errors
  lint:xliff                              Lints a XLIFF file and outputs encountered errors
  lint:yaml                               Lints a file and outputs encountered errors
 router
  router:match                            Helps debug routes by simulating a path info match
 security
  security:check                          Checks security issues in your project dependencies
  security:encode-password                Encodes a password.
 swiftmailer
  swiftmailer:email:send                  Send simple email message
  swiftmailer:spool:send                  Sends emails from the spool
 translation
  translation:update                      Updates the translation file
</code>```

I've tried to fix it by running composer require symfony/symfony and composer update but it still doesn't show.
Is there anything else that I can try?

Edit below is my php info from php -version

```<code>PHP 7.0.15-0ubuntu0.16.04.4 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.15-0ubuntu0.16.04.4, Copyright (c) 1999-2017, by Zend Technologies
    with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans
</code>```

EDIT 2

the directory vendor\symfon\symfony\src\Symfony\Bundle\FrameworkBundle\Command exists and contains the following files

```<code>AboutCommand.php
AbstractConfigCommand.php
AssetsInstallCommand.php
CacheClearCommand.php
CachePoolClearCommand.php
CacheWarmupCommand.php
ConfigDebugCommand.php
ConfigDumpReferenceCommand.php
ContainerAwareCommand.php
ContainerDebugCommand.php
EventDispatcherDebugCommand.php
RouterDebugCommand.php
RouterMatchCommand.php
TranslationDebugCommand.php
TranslationUpdateCommand.php
WorkflowDumpCommand.php
XliffLintCommand.php
YamlLintCommand.php
</code>```

答:
As I mentioned in my comment, in S3.3 the server commands have been moved to their own WebServerBundle.  Some editing of AppKernel.php is required to activate the bundle.  I suspect that many other developers might run into this once 3.3 is actually released and people try upgrading.

I make no promises but try updating AppKernel.php with:

```<code>    if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
        $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
        $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
        $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

        if ('dev' === $this->getEnvironment()) {
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
            $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
        }
    }
</code>```

I don't have a good test project to try it on but at least the commands should show up.

And in case anyone is wondering,  all I did was to install a fresh development project and poked around a bit.

```<code>composer create-project symfony/framework-standard-edition s33 "3.3.*" --stability=dev
</code>```

I also found this but it does not mention the need to update AppKernel.php
http://symfony.com/blog/new-in-symfony-3-3-webserverbundle

From the upgrade guide: https://github.com/symfony/symfony/blob/3.4/UPGRADE-3.3.md

The server:run, server:start, server:stop and server:status console commands have been moved to a dedicated bundle. Require symfony/web-server-bundle in your composer.json and register Symfony\Bundle\WebServerBundle\WebServerBundle in your AppKernel to use them.

As long as your composer.json has symfony/symfony in it then there is no need to add the web server bundle to it.  Just need to adjust the AppKernel file.

Body:
When I run the server using php bin/console server:run I get the following error.
There are no commands defined in the "server" namespace.

When I run php bin/console command I egt the following output. Which does't show any server: commands.

Symfony 3.3.0-DEV (kernel: app, env: dev, debug: true)

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -e, --env=ENV         The environment name [default: "dev"]
      --no-debug        Switches off debug mode
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  about                                   Displays information about the current project
  help                                    Displays help for a command
  list                                    Lists commands
 app
  app:download-beameemail                 download beame emails.
  app:download-businessunits              download businessunits.
  app:download-drivers                    download drivers.
  app:download-fleets                     download fleets.
  app:download-fmpositions                download fm_positions.
  app:download-fmtrips                    download fm_trips.
  app:download-fmunits                    download fm_units.
  app:download-skypositions               download skytrack_positions.
  app:download-skyunits                   download skytrack_units.
  app:download-vehicles                   download vehicles.
 assets
  assets:install                          Installs bundles web assets under a public web directory
 cache
  cache:clear                             Clears the cache
  cache:pool:clear                        Clears cache pools
  cache:warmup                            Warms up an empty cache
 config
  config:dump-reference                   Dumps the default configuration for an extension
 debug
  debug:config                            Dumps the current configuration for an extension
  debug:container                         Displays current services for an application
  debug:event-dispatcher                  Displays configured listeners for an application
  debug:router                            Displays current routes for an application
  debug:swiftmailer                       [swiftmailer:debug] Displays current mailers for an application
  debug:translation                       Displays translation messages information
  debug:twig                              Shows a list of twig functions, filters, globals and tests
 doctrine
  doctrine:cache:clear-collection-region  Clear a second-level cache collection region.
  doctrine:cache:clear-entity-region      Clear a second-level cache entity region.
  doctrine:cache:clear-metadata           Clears all metadata cache for an entity manager
  doctrine:cache:clear-query              Clears all query cache for an entity manager
  doctrine:cache:clear-query-region       Clear a second-level cache query region.
  doctrine:cache:clear-result             Clears result cache for an entity manager
  doctrine:database:create                Creates the configured database
  doctrine:database:drop                  Drops the configured database
  doctrine:database:import                Import SQL file(s) directly to Database.
  doctrine:ensure-production-settings     Verify that Doctrine is properly configured for a production environment.
  doctrine:generate:crud                  [generate:doctrine:crud] Generates a CRUD based on a Doctrine entity
  doctrine:generate:entities              [generate:doctrine:entities] Generates entity classes and method stubs from your mapping information
  doctrine:generate:entity                [generate:doctrine:entity] Generates a new Doctrine entity inside a bundle
  doctrine:generate:form                  [generate:doctrine:form] Generates a form type class based on a Doctrine entity
  doctrine:mapping:convert                [orm:convert:mapping] Convert mapping information between supported formats.
  doctrine:mapping:import                 Imports mapping information from an existing database
  doctrine:mapping:info
  doctrine:query:dql                      Executes arbitrary DQL directly from the command line.
  doctrine:query:sql                      Executes arbitrary SQL directly from the command line.
  doctrine:schema:create                  Executes (or dumps) the SQL needed to generate the database schema
  doctrine:schema:drop                    Executes (or dumps) the SQL needed to drop the current database schema
  doctrine:schema:update                  Executes (or dumps) the SQL needed to update the database schema to match the current mapping metadata.
  doctrine:schema:validate                Validate the mapping files.
 fos
  fos:js-routing:debug                    Displays currently exposed routes for an application
  fos:js-routing:dump                     Dumps exposed routes to the filesystem
 generate
  generate:bundle                         Generates a bundle
  generate:command                        Generates a console command
  generate:controller                     Generates a controller
 lint
  lint:twig                               Lints a template and outputs encountered errors
  lint:xliff                              Lints a XLIFF file and outputs encountered errors
  lint:yaml                               Lints a file and outputs encountered errors
 router
  router:match                            Helps debug routes by simulating a path info match
 security
  security:check                          Checks security issues in your project dependencies
  security:encode-password                Encodes a password.
 swiftmailer
  swiftmailer:email:send                  Send simple email message
  swiftmailer:spool:send                  Sends emails from the spool
 translation
  translation:update                      Updates the translation file

I've tried to fix it by running composer require symfony/symfony and composer update but it still doesn't show.
Is there anything else that I can try?

Edit below is my php info from php -version

PHP 7.0.15-0ubuntu0.16.04.4 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.15-0ubuntu0.16.04.4, Copyright (c) 1999-2017, by Zend Technologies
    with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans

EDIT 2

the directory vendor\symfon\symfony\src\Symfony\Bundle\FrameworkBundle\Command exists and contains the following files

AboutCommand.php
AbstractConfigCommand.php
AssetsInstallCommand.php
CacheClearCommand.php
CachePoolClearCommand.php
CacheWarmupCommand.php
ConfigDebugCommand.php
ConfigDumpReferenceCommand.php
ContainerAwareCommand.php
ContainerDebugCommand.php
EventDispatcherDebugCommand.php
RouterDebugCommand.php
RouterMatchCommand.php
TranslationDebugCommand.php
TranslationUpdateCommand.php
WorkflowDumpCommand.php
XliffLintCommand.php
YamlLintCommand.php

Body:
As I mentioned in my comment, in S3.3 the server commands have been moved to their own WebServerBundle.  Some editing of AppKernel.php is required to activate the bundle.  I suspect that many other developers might run into this once 3.3 is actually released and people try upgrading.

I make no promises but try updating AppKernel.php with:

    if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
        $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
        $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
        $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

        if ('dev' === $this->getEnvironment()) {
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
            $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
        }
    }

I don't have a good test project to try it on but at least the commands should show up.

And in case anyone is wondering,  all I did was to install a fresh development project and poked around a bit.

composer create-project symfony/framework-standard-edition s33 "3.3.*" --stability=dev

I also found this but it does not mention the need to update AppKernel.php
http://symfony.com/blog/new-in-symfony-3-3-webserverbundle

From the upgrade guide: https://github.com/symfony/symfony/blob/3.4/UPGRADE-3.3.md

The server:run, server:start, server:stop and server:status console commands have been moved to a dedicated bundle. Require symfony/web-server-bundle in your composer.json and register Symfony\Bundle\WebServerBundle\WebServerBundle in your AppKernel to use them.

As long as your composer.json has symfony/symfony in it then there is no need to add the web server bundle to it.  Just need to adjust the AppKernel file.


问:
Change SSH pem file
I want to change my remote server SSH. Currently I login through a .pem file

```<code>ssh -l ubuntu -i .ssh/myfile.pem XX.XX.XXX.XXX
</code>```

I tried to find how to change that access key but I found only that methor :

```<code>ssh-keygen -t rsa -b 2048
cp id_rsa.pub authorised_keys
scp authorized_keys ubuntu@XX.XX.XXX.XXX:/home/ubuntu/.ssh
</code>```

I see no .pem file generated, plus how can I connect now ?
I want to make sure before I do anything so I don't lose ability to connect via SSH.
Should I remove the old key with :

```<code>ssh-keygen -R hostname
</code>```

If yes, when ? after or before the scp ? if after this will remove both keys, if before then I wouldn't be able to perform scp !!!
I am a bot confused.
I see no .pem file in my remote, the pem file is only in my local .ssh folder. in remote .ssh I see :

答:
With "ssh-keygen" command you generate a pair of public and private keys (by default stored in $HOME/.ssh).

Then you copy the public key in your remote server, and the private key in your local client (with permissions 0600). You can use "ssh-add" command to add the private key to the authentication agent to be able to connect to the remote server.

Title: Change SSH pem file

Body:
I want to change my remote server SSH. Currently I login through a .pem file

ssh -l ubuntu -i .ssh/myfile.pem XX.XX.XXX.XXX

I tried to find how to change that access key but I found only that methor :

ssh-keygen -t rsa -b 2048
cp id_rsa.pub authorised_keys
scp authorized_keys ubuntu@XX.XX.XXX.XXX:/home/ubuntu/.ssh

I see no .pem file generated, plus how can I connect now ?
I want to make sure before I do anything so I don't lose ability to connect via SSH.
Should I remove the old key with :

ssh-keygen -R hostname

If yes, when ? after or before the scp ? if after this will remove both keys, if before then I wouldn't be able to perform scp !!!
I am a bot confused.
I see no .pem file in my remote, the pem file is only in my local .ssh folder. in remote .ssh I see :


问:
Create 2 independent components DrawerLayout left and right
How to create 2 DrawerLayout as in the screenshot. And they should be independent and they can be opened 2 simultaneously

答:
two_drawer.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <include
        android:id="@+id/main_layout"
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_left"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@color/right_side_header_bg_color"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_right" />

</android.support.v4.widget.DrawerLayout>
</code>```

In java file

```<code>private NavigationView navigationView_left, navigationView_right;

navigationView_left = (NavigationView) findViewById(R.id.nav_view);
 navigationView_left.setNavigationItemSelectedListener(this);
 navigationView_right =(NavigationView)findViewById(R.id.nav_view_right);
 navigationView_right.setNavigationItemSelectedListener(this);
</code>```

Body:
two_drawer.xml

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <include
        android:id="@+id/main_layout"
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_left"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@color/right_side_header_bg_color"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_right" />

</android.support.v4.widget.DrawerLayout>

In java file

private NavigationView navigationView_left, navigationView_right;

navigationView_left = (NavigationView) findViewById(R.id.nav_view);
 navigationView_left.setNavigationItemSelectedListener(this);
 navigationView_right =(NavigationView)findViewById(R.id.nav_view_right);
 navigationView_right.setNavigationItemSelectedListener(this);


问:
BIRT report custom font not shown
My birt-eclipse 4.6.0 editor displays custom fonts correctly.
I'm trying to understand why some custom fonts are displayed while other are not (falling back to standard) when report is generated to PDF (or other format) on birt runtime 4.4.2 server.

I'm registering custom fonts using below method when server starts:

```<code>com.lowagie.text.FontFactory.register("/font/path")
</code>```

Same problem happens when I click Run -> View Report -> As PDF in eclipse-editor.
For example AvenirNextLTPro-MediumCn.otf is displayed, but AvenirLTStd-Medium.otf is not. Same happens with *.ttf fonts - some displayed correctly, others do not. But all are visible in birt-eclipse editor.

Editor and runtime server are running on same machine - Ubuntu 16.04, fonts are copied to /usr/share/fonts and registered with fc-cache -fv command.

Why some fonts are not visible in PDF?

答:
Could not find exact cause of the problem, I think it is somehow related to font naming.

Solution that worked for me:

```<code>com.lowagie.text.FontFactory.register(String path, String alias)
</code>```

There is a "register" method that accepts second parameter - font alias.  In my case, second parameter was "Avenir LT Std". Took this title from BIRT-eclipse editor's font drop-down list.

Title: BIRT report custom font not shown

Body:
My birt-eclipse 4.6.0 editor displays custom fonts correctly.
I'm trying to understand why some custom fonts are displayed while other are not (falling back to standard) when report is generated to PDF (or other format) on birt runtime 4.4.2 server.

I'm registering custom fonts using below method when server starts:

com.lowagie.text.FontFactory.register("/font/path")

Same problem happens when I click Run -> View Report -> As PDF in eclipse-editor.
For example AvenirNextLTPro-MediumCn.otf is displayed, but AvenirLTStd-Medium.otf is not. Same happens with *.ttf fonts - some displayed correctly, others do not. But all are visible in birt-eclipse editor.

Editor and runtime server are running on same machine - Ubuntu 16.04, fonts are copied to /usr/share/fonts and registered with fc-cache -fv command.

Why some fonts are not visible in PDF?

Body:
Could not find exact cause of the problem, I think it is somehow related to font naming.

Solution that worked for me:

com.lowagie.text.FontFactory.register(String path, String alias)

There is a "register" method that accepts second parameter - font alias.  In my case, second parameter was "Avenir LT Std". Took this title from BIRT-eclipse editor's font drop-down list.


问:
What is the difference between CPU Revision and Revision fields for arm processors?
Making a cat /proc/cpuinfo on Android returns this kind of output:

```<code>    Processor   : ARMv7 Processor rev 1 (v7l)
    processor   : 0
    BogoMIPS    : 38.00

    processor   : 1
    BogoMIPS    : 38.00

    processor   : 2
    BogoMIPS    : 38.00

    processor   : 3
    BogoMIPS    : 38.00

    Features    : swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32
    CPU implementer : 0x51
    CPU architecture: 7
    CPU variant : 0x2
    CPU part    : 0x06f
    CPU revision    : 1

    Hardware    : Qualcomm MSM8974PRO-AC
    Revision    : 0000
    Serial      : 0000000000000000
</code>```

I do not find the meaning difference between those two fields:

CPU revision

Revision

答:
CPU revision: It Indicates patch release or "minor revision". In your case it is 1. So this value is specific to your CPU. You can see that CPU revision is matching to Processor   : ARMv7 Processor rev 1 (v7l)

You can refer to attached image for the details of other filled as well.

Revision: It is related to your hardware (board) configuration. In your case your are using the Qualcomm hardware so revision number depends upon on it. It is independent of the CPU revision number.

Body:
Making a cat /proc/cpuinfo on Android returns this kind of output:

    Processor   : ARMv7 Processor rev 1 (v7l)
    processor   : 0
    BogoMIPS    : 38.00

    processor   : 1
    BogoMIPS    : 38.00

    processor   : 2
    BogoMIPS    : 38.00

    processor   : 3
    BogoMIPS    : 38.00

    Features    : swp half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32
    CPU implementer : 0x51
    CPU architecture: 7
    CPU variant : 0x2
    CPU part    : 0x06f
    CPU revision    : 1

    Hardware    : Qualcomm MSM8974PRO-AC
    Revision    : 0000
    Serial      : 0000000000000000

I do not find the meaning difference between those two fields:

CPU revision

Revision


问:
regexp for renaming multiple files using 'rename.pl'
I'm using rename.pl to rename a multiple files. I am having trouble coming up with the right regexp. My file names are of the form:

nn.some.title.string.ext

I want to change just the first '.' to ' - '. I thought this would work but it does not.

```<code>s/\.?/ - /
</code>```

Can someone help me out with this? TIA.

答:
Just try this for simple regex pattern.</p>

```<code>my $str = "nn.some.title.string.ext";

$str=~s/^([^\.]*)\./$1-/i;
or
$str=~s/\./-/;

#^([^\.]*)       Starting point upto the first dot

print $str;
</code>```

Body:
I'm using rename.pl to rename a multiple files. I am having trouble coming up with the right regexp. My file names are of the form:

nn.some.title.string.ext

I want to change just the first '.' to ' - '. I thought this would work but it does not.

s/\.?/ - /

Can someone help me out with this? TIA.

Body:
Just try this for simple regex pattern.

my $str = "nn.some.title.string.ext";

$str=~s/^([^\.]*)\./$1-/i;
or
$str=~s/\./-/;

#^([^\.]*)       Starting point upto the first dot

print $str;


问:
Can I create a GIT fork with limited branch set
My parent repository has master, development, release and feature branches. I want to create a fork with only master, development and release branch.

Is this possible with GIT. How do I achieve this?

答:
It kind of depends on what you mean about only wanting certain branches.  Or, more to the point, on what you're hoping to gain from only having certain branches.

If it's as simple as wanting a shorter list of refs when you git branch --list --all, then Alejandro Montilla's suggestion (fork then delete branches) should work.

If the parent repo has significant size bound up in unmerged branches and you want to reclaim that space, that's a little harder.  You'd have to make sure after the branches were deleted that gc cleaned it up.  You can always gc a local repo, but when it's hosted on a service, they may or may not offer control over garbage collection.

Maybe you want something even more complicated... many people seem to find a history that preserves the original branch topology to be "messy" and they want to "clean it up" - much of the motivation behind various rebasing operations. This would require getting rid of not only merged branches, but the commits in (one line of) the merge's history. There's not an easy way to do this to an existing history (and if you do, any relationship between the resulting repo and the parent repo would be irrevocably lost).  So if that's what you're after, you might consider re-framing the problem in terms of how to get better looking log output for the history as it exists.


问:
How to implement video with connectionservice
I want to implement a videochat using the system app via connectionservice.  https://developer.android.com/reference/android/telecom/ConnectionService.html. Unfortunately i can not find any example or tutorial how to do it.  Here is what i have done:

Registering the service:

```<code>TelecomManager manager = (TelecomManager) getSystemService(TELECOM_SERVICE);
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(new    ComponentName(getBaseContext().getPackageName(),    PhoneConnectionService.class.getName()), "myConnectionServiceId");
PhoneAccount.Builder builder = PhoneAccount.builder(phoneAccountHandle,   Localization.localize(R.string.IDS_APP_NAME_SHORT));
builder.setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER | PhoneAccount.CAPABILITY_CONNECTION_MANAGER| PhoneAccount.CAPABILITY_VIDEO_CALLING );
PhoneAccount phoneAccount = builder.build();
manager.registerPhoneAccount(phoneAccount);
</code>```

Placing the call:

```<code>TelecomManager manager = (TelecomManager) context.getSystemService(TELECOM_SERVICE);
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(new ComponentName(context.getPackageName(), PhoneConnectionService.class.getName()), "estosConnectionServiceId");
Bundle test = new Bundle();
test.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,phoneAccountHandle);
test.putInt(TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, VideoProfile.STATE_BIDIRECTIONAL);
test.putParcelable(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS,extras);
manager.placeCall(Uri.parse("tel:" + number),test);
</code>```

My ConnectionService get called and

```<code>@Override
public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {

    Connection conn = new MyAndroidCallConnection();
    conn.setAddress(request.getAddress(),PRESENTATION_ALLOWED);
    conn.setInitializing();
    conn.setVideoProvider(new MyVideoProvider());
    conn.setActive();

    return conn;
}
</code>```

i place my videoprovider into the connection the system asks for.
The phone activity appears and showing me the call with the little camera sign, so the system knows what i want to do.
I now somehow expect that the videoprovider methods get called from the system to give me the surfaces for video and so on but no method get called.
Does somebody know what am i doing wrong or know where to find a good example of this topic.

答: I simply forgot to add conn.setVideoState(VideoProfile.STATE_BIDIRECTIONAL); to my connection not only on placeCall. Now the VideoProvider is accessed as expected

Body:
I want to implement a videochat using the system app via connectionservice.  https://developer.android.com/reference/android/telecom/ConnectionService.html. Unfortunately i can not find any example or tutorial how to do it.  Here is what i have done:

Registering the service:

TelecomManager manager = (TelecomManager) getSystemService(TELECOM_SERVICE);
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(new    ComponentName(getBaseContext().getPackageName(),    PhoneConnectionService.class.getName()), "myConnectionServiceId");
PhoneAccount.Builder builder = PhoneAccount.builder(phoneAccountHandle,   Localization.localize(R.string.IDS_APP_NAME_SHORT));
builder.setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER | PhoneAccount.CAPABILITY_CONNECTION_MANAGER| PhoneAccount.CAPABILITY_VIDEO_CALLING );
PhoneAccount phoneAccount = builder.build();
manager.registerPhoneAccount(phoneAccount);

Placing the call:

TelecomManager manager = (TelecomManager) context.getSystemService(TELECOM_SERVICE);
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(new ComponentName(context.getPackageName(), PhoneConnectionService.class.getName()), "estosConnectionServiceId");
Bundle test = new Bundle();
test.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,phoneAccountHandle);
test.putInt(TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, VideoProfile.STATE_BIDIRECTIONAL);
test.putParcelable(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS,extras);
manager.placeCall(Uri.parse("tel:" + number),test);

My ConnectionService get called and

@Override
public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {

    Connection conn = new MyAndroidCallConnection();
    conn.setAddress(request.getAddress(),PRESENTATION_ALLOWED);
    conn.setInitializing();
    conn.setVideoProvider(new MyVideoProvider());
    conn.setActive();

    return conn;
}

i place my videoprovider into the connection the system asks for.
The phone activity appears and showing me the call with the little camera sign, so the system knows what i want to do.
I now somehow expect that the videoprovider methods get called from the system to give me the surfaces for video and so on but no method get called.
Does somebody know what am i doing wrong or know where to find a good example of this topic.


问:
What are the chances for collision in sum of 2 hash codes?
What is the probability of collision if a new hash code is generated by added 2 other hash codes in Java

Eg:

```<code>Integer reportHashCode = reportFields.hashCode() + reportId.hashCode();
</code>```

Let's assume Java's hash code is 32bits and we can ignore normal collision in the hash code itself.

答: I would XOR here instead of addition, cause xor has a 50-50% of distribution of 1 and 0.

Body:
What is the probability of collision if a new hash code is generated by added 2 other hash codes in Java

Eg:

Integer reportHashCode = reportFields.hashCode() + reportId.hashCode();

Let's assume Java's hash code is 32bits and we can ignore normal collision in the hash code itself.


问:
extended algorithm implementation in matlab
i have  found following pseudo-code for extended euclidean algorithm

i implemented following algorithm

```<code>    function [x1,y1,d1]=extend_eucledian(a,b)
            if b==0
                x1=1;
                y1=0;
                d1=a;
                return;
            end

            [x1,y1,d1]=extend_eucledian(b,mod(a,b));

 x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;

        end
</code>```

when i run   following  this program, i got following  result

```<code>[x1,y1,d1]=extend_eucledian(23,20)

x1 =

     0

y1 =

     0

d1 =

     1
</code>```

i guess that  [x1,y1,d1] are not changing their values  during the iteration, for instance  , i have tried following code

```<code>    function [x1,y1,d1]=extend_eucledian(a,b)
            if b==0
                x1=1;
                y1=0;
                d1=a;
                return;
            else
                 x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;
            end

            [x1,y1,d1]=extend_eucledian(b,mod(a,b));

        end
</code>```

but i got

```<code>>> [x1,y1,d1]=extend_eucledian(23,20)
Undefined function or variable 'y1'.

Error in extend_eucledian (line 8)
                 x1=y1;
</code>```

how can i fix this  problem? where i am making mistake?

答:
The error in the question is that x1, y1, d1 are used simultaneously as working and output variables. The code can be rewritten using a new tern [x, y d] for the output values:

```<code>function [x y d]=eucledian_pairs(a,b)
%a>0,b>0
%d=gcd(a,b)  a*x+y*b=d
[x1,y1,d1]=extend_eucledian(a,b);

x=y1;
y=x1-floor(a/b)*y1;
d=d1;

    function [x1,y1,d1]=extend_eucledian(a,b)
        if b==0
            x1=1;
            y1=0;
            d1=a;
            return;
        end
        [x1,y1,d1]=extend_eucledian(b,mod(a,b));
    end
end
</code>```

Executing this code gives the desired result.

```<code>>> [x y d]=eucledian_pairs(20,25)

x =

     0

y =

     1

d =

     5
</code>```

Body:
i have  found following pseudo-code for extended euclidean algorithm

i implemented following algorithm

    function [x1,y1,d1]=extend_eucledian(a,b)
            if b==0
                x1=1;
                y1=0;
                d1=a;
                return;
            end

            [x1,y1,d1]=extend_eucledian(b,mod(a,b));

 x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;

        end

when i run   following  this program, i got following  result

[x1,y1,d1]=extend_eucledian(23,20)

x1 =

     0

y1 =

     0

d1 =

     1

i guess that  [x1,y1,d1] are not changing their values  during the iteration, for instance  , i have tried following code

    function [x1,y1,d1]=extend_eucledian(a,b)
            if b==0
                x1=1;
                y1=0;
                d1=a;
                return;
            else
                 x1=y1;
y1=x1-floor(a/b)*y1;
d1=d1;
            end

            [x1,y1,d1]=extend_eucledian(b,mod(a,b));

        end

but i got

>> [x1,y1,d1]=extend_eucledian(23,20)
Undefined function or variable 'y1'.

Error in extend_eucledian (line 8)
                 x1=y1;

how can i fix this  problem? where i am making mistake?

Body:
The error in the question is that x1, y1, d1 are used simultaneously as working and output variables. The code can be rewritten using a new tern [x, y d] for the output values:

function [x y d]=eucledian_pairs(a,b)
%a>0,b>0
%d=gcd(a,b)  a*x+y*b=d
[x1,y1,d1]=extend_eucledian(a,b);

x=y1;
y=x1-floor(a/b)*y1;
d=d1;

    function [x1,y1,d1]=extend_eucledian(a,b)
        if b==0
            x1=1;
            y1=0;
            d1=a;
            return;
        end
        [x1,y1,d1]=extend_eucledian(b,mod(a,b));
    end
end

Executing this code gives the desired result.

>> [x y d]=eucledian_pairs(20,25)

x =

     0

y =

     1

d =

     5


问:
Wpf Application Does not start at startup but run manually?
I have created an app in WPF which is just polling app. Now I want to start that app on windows Startup (after user login). I also created an installer package using Wix Toolset which adds a registry key to Software\Microsoft\Windows\CurrentVersion\Run. Program actually tries to run but gives no error. I was able to get error from Windows Event Viewer and I cannot understand where this error is generated.

Stack Trace:

```<code>Application: icBlync.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.DirectoryNotFoundException
   at System.IO.__Error.WinIOError(Int32, System.String)
   at System.IO.FileStream.Init(System.String, System.IO.FileMode, System.IO.FileAccess, Int32, Boolean, System.IO.FileShare, Int32, System.IO.FileOptions, SECURITY_ATTRIBUTES, System.String, Boolean, Boolean, Boolean)
   at System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare)
   at System.Windows.Media.Imaging.BitmapDecoder.SetupDecoderFromUriOrStream(System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCacheOption, System.Guid ByRef, Boolean ByRef, System.IO.Stream ByRef, System.IO.UnmanagedMemoryStream ByRef, Microsoft.Win32.SafeHandles.SafeFileHandle ByRef)
   at System.Windows.Media.Imaging.BitmapDecoder.CreateFromUriOrStream(System.Uri, System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCreateOptions, System.Windows.Media.Imaging.BitmapCacheOption, System.Net.Cache.RequestCachePolicy, Boolean)
   at System.Windows.Media.Imaging.BitmapFrame.CreateFromUriOrStream(System.Uri, System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCreateOptions, System.Windows.Media.Imaging.BitmapCacheOption, System.Net.Cache.RequestCachePolicy)
   at System.Windows.Media.Imaging.BitmapFrame.Create(System.Uri, System.Net.Cache.RequestCachePolicy)
   at System.Windows.Media.Imaging.BitmapFrame.Create(System.Uri)
   at icBlync.Windows.SettingWindow..ctor()
   at icBlync.App..ctor()
   at icBlync.App.Main()
</code>```

Pls Help.

答:
When App starts from Startup, working directory was not the installed directory. So when the app tries to load Icons, it gives System.IO.DirectoryNotFoundException.

I just changed the working directory to the Installed directory using:

```<code>Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
</code>```

Body:
I have created an app in WPF which is just polling app. Now I want to start that app on windows Startup (after user login). I also created an installer package using Wix Toolset which adds a registry key to Software\Microsoft\Windows\CurrentVersion\Run. Program actually tries to run but gives no error. I was able to get error from Windows Event Viewer and I cannot understand where this error is generated.

Stack Trace:

Application: icBlync.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.DirectoryNotFoundException
   at System.IO.__Error.WinIOError(Int32, System.String)
   at System.IO.FileStream.Init(System.String, System.IO.FileMode, System.IO.FileAccess, Int32, Boolean, System.IO.FileShare, Int32, System.IO.FileOptions, SECURITY_ATTRIBUTES, System.String, Boolean, Boolean, Boolean)
   at System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare)
   at System.Windows.Media.Imaging.BitmapDecoder.SetupDecoderFromUriOrStream(System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCacheOption, System.Guid ByRef, Boolean ByRef, System.IO.Stream ByRef, System.IO.UnmanagedMemoryStream ByRef, Microsoft.Win32.SafeHandles.SafeFileHandle ByRef)
   at System.Windows.Media.Imaging.BitmapDecoder.CreateFromUriOrStream(System.Uri, System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCreateOptions, System.Windows.Media.Imaging.BitmapCacheOption, System.Net.Cache.RequestCachePolicy, Boolean)
   at System.Windows.Media.Imaging.BitmapFrame.CreateFromUriOrStream(System.Uri, System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCreateOptions, System.Windows.Media.Imaging.BitmapCacheOption, System.Net.Cache.RequestCachePolicy)
   at System.Windows.Media.Imaging.BitmapFrame.Create(System.Uri, System.Net.Cache.RequestCachePolicy)
   at System.Windows.Media.Imaging.BitmapFrame.Create(System.Uri)
   at icBlync.Windows.SettingWindow..ctor()
   at icBlync.App..ctor()
   at icBlync.App.Main()

Pls Help.

Body:
When App starts from Startup, working directory was not the installed directory. So when the app tries to load Icons, it gives System.IO.DirectoryNotFoundException.

I just changed the working directory to the Installed directory using:

Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);


问:
How can I sort data in descending order using sails-js?
I want my data sort by "createdAt" column . Sometime in ascending order and also descending order also. I am using mongo db .

Currently, I have created app which have feature like Users data can be sorted by admin request. Admin can view data in ascending order or by descending order.

I have tried option by using sort parameter which gives me data every time in same order. How can I change as admin per admin request.

Please review below that I have tried.

```<code>var options = {
    limit: request.body.limit || undefined,
    skip: request.body.skip || undefined,
    sort: request.body.sort || "createdAt",
    where: request.body.where  || undefined
};

Users.find(options, function (err, Users) {
    if (Users === undefined) {
        return response.json({message: "No data Found"});
    }
    else if (err) {
        return response.json({message: err});
    } else {
        return response.json({data: Users});
    }
});
</code>```

答:
try this

```<code>var myQuery = Users.find(options);

// if you want to sort in descending order
myQuery.sort('createdAt DESC');

// if you want to sort in ascending order
myQuery.sort('createdAt ASC')

myQuery.exec(function callBack(err,results){
    console.log(results)
});
</code>```

Body:
I want my data sort by "createdAt" column . Sometime in ascending order and also descending order also. I am using mongo db .

Currently, I have created app which have feature like Users data can be sorted by admin request. Admin can view data in ascending order or by descending order.

I have tried option by using sort parameter which gives me data every time in same order. How can I change as admin per admin request.

Please review below that I have tried.

var options = {
    limit: request.body.limit || undefined,
    skip: request.body.skip || undefined,
    sort: request.body.sort || "createdAt",
    where: request.body.where  || undefined
};

Users.find(options, function (err, Users) {
    if (Users === undefined) {
        return response.json({message: "No data Found"});
    }
    else if (err) {
        return response.json({message: err});
    } else {
        return response.json({data: Users});
    }
});

Body:
try this

var myQuery = Users.find(options);

// if you want to sort in descending order
myQuery.sort('createdAt DESC');

// if you want to sort in ascending order
myQuery.sort('createdAt ASC')

myQuery.exec(function callBack(err,results){
    console.log(results)
});


问:
Load runner throwing 406 Error while replaying script
While replaying the script I am getting below error message:
Error -26625: HTTP Status-Code=406 (Not Acceptable) for "https://example.com"      [MsgId: MERR-26625]

406 - Client browser does not accept the MIME type of the requested
  page.

The page you are looking for cannot be opened by your browser because
  it has a file name extension that your browser does not accept.

Getting this error at below call

```<code>web_custom_request("bootstrap",
                   "URL=https://<Domain Information>",
                   "Method=POST",
                   "Resource=0",
                   "RecContentType=application/json",
                   "Referer=https://<Domain Information>",
                   "Mode=HTTP",
                   "EncType=application/json;
</code>```

Can you please suggest how can I overcome this error.

答: Have you considered that you may be missing a header in your request?   Also a possibility, cookie mismanagement - Which could also be header related if you needed a cookie value in the header which was unhandled.</p>

Body:
While replaying the script I am getting below error message:
Error -26625: HTTP Status-Code=406 (Not Acceptable) for "https://example.com"      [MsgId: MERR-26625]

406 - Client browser does not accept the MIME type of the requested
  page.

The page you are looking for cannot be opened by your browser because
  it has a file name extension that your browser does not accept.

Getting this error at below call

web_custom_request("bootstrap",
                   "URL=https://<Domain Information>",
                   "Method=POST",
                   "Resource=0",
                   "RecContentType=application/json",
                   "Referer=https://<Domain Information>",
                   "Mode=HTTP",
                   "EncType=application/json;

Can you please suggest how can I overcome this error.


问:
Why is UICollectionView insetForSectionsAtIndex not being called?
I'm looking to use the following function but unfortunately it's not being called.

```<code>func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlowLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        let cellCount = Double(collectionView.numberOfItems(inSection: section))
        if let cell = collectionView.cellForItem(at: IndexPath(row: 0, section: section))
        {
            let cellWidth = Double(cell.frame.size.width)
            let totalCellWidth = cellWidth * cellCount
            let cellSpacing = Double(collectionViewLayout.minimumInteritemSpacing)
            let totalSpacingWidth = cellSpacing * (cellCount - 1)

            let leftInset = (collectionView.frame.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
            let rightInset = leftInset

            return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
        }

    return collectionView.layoutMargins
}
</code>```

I'm getting the following console errors but my cell is smaller than my collectionView and I've set the section insets and layout margins to 0.

2017-03-30 11:25:14.624 Prep[92400:1862856] The behavior of the UICollectionViewFlowLayout is not defined because:
  2017-03-30 11:25:14.624 Prep[92400:1862856] the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values.
  2017-03-30 11:25:14.624 Prep[92400:1862856] The relevant UICollectionViewFlowLayout instance is , and it is attached to ; layer = ; contentOffset: {0, 0}; contentSize: {0, 68.5}> collection view layout: .
  2017-03-30 11:25:14.625 Prep[92400:1862856] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
   cell height --> 42.0

Protocols

```<code>class OverviewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var vipCollectionView: UICollectionView!

var hostedMeetingsArray: [String]?
var vipArray: [Attendee]?

class OverviewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var vipCollectionView: UICollectionView!

var hostedMeetingsArray: [String]?
var vipArray: [Attendee]?
</code>```

答:
Ok, the problem that insetForSectionAt is not called is that you have to implement it like this:

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

   //access to minimumInteritemSpacing by casting to UICollectionViewFlowLayout
   let layout = collectionViewLayout as! UICollectionViewFlowLayout
   let spacing = layout.minimumInteritemSpacing

   return UIEdgeInsetsMake(0.5,0,0.5,0)

}
</code>```

Take a look on UICollectionViewDelegateFlowLayout protocol. The insetForSectionAt is declared like this:

```<code>@available(iOS 6.0, *)
optional public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
</code>```

So you need that first optional parameter, to implement this function.

Body:
I'm looking to use the following function but unfortunately it's not being called.

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlowLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        let cellCount = Double(collectionView.numberOfItems(inSection: section))
        if let cell = collectionView.cellForItem(at: IndexPath(row: 0, section: section))
        {
            let cellWidth = Double(cell.frame.size.width)
            let totalCellWidth = cellWidth * cellCount
            let cellSpacing = Double(collectionViewLayout.minimumInteritemSpacing)
            let totalSpacingWidth = cellSpacing * (cellCount - 1)

            let leftInset = (collectionView.frame.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
            let rightInset = leftInset

            return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
        }

    return collectionView.layoutMargins
}

I'm getting the following console errors but my cell is smaller than my collectionView and I've set the section insets and layout margins to 0.

2017-03-30 11:25:14.624 Prep[92400:1862856] The behavior of the UICollectionViewFlowLayout is not defined because:
  2017-03-30 11:25:14.624 Prep[92400:1862856] the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values.
  2017-03-30 11:25:14.624 Prep[92400:1862856] The relevant UICollectionViewFlowLayout instance is , and it is attached to ; layer = ; contentOffset: {0, 0}; contentSize: {0, 68.5}> collection view layout: .
  2017-03-30 11:25:14.625 Prep[92400:1862856] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
   cell height --> 42.0

Protocols

class OverviewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var vipCollectionView: UICollectionView!

var hostedMeetingsArray: [String]?
var vipArray: [Attendee]?

class OverviewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var vipCollectionView: UICollectionView!

var hostedMeetingsArray: [String]?
var vipArray: [Attendee]?

Body:
Ok, the problem that insetForSectionAt is not called is that you have to implement it like this:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

   //access to minimumInteritemSpacing by casting to UICollectionViewFlowLayout
   let layout = collectionViewLayout as! UICollectionViewFlowLayout
   let spacing = layout.minimumInteritemSpacing

   return UIEdgeInsetsMake(0.5,0,0.5,0)

}

Take a look on UICollectionViewDelegateFlowLayout protocol. The insetForSectionAt is declared like this:

@available(iOS 6.0, *)
optional public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets

So you need that first optional parameter, to implement this function.