问:
How can I create a android swipe up menu? Please refer to the attached images
I want my home screen to look like this

When i click on the center button or swipe up a menu should appear

答:
I was trying to animated the layout from bottom to top on the click of a button
layout :

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/click"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    android:layout_width="wrap_content"
    android:text="click"
    android:layout_height="wrap_content" />

<RelativeLayout
    android:visibility="gone"
    android:id="@+id/layout"
    android:background="#313131"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</RelativeLayout>
</code>```

java:

```<code>public class Sample extends AppCompatActivity {
RelativeLayout layout;
Boolean isAnimated = false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sample);

    Button click = (Button) findViewById(R.id.click);
    layout = (RelativeLayout) findViewById(R.id.layout);

    click.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!isAnimated){
                layout.setVisibility(View.VISIBLE);
                layout.startAnimation(AnimationUtils.loadAnimation(Sample.this, R.anim.translate_animation_top));
                isAnimated = true;
            }else {
                layout.setVisibility(View.GONE);
                layout.startAnimation(AnimationUtils.loadAnimation(Sample.this, R.anim.translate_animation_bottom));
                isAnimated = false;
            }

        }
    });
}}
</code>```

Animation file:

translate_animation_bottom:

```<code><set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="4000"
    android:fromXDelta="0"
    android:fromYDelta="0%"
    android:toXDelta="0"
    android:toYDelta="100%" />
</code>```

translate_animation_top:

```<code><set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="4000"
    android:fromXDelta="0"
    android:fromYDelta="100%"
    android:toXDelta="0"
    android:toYDelta="0%" />
</code>```

Body:
I was trying to animated the layout from bottom to top on the click of a button
layout :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/click"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    android:layout_width="wrap_content"
    android:text="click"
    android:layout_height="wrap_content" />

<RelativeLayout
    android:visibility="gone"
    android:id="@+id/layout"
    android:background="#313131"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</RelativeLayout>

java:

public class Sample extends AppCompatActivity {
RelativeLayout layout;
Boolean isAnimated = false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sample);

    Button click = (Button) findViewById(R.id.click);
    layout = (RelativeLayout) findViewById(R.id.layout);

    click.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!isAnimated){
                layout.setVisibility(View.VISIBLE);
                layout.startAnimation(AnimationUtils.loadAnimation(Sample.this, R.anim.translate_animation_top));
                isAnimated = true;
            }else {
                layout.setVisibility(View.GONE);
                layout.startAnimation(AnimationUtils.loadAnimation(Sample.this, R.anim.translate_animation_bottom));
                isAnimated = false;
            }

        }
    });
}}

Animation file:

translate_animation_bottom:

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="4000"
    android:fromXDelta="0"
    android:fromYDelta="0%"
    android:toXDelta="0"
    android:toYDelta="100%" />

translate_animation_top:

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="4000"
    android:fromXDelta="0"
    android:fromYDelta="100%"
    android:toXDelta="0"
    android:toYDelta="0%" />


来源: stackexchange

问:
@RequestParam couldn't find CommonsMultipartFile attachFile[]
I am creating an email service using Spring 4 where the user can upload multiple attachments and the inputs come from a JSP page. I have implemented the service in the following way:

The JSP Page:

```<code><%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html >
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring MVC - Email</title>
</head>
<body>
<h1>Spring MVC - Send e-mail with attachments</h1>

<form method="post" action="/sendEmail2" enctype="multipart/form-data">
    Email To:
    <input type="text" name="mailTo[]" size="65"/><br>

    CC:
    <input type="text" name="ccTo[]" size="65"/><br>

    Subject:
    <input type="text" name="subject" size="65"/><br>

    Message:
    <textarea cols="50" rows="10" name="message"></textarea><br>

    From:
    <input type="text" name="from" size="65"/><br>

    Attach file:
    <input type="file" name="attachFile[]" size="60"/><br>

    <input type="submit" value="Send E-mail"/>
</form>
</body>
</html>
</code>```

The controller:

```<code>@Controller
public class myController2 {

    @Autowired
    ReportingService2 service2;

    @RequestMapping(value = "/sendEmail2", method = RequestMethod.POST)
public String sendEmail2(HttpServletRequest request,
                         @RequestParam CommonsMultipartFile attachFile[]
) {
    String emailTo[] = request.getParameterValues("mailTo[]");
    String ccTo[] = request.getParameterValues("ccTo[]");
    String subject = request.getParameter("subject");
    String msg = request.getParameter("message");
    fromName = request.getParameter("from");

    boolean res = service2.sendEmail(
            emailTo, ccTo, subject, msg, attachFile,
            fromName, username, password, hostName,
            encoding, protocol, portNo, TLS,
            sendPartial, SMTPAuth, SSL
    );

    if (res) {
        return "/WEB-INF/Result";

    } else {
        return "errorpage";
    }
}
</code>```

The Service for email:

```<code>@Service
public class EmailService2 implements ReportingService2 {

    @Override
    public boolean sendEmail(String[] toEmailAddresses, String[] toCc,
                             String subject, String message,
                             CommonsMultipartFile[] attachFile,
                             String fromName, String userName,
                             String password, String hostName,
                             String encoding, String protocol,
                             String portNo, boolean TLS, boolean sendPartial,
                             boolean SMTPAuth, boolean SSL) {

        Properties mailProperties = new Properties();

        if (SSL) {
            // if SSL is used then port no should be 465
            mailProperties.put("mail.smtp.ssl.enable", true);
            mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            mailProperties.put("mail.smtp.socketFactory.port", portNo);
            mailProperties.put("mail.smtp.socketFactory.fallback", false);

        } else if (TLS) {
            //if TLS is used then port no should be 587
            mailProperties.put("mail.smtp.starttls.enable", true);
        }

        if (SMTPAuth) {
            mailProperties.put("mail.smtp.auth", true);
        }

        if (sendPartial) {
            mailProperties.put("mail.smtp.sendpartial", true);
        }

        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setJavaMailProperties(mailProperties);

        //if no TLS and no SSL then default port no is 25
        javaMailSenderImpl.setPort(Integer.parseInt(portNo));
        javaMailSenderImpl.setHost(hostName);
        javaMailSenderImpl.setUsername(userName);
        javaMailSenderImpl.setPassword(password);
        javaMailSenderImpl.setDefaultEncoding(encoding);

        javaMailSenderImpl.send(mimeMessage -> {

            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, encoding);

            messageHelper.setSubject(subject);
            messageHelper.setText(message);
            messageHelper.setFrom(fromName);

            if (toEmailAddresses != null) {
                for (String singleEmailTo : toEmailAddresses) {
                    messageHelper.setTo(singleEmailTo);
                }
            }

            if (toCc != null) {
                for (String singleCc : toCc) {
                    messageHelper.setCc(singleCc);
                }
            }

            if (attachFile != null) {
                for (CommonsMultipartFile singleFile : attachFile) {
                    messageHelper.addAttachment(singleFile.getOriginalFilename(), singleFile);
                }
            }
        });

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

Now when i run the project and hit the mapping the error i get is in the controller. Below is the error message:

```<code>**HTTP Status 400 – Bad Request**

**Type** Status Report

**Message** Required CommonsMultipartFile[] parameter 'attachFile' is not present

**Description** The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Apache Tomcat/8.5.23
</code>```

I have tried to receive the array of attachments in the following way but it says incompatible type:

```<code>CommonsMultipartFile[] files=request.getParameterValues("attachFile[]");
</code>```

Please help...

答:
In your controller use

```<code>@RequestParam("attachFile")
</code>```

As the error message says, spring framework is looking for a parameter with name 'attachFile'

ContentLicense: CC BY-SA 3.0

Body:
I am creating an email service using Spring 4 where the user can upload multiple attachments and the inputs come from a JSP page. I have implemented the service in the following way:

The JSP Page:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html >

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring MVC - Email</title>

Spring MVC - Send e-mail with attachments

<form method="post" action="/sendEmail2" enctype="multipart/form-data">
    Email To:
    <input type="text" name="mailTo[]" size="65"/>

    CC:
    <input type="text" name="ccTo[]" size="65"/>

    Subject:
    <input type="text" name="subject" size="65"/>

    Message:
    <textarea cols="50" rows="10" name="message"></textarea>

    From:
    <input type="text" name="from" size="65"/>

    Attach file:
    <input type="file" name="attachFile[]" size="60"/>

    <input type="submit" value="Send E-mail"/>
</form>

The controller:

@Controller
public class myController2 {

    @Autowired
    ReportingService2 service2;

    @RequestMapping(value = "/sendEmail2", method = RequestMethod.POST)
public String sendEmail2(HttpServletRequest request,
                         @RequestParam CommonsMultipartFile attachFile[]
) {
    String emailTo[] = request.getParameterValues("mailTo[]");
    String ccTo[] = request.getParameterValues("ccTo[]");
    String subject = request.getParameter("subject");
    String msg = request.getParameter("message");
    fromName = request.getParameter("from");

    boolean res = service2.sendEmail(
            emailTo, ccTo, subject, msg, attachFile,
            fromName, username, password, hostName,
            encoding, protocol, portNo, TLS,
            sendPartial, SMTPAuth, SSL
    );

    if (res) {
        return "/WEB-INF/Result";

    } else {
        return "errorpage";
    }
}

The Service for email:

@Service
public class EmailService2 implements ReportingService2 {

    @Override
    public boolean sendEmail(String[] toEmailAddresses, String[] toCc,
                             String subject, String message,
                             CommonsMultipartFile[] attachFile,
                             String fromName, String userName,
                             String password, String hostName,
                             String encoding, String protocol,
                             String portNo, boolean TLS, boolean sendPartial,
                             boolean SMTPAuth, boolean SSL) {

        Properties mailProperties = new Properties();

        if (SSL) {
            // if SSL is used then port no should be 465
            mailProperties.put("mail.smtp.ssl.enable", true);
            mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            mailProperties.put("mail.smtp.socketFactory.port", portNo);
            mailProperties.put("mail.smtp.socketFactory.fallback", false);

        } else if (TLS) {
            //if TLS is used then port no should be 587
            mailProperties.put("mail.smtp.starttls.enable", true);
        }

        if (SMTPAuth) {
            mailProperties.put("mail.smtp.auth", true);
        }

        if (sendPartial) {
            mailProperties.put("mail.smtp.sendpartial", true);
        }

        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setJavaMailProperties(mailProperties);

        //if no TLS and no SSL then default port no is 25
        javaMailSenderImpl.setPort(Integer.parseInt(portNo));
        javaMailSenderImpl.setHost(hostName);
        javaMailSenderImpl.setUsername(userName);
        javaMailSenderImpl.setPassword(password);
        javaMailSenderImpl.setDefaultEncoding(encoding);

        javaMailSenderImpl.send(mimeMessage -> {

            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, encoding);

            messageHelper.setSubject(subject);
            messageHelper.setText(message);
            messageHelper.setFrom(fromName);

            if (toEmailAddresses != null) {
                for (String singleEmailTo : toEmailAddresses) {
                    messageHelper.setTo(singleEmailTo);
                }
            }

            if (toCc != null) {
                for (String singleCc : toCc) {
                    messageHelper.setCc(singleCc);
                }
            }

            if (attachFile != null) {
                for (CommonsMultipartFile singleFile : attachFile) {
                    messageHelper.addAttachment(singleFile.getOriginalFilename(), singleFile);
                }
            }
        });

        return true;
    }
}

Now when i run the project and hit the mapping the error i get is in the controller. Below is the error message:

**HTTP Status 400 – Bad Request**

**Type** Status Report

**Message** Required CommonsMultipartFile[] parameter 'attachFile' is not present

**Description** The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Apache Tomcat/8.5.23

I have tried to receive the array of attachments in the following way but it says incompatible type:

CommonsMultipartFile[] files=request.getParameterValues("attachFile[]");

Please help...

Body:
In your controller use

@RequestParam("attachFile")

As the error message says, spring framework is looking for a parameter with name 'attachFile'


问:
VBA run time error 438
I am trying to write a code to open a PPTX file from excel VBA and update links in ppt.

below is the code that i have got but while the code is trying to update links i am getting the

Run time error 438 Object does not support this property or method

```<code>Sub kunal()

Dim PPObj As Object

Set PPObj = CreateObject("PowerPoint.application")

With PPObj
    .Presentations.Add

    .Presentations.Open Filename:="Y:\Desktop\Month End\One_Shot\Template AVP Report Package\ABD-OME SDeeson.pptx"

    .Visible = True
    .UpdateLinks
    .Presentation.Save

    .Quit
    Set PPObj = Nothing
End With

End Sub
</code>```

答:
438 means that you are trying to access a property of a method or object, that does not exist. Thus, you need a presentation object and not application object to update the links.

Try like this:

```<code>Option Explicit

Sub kunal()

    Dim PPObj As Object
    Dim pptPresentation As Object

    Set PPObj = CreateObject("PowerPoint.application")
    Set pptPresentation = PPObj.presentations.Open("C:\test.pptx")

    With PPObj

        .presentations.Add

        .Visible = True
        pptPresentation.UpdateLinks
        pptPresentation.Save
        pptPresentation.Close

        .Quit
        'Set PPObj = Nothing - No need for this
    End With

End Sub
</code>```

Application Object MSDN

Presentation Object MSDN

Title: VBA run time error 438

Body:
I am trying to write a code to open a PPTX file from excel VBA and update links in ppt.

below is the code that i have got but while the code is trying to update links i am getting the

Run time error 438 Object does not support this property or method

Sub kunal()

Dim PPObj As Object

Set PPObj = CreateObject("PowerPoint.application")

With PPObj
    .Presentations.Add

    .Presentations.Open Filename:="Y:\Desktop\Month End\One_Shot\Template AVP Report Package\ABD-OME SDeeson.pptx"

    .Visible = True
    .UpdateLinks
    .Presentation.Save

    .Quit
    Set PPObj = Nothing
End With

End Sub

Body:
438 means that you are trying to access a property of a method or object, that does not exist. Thus, you need a presentation object and not application object to update the links.

Try like this:

Option Explicit

Sub kunal()

    Dim PPObj As Object
    Dim pptPresentation As Object

    Set PPObj = CreateObject("PowerPoint.application")
    Set pptPresentation = PPObj.presentations.Open("C:\test.pptx")

    With PPObj

        .presentations.Add

        .Visible = True
        pptPresentation.UpdateLinks
        pptPresentation.Save
        pptPresentation.Close

        .Quit
        'Set PPObj = Nothing - No need for this
    End With

End Sub

Application Object MSDN

Presentation Object MSDN


问:
How to create a new user in OpenShift?
I am trying to find out how to create a new user in OpenShift enterprise.

According to the documentation (on https://docs.openshift.com/enterprise/3.0/architecture/core_concepts/projects_and_users.html):

Regular users are created automatically in the system upon first login...

This sounds illogical. How does a user login if they dont have a username and password?

Can someone please clarify this - I'm sure there must be some command for creating a new user, but it is not clear.

Thanks

答:
I am creating a script for simply adding a user if OpenShift using HTPasswdPasswordIdentityProvider

```<code>wget https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64
mv jq-linux64 jq && chmod 755 jq

FILE=$(cat /etc/origin/master/master-config.yaml | python -c 'import sys, yaml, json; y=yaml.load(sys.stdin.read()); print json.dumps(y,indent=4, sort_keys=True)' | ./jq '.oauthConfig.identityProviders[0].provider.file')
FILE=$(sed -e 's/^"//' -e 's/"$//' <<<"$FILE")

htpasswd $FILE user1
</code>```

Title: How to create a new user in OpenShift?

Body:
I am creating a script for simply adding a user if OpenShift using HTPasswdPasswordIdentityProvider

wget https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64
mv jq-linux64 jq && chmod 755 jq

FILE=$(cat /etc/origin/master/master-config.yaml | python -c 'import sys, yaml, json; y=yaml.load(sys.stdin.read()); print json.dumps(y,indent=4, sort_keys=True)' | ./jq '.oauthConfig.identityProviders[0].provider.file')
FILE=$(sed -e 's/^"//' -e 's/"$//' <<<"$FILE")

htpasswd $FILE user1


问:
Downloadhander (save plot) for basic plot in shiny
How to save plot using download button in shiny?

I know how to do it for ggplot, but I can't find how to do it for basic plot().

Example:

```<code>library(shiny)
library(ggplot2)

# ui
ui <- fluidPage(
  downloadButton("save", "save")
)

# server
server <- function(input, output){

  p <- reactive({ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()})
  p2 <- reactive({dotchart(iris$Sepal.Length, iris$Species, iris$Species)})

  output$save <- downloadHandler(
    file = "save.png" , # variable with filename
    content = function(file) {
      ggsave(p(), filename = file)
    })
}

# run
shinyApp(ui, server)
</code>```

above there is implemented saving the plot p. Now how to implement saving the plot p2 ?

答:
You can write it on a png object using device graphics. Check the code.

```<code>library(shiny)
library(ggplot2)

# ui
ui <- fluidPage(
  downloadButton("save", "save")
)

# server
server <- function(input, output){

  p <- reactive({ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()})
  p2 <- reactive({dotchart(iris$Sepal.Length, iris$Species, iris$Species)})

  output$save <- downloadHandler(
    file = "save.png" , # variable with filename
    content = function(file) {
      #ggsave(p(), filename = file)
      png(file = file)
      p2()
      dev.off()
    })
}

# run
shinyApp(ui, server)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to save plot using download button in shiny?

I know how to do it for ggplot, but I can't find how to do it for basic plot().

Example:

library(shiny)
library(ggplot2)

# ui
ui <- fluidPage(
  downloadButton("save", "save")
)

# server
server <- function(input, output){

  p <- reactive({ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()})
  p2 <- reactive({dotchart(iris$Sepal.Length, iris$Species, iris$Species)})

  output$save <- downloadHandler(
    file = "save.png" , # variable with filename
    content = function(file) {
      ggsave(p(), filename = file)
    })
}

# run
shinyApp(ui, server)

above there is implemented saving the plot p. Now how to implement saving the plot p2 ?

Body:
You can write it on a png object using device graphics. Check the code.

library(shiny)
library(ggplot2)

# ui
ui <- fluidPage(
  downloadButton("save", "save")
)

# server
server <- function(input, output){

  p <- reactive({ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()})
  p2 <- reactive({dotchart(iris$Sepal.Length, iris$Species, iris$Species)})

  output$save <- downloadHandler(
    file = "save.png" , # variable with filename
    content = function(file) {
      #ggsave(p(), filename = file)
      png(file = file)
      p2()
      dev.off()
    })
}

# run
shinyApp(ui, server)


问:
Javascript loop through Json
Trying to figure out how to loop through users in the following Json response:

```<code>{ "id": 23, "users": { "26": "user 333", "27": "user 222" } }
</code>```

A normal for-loop is not working, i.e for(i = 0; i <object.users.length; i++). So I started thinking maybe it's not a normal array because there are no [] brackets. But even the simplest operation fails: alert(object.users[0]).

I need help figuring out how I can loop through each user and get both key and value (key:value).

答:
You can do something like this (a loop on the keys of your sub-object): </p>

```<code>for(var u in object.users){
    var user = object.users[u];
}
</code>```

Title: Javascript loop through Json

Body:
Trying to figure out how to loop through users in the following Json response:

{ "id": 23, "users": { "26": "user 333", "27": "user 222" } }

A normal for-loop is not working, i.e for(i = 0; i <object.users.length; i++). So I started thinking maybe it's not a normal array because there are no [] brackets. But even the simplest operation fails: alert(object.users[0]).

I need help figuring out how I can loop through each user and get both key and value (key:value).

Body:
You can do something like this (a loop on the keys of your sub-object):

for(var u in object.users){
    var user = object.users[u];
}


问:
Mocha First unit test always slower than the others
For some reason the first unit test of my test suit is always slower than the others. When executing the tests in my console I get something like:

```<code>√ unit test A (483ms)
√ unit test B
</code>```

But in the code if I change the unit test B to above the unit test A, I get this:

```<code>√ unit test B (470ms)
√ unit test A
</code>```

For some reason the first unit tests gets always slower and because of that I think, the reason of being slow in not my code, but something in Mocha. At the same time I have others tests suits that are testing other code and it works fine, so I'm confused. Maybe is not Mocha, but due to not being sure, I need to ask if you have an idea of what can be happening.

The test is something like this:

```<code>let target = require('...');

describe('Module of unit tests', function () {
  this.timeout(1000);
  before(function () {
        ...
    target = proxyquire('...', {
      'node-chartist': sinon.stub().resolves('...'),
      'ws': function(){
        return {
          'close': function(){ /*Do nothing*/ },
          'send': function(){ /*Do nothing*/ },
          'on': function(arg, callback){
            ...
          }
        };
      }
    });
  });

  //Warning happens here
  it('unit test A', function () {
    ...
    target();
    ...
  });

  //If this unit test goes above unit test A, this will be the one to get
  the warning.
  it('unit test B', function () {
    ...
    target();
    ...
  });
})
</code>```

`

I tried to reproduce in other projects without success, so I doubt you will be able to do it, but what I'm doing is execute tests suit with unit test A above and then execute tests suit with unit test B above.

Versions:

```<code>node v6.11.4
npm 3.10.10
mocha 4.0.1
sinon 4.1.2
chai 3.5.0
proxyquire 1.8.0
</code>```

I used fiddler to make sure that while executing the unit tests, none network request was being made for the outside, to make sure that the delay is not caused by any network request.

I also debugged the code that the unit test is testing and I really don't see any reason for the delay in any case.

Thanks for any help.

答:
The problem was happening because I was making some stubs with proxyquire and by default the npm modules are loaded even when stubbed. In my case I have a module called node-chartist that was being loaded during the first unit test and the others unit tests were using cache, I suppose. that is why the other unit tests weren't slower.

To solve this problem I had to use the method noCallThru() of proxyquire which make proxyquire don't load any original dependencies.

Kind regards

Body:
For some reason the first unit test of my test suit is always slower than the others. When executing the tests in my console I get something like:

√ unit test A (483ms)
√ unit test B

But in the code if I change the unit test B to above the unit test A, I get this:

√ unit test B (470ms)
√ unit test A

For some reason the first unit tests gets always slower and because of that I think, the reason of being slow in not my code, but something in Mocha. At the same time I have others tests suits that are testing other code and it works fine, so I'm confused. Maybe is not Mocha, but due to not being sure, I need to ask if you have an idea of what can be happening.

The test is something like this:

let target = require('...');

describe('Module of unit tests', function () {
  this.timeout(1000);
  before(function () {
        ...
    target = proxyquire('...', {
      'node-chartist': sinon.stub().resolves('...'),
      'ws': function(){
        return {
          'close': function(){ /*Do nothing*/ },
          'send': function(){ /*Do nothing*/ },
          'on': function(arg, callback){
            ...
          }
        };
      }
    });
  });

  //Warning happens here
  it('unit test A', function () {
    ...
    target();
    ...
  });

  //If this unit test goes above unit test A, this will be the one to get
  the warning.
  it('unit test B', function () {
    ...
    target();
    ...
  });
})

`

I tried to reproduce in other projects without success, so I doubt you will be able to do it, but what I'm doing is execute tests suit with unit test A above and then execute tests suit with unit test B above.

Versions:

node v6.11.4
npm 3.10.10
mocha 4.0.1
sinon 4.1.2
chai 3.5.0
proxyquire 1.8.0

I used fiddler to make sure that while executing the unit tests, none network request was being made for the outside, to make sure that the delay is not caused by any network request.

I also debugged the code that the unit test is testing and I really don't see any reason for the delay in any case.

Thanks for any help.


问:
Find if listA contains any elements not in listB
I have two lists:

```<code>List<int> listA
List<int> listB
</code>```

How to check using LINQ if in the listA exists an element wchich deosn't exists in the listB ? I can use the foreach loop but I'm wondering if I can do this using LINQ

答:
This piece of code compares two lists both containing a field for a CultureCode like 'en-GB'. This will leave non existing translations in the list. (we needed a dropdown list for not-translated languages for articles)

var compared = supportedLanguages.Where(sl => !existingTranslations.Any(fmt => fmt.CultureCode == sl.Culture)).ToList();

Body:
I have two lists:

List<int> listA
List<int> listB

How to check using LINQ if in the listA exists an element wchich deosn't exists in the listB ? I can use the foreach loop but I'm wondering if I can do this using LINQ


问:
Finding K closest elements from the median of an unsorted Array
Given an unsorted array, I am trying to find the K nearest elements to the median of an Array.  I am having trouble finding the solution in linear running time.

```<code>A[] = 1, 2, 3, 4, 5 ,6 , 30 ,31, 32 ,33 ,34    # assume sorting part is done
</code>```

Median here is 6.

Answer for this is 2,3,4,5,6.

Any help or hint will be appreciated.

答:
My suggestion for this would be a two step approach.

First, use the Median of Medians algorithm to find the Median of an unsorted array in linear time.

Second, scan the array and fill a Max Heap (of size k), where elements are organized according to distance to the median, in order to find the k nearest elements.

You ensure that the heap never contains more than k elements in the following way. When you want add the (k+1)th element to the heap you check if it is smaller than the root. If so you add it to the heap, and after reorganization of the heap you remove the (new)root. If not you can discard it.

The above should have a runtime of O(N log(k)) which is linear in N.

Body:
Given an unsorted array, I am trying to find the K nearest elements to the median of an Array.  I am having trouble finding the solution in linear running time.

A[] = 1, 2, 3, 4, 5 ,6 , 30 ,31, 32 ,33 ,34    # assume sorting part is done

Median here is 6.

Answer for this is 2,3,4,5,6.

Any help or hint will be appreciated.


问:
jquery maintain scroll position for modal dialog
If users are not authenticated and click something only authenticated users do then i am loading a modal dialog saying they need to login to perform this.

the modal contains a link which when clicked is meant to load a modal dialog with a login form.

this is what i have:

```<code>$("#login-link").click(function () {
        $("#dialog-unauthenticated").dialog("close");
        var x = $(this).position().left + jQuery(this).outerWidth();
        var y = $(this).position().top - jQuery(document).scrollTop();
        $("#dialog-form").dialog("open",{position:[x,y]});

    });
</code>```

it works okay, the only problem is that the page does not maintain the scroll position.
the dialog loads in the right place.

how can i maintaining page scroll position instead of it scrolling to the top?

答:
when opening the first modal (or right before) - save the page (document? document.body?)  scroll position into some variables.
then, on your $("#login-link").click() function, set it to those values you saved.
sorry I don't have code for you, but basicall it's</p>

```<code>$(document).scrollTop()
// or
$(document.body).scrollTop()
// or even without the $ function!
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If users are not authenticated and click something only authenticated users do then i am loading a modal dialog saying they need to login to perform this.

the modal contains a link which when clicked is meant to load a modal dialog with a login form.

this is what i have:

$("#login-link").click(function () {
        $("#dialog-unauthenticated").dialog("close");
        var x = $(this).position().left + jQuery(this).outerWidth();
        var y = $(this).position().top - jQuery(document).scrollTop();
        $("#dialog-form").dialog("open",{position:[x,y]});

    });

it works okay, the only problem is that the page does not maintain the scroll position.
the dialog loads in the right place.

how can i maintaining page scroll position instead of it scrolling to the top?

Body:
when opening the first modal (or right before) - save the page (document? document.body?)  scroll position into some variables.
then, on your $("#login-link").click() function, set it to those values you saved.
sorry I don't have code for you, but basicall it's

$(document).scrollTop()
// or
$(document.body).scrollTop()
// or even without the $ function!


问:
Get php variable in JavaScript - options
I'm aware that there are similar questions, however, I have a few issues with them, as they mentioned a few possibilities and I'm not sure which one is best for my situation.

I have a form that has one section where you can enter the name of an xml-file, which is then generated using php. The name of the file is stored in a variable using php. In order to access the xml-file, I wanted to retrieve the value of the php-variable in JavaScript.
According to what I read, there are a few possibilities:

An Ajax-request. My problem: I tried to follow this tutorial (https://www.w3schools.com/xml/ajax_php.asp). I don't fully understand this tutorial though.

First of all, in the first example, what is "this"? (e.g this.responseText)

Secondly, why is it "gethint.php?q=" + str instead of simply "gethint.php" (in xmlhttp.open())?

Finally, what does $q = $_REQUEST["q"]; tell me exactly? I know that some kind of a variable is declared but I don't understand what is does exactly.

I also read that you could use cookies, but would that make sense in my instance?
Please let me know if you need further information and thank you very much in advance for your replies.

Edit: Here's the code I tried to follow:
HTML:

```<code><html>
<head>
<script>
    function showHint(str) {
        if (str.length == 0) {
            document.getElementById("txtHint").innerHTML = "";
            return;
        } else {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "gethint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

    <p><b>Start typing a name in the input field below:</b></p>
    <form>
        First name: <input type="text" onkeyup="showHint(this.value)">
    </form>
    <p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
</code>```

PHP:

```<code>// get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";
            }
        }
    }
}

// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
</code>```

$a is an array of names, which I did not include in the extract in order to save space.

Here's my code:

HTML:

```<code><body onload="alertFunction()">
    <h1 id="title">Append to me:</h1>
    <p id="paragraph"></p>
</body>
</code>```

JavaScript:

```<code>function alertFunction() {
    var xhttp;

    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var filename = xhttp.responseText;
            alert(filename);
        }
    };
    xhttp.open("GET", "profile3.php?q=", true);
    xhttp.send();
};
</code>```

PHP:

```<code><?php
    $q = $_REQUEST["q"];
    echo $filename
?>
</code>```

$filename is declared to be the name of my xml-document. I did not include that piece of code because I know that that's not the problem.

答:
I would have to say the w3schools isn't the best resource.
But anyway:

First of all, in the first example, what is "this"? (e.g
  this.responseText)

XMLHttpRequest is an object and it has properties.
this is used to access the XMLHttpRequest object properties in the scope of its event handler (onreadystatechange).

Secondly, why is it "gethint.php?q=" + str instead of simply
  "gethint.php" (in xmlhttp.open())?

It's a matter of usage but in this example you want to send data to the server side, then the server-side's script does something with this data and returns a response. So you're passing the str variable with a query string.

Finally, what does $q = $_REQUEST["q"]; tell me exactly? I know that
  some kind of a variable is declared but I don't understand what is
  does exactly.

In continuation to the previous point, now it's the server's side script turn to get the data we've sent in the ajax request.
q is the query string variable. (?q=something)
and by using $_REQUEST['q'] the script will be able to access to that value. so if $q = $_REQUEST['q'], now $q would be "something".

Body:
I'm aware that there are similar questions, however, I have a few issues with them, as they mentioned a few possibilities and I'm not sure which one is best for my situation.

I have a form that has one section where you can enter the name of an xml-file, which is then generated using php. The name of the file is stored in a variable using php. In order to access the xml-file, I wanted to retrieve the value of the php-variable in JavaScript.
According to what I read, there are a few possibilities:

An Ajax-request. My problem: I tried to follow this tutorial (https://www.w3schools.com/xml/ajax_php.asp). I don't fully understand this tutorial though.

First of all, in the first example, what is "this"? (e.g this.responseText)

Secondly, why is it "gethint.php?q=" + str instead of simply "gethint.php" (in xmlhttp.open())?

Finally, what does $q = $_REQUEST["q"]; tell me exactly? I know that some kind of a variable is declared but I don't understand what is does exactly.

I also read that you could use cookies, but would that make sense in my instance?
Please let me know if you need further information and thank you very much in advance for your replies.

Edit: Here's the code I tried to follow:
HTML:

Start typing a name in the input field below:

    <form>
        First name: <input type="text" onkeyup="showHint(this.value)">
    </form>

Suggestions:

PHP:

// get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";
            }
        }
    }
}

// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>

$a is an array of names, which I did not include in the extract in order to save space.

Here's my code:

HTML:

Append to me:

JavaScript:

function alertFunction() {
    var xhttp;

    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var filename = xhttp.responseText;
            alert(filename);
        }
    };
    xhttp.open("GET", "profile3.php?q=", true);
    xhttp.send();
};

PHP:

<?php
    $q = $_REQUEST["q"];
    echo $filename
?>

$filename is declared to be the name of my xml-document. I did not include that piece of code because I know that that's not the problem.


答:
do it like this</p>

```<code>for(var u in object.users){
    var user = object.users[u];
}
</code>```

Title: Javascript loop through Json

Body:
do it like this

for(var u in object.users){
    var user = object.users[u];
}


问:
PHP file not opening with html head tag
When I open this php file, it does not load:

```<code><?php
    echo "I am awesome";
?>
<html>
<head> </head>
</html>
</code>```

Error screenshot

However, if I remove the  tag, code works fine.

I've used both Xampp and Wamp servers on Windows PC, tried changing ports but the issue still persists.

Solved: Using http://127.0.0.1/test.php instead of http://localhost/test.php fixed the problem for me and code executed successfully.

答: I think you have saved it as html. Change it to php.</p>

Title: PHP file not opening with html head tag

Body:
When I open this php file, it does not load:

<?php
    echo "I am awesome";
?>

Error screenshot

However, if I remove the  tag, code works fine.

I've used both Xampp and Wamp servers on Windows PC, tried changing ports but the issue still persists.

Solved: Using http://127.0.0.1/test.php instead of http://localhost/test.php fixed the problem for me and code executed successfully.


问:
Meteor-up terminates after running deploy
I don't know why I'm getting this error. Meteor-up is a brilliant. Whenever I run the deploy command it gets to a time and terminates. Could it be that a timeout has been set for the server to finish uploading the files?

```<code>C:\Programs\contract\schoolapps\.deploy>mup.cmd deploy --cached-build

   ┌─────────────────────────────────────┐
   │                                     │
   │   update available 1.3.2 => 1.3.3   │
   │     To update, run npm i -g mup     │
   │                                     │
   └─────────────────────────────────────┘

Not building app. Using build from previous deploy at
C:\Users\Kehinde\AppData\Local\Temp\mup-meteor-58e876b4-e682-4ecf-9d41-168fa46a5b19

Started TaskList: Pushing Meteor App
[xxx.xxx.xx.xx] - Pushing Meteor App Bundle to The Server
[===============                        ] 41% 630.4sevents.js:160
      throw er; // Unhandled 'error' event
      ^

Error: write ECONNRESET
    at exports._errnoException (util.js:1020:11)
    at WriteWrap.afterWrite (net.js:800:14)

C:\Programs\contract\schoolapps\.deploy>
</code>```

After the upload was successful I got this error:

```<code>[xxx.xxx.xx.xx] x Prepare Bundle: FAILED

        -----------------------------------STDERR-----------------------------------
        Error response from daemon: No such container: myappsupload
        The command '/bin/sh -c cd  /built_app/programs/server &&     npm install --unsafe-perm' returned a non-zero code: 1
        Error response from daemon: No such container: myappsupload
        Error: failed to start containers: myappsupload
        -----------------------------------STDOUT-----------------------------------
        mnpm ERR! meteor-dev-bundle@0.0.0 install: `node npm-rebuild.js`
        npm ERR! Exit status 254
        npm ERR!
        npm ERR! Failed at the meteor-dev-bundle@0.0.0 install script 'node npm-rebuild.js'.
        npm ERR! Make sure you have the latest version of node.js and npm installed.
        npm ERR! If you do, this is most likely a problem with the meteor-dev-bundle package,
        npm ERR! not with npm itself.
        npm ERR! Tell the author that this fails on your system:
        npm ERR!     node npm-rebuild.js
        npm ERR! You can get information on how to open an issue for this project with:
        npm ERR!     npm bugs meteor-dev-bundle
        npm ERR! Or if that isn't available, you can get their info via:
        npm ERR!     npm owner ls meteor-dev-bundle
        npm ERR! There is likely additional logging output above.

        npm ERR! Please include the following file with any support request:
        npm ERR!     /built_app/programs/server/npm-debug.log

        ----------------------------------------------------------------------------

C:\Programs\contract\myappsupload\.deploy>
</code>```

This is the mup.js file:

```<code>module.exports = {
  servers: {
    one: {
      // TODO: set host address, username, and authentication method
      host: 'xxx.xxx.xx.xx',
      username: 'root',
      // pem: './path/to/pem'
       password: 'xxxxxxxxxxxxxxxx'
      // or neither for authenticate from ssh-agent
    }
  },

  app: {
    // TODO: change app name and path
    name: 'schoolapps',
    path: '../',

    servers: {
      one: {},
    },

    buildOptions: {
      serverOnly: true,
    },

    env: {
      // TODO: Change to your app's url
      // If you are using ssl, it needs to start with https://
      ROOT_URL: 'http://schoolapps.com',
      MONGO_URL: 'mongodb://localhost/meteor',
    },

    // ssl: { // (optional)
    //   // Enables let's encrypt (optional)
    //   autogenerate: {
    //     email: 'email.address@domain.com',
    //     // comma separated list of domains
    //     domains: 'website.com,www.website.com'
    //   }
    // },

    docker: {
      // change to 'kadirahq/meteord' if your app is using Meteor 1.3 or older
      image: 'abernix/meteord:base',

      args: [
        //'--link=myCustomMongoDB:myCustomMongoDB', // linking example
        '--memory-reservation 300M' // memory reservation example
      ],
    },

    // Show progress bar while uploading bundle to server
    // You might need to disable it on CI servers
    enableUploadProgressBar: true,
    deployCheckWaitTime: 150
  },

  mongo: {
    version: '3.4.1',
    servers: {
      one: {}
    }
  }
};
</code>```

答:
I do not know if it is still relevant, but maybe my answer will help someone else dealing with the same problem.

The task "Prepare bundle" was introduced in the version 1.3.0 of Meteor Up (see release notes):

After the bundle is uploaded to each server, a new task is run called "Prepare bundle". It installs the Meteor npm dependencies, rebuilds native modules, and stores the result in a docker image. This has a few benefits:

The time in meteor.deployCheckWaitTime no longer needs to include the time to install npm dependencies

When installing dependencies fails, it does not continuously restart until meteor.deployCheckWaitTime expires, and running with --verbose shows the full logs from npm install

Dependencies are only installed once during each deploy. This means that mup start, mup restart, and mup reconfig are all much faster.

From the version 1.3.1 this task can be disabled by adding the option app.docker.prepareBundle in mup.js and setting it to false. I dealt with the same error a few weeks ago and with this workaround I was able to deploy my application to DigitalOcean.

Body:
I don't know why I'm getting this error. Meteor-up is a brilliant. Whenever I run the deploy command it gets to a time and terminates. Could it be that a timeout has been set for the server to finish uploading the files?

C:\Programs\contract\schoolapps\.deploy>mup.cmd deploy --cached-build

   ┌─────────────────────────────────────┐
   │                                     │
   │   update available 1.3.2 => 1.3.3   │
   │     To update, run npm i -g mup     │
   │                                     │
   └─────────────────────────────────────┘

Not building app. Using build from previous deploy at
C:\Users\Kehinde\AppData\Local\Temp\mup-meteor-58e876b4-e682-4ecf-9d41-168fa46a5b19

Started TaskList: Pushing Meteor App
[xxx.xxx.xx.xx] - Pushing Meteor App Bundle to The Server
[===============                        ] 41% 630.4sevents.js:160
      throw er; // Unhandled 'error' event
      ^

Error: write ECONNRESET
    at exports._errnoException (util.js:1020:11)
    at WriteWrap.afterWrite (net.js:800:14)

C:\Programs\contract\schoolapps\.deploy>

After the upload was successful I got this error:

[xxx.xxx.xx.xx] x Prepare Bundle: FAILED

        -----------------------------------STDERR-----------------------------------
        Error response from daemon: No such container: myappsupload
        The command '/bin/sh -c cd  /built_app/programs/server &&     npm install --unsafe-perm' returned a non-zero code: 1
        Error response from daemon: No such container: myappsupload
        Error: failed to start containers: myappsupload
        -----------------------------------STDOUT-----------------------------------
        mnpm ERR! meteor-dev-bundle@0.0.0 install: `node npm-rebuild.js`
        npm ERR! Exit status 254
        npm ERR!
        npm ERR! Failed at the meteor-dev-bundle@0.0.0 install script 'node npm-rebuild.js'.
        npm ERR! Make sure you have the latest version of node.js and npm installed.
        npm ERR! If you do, this is most likely a problem with the meteor-dev-bundle package,
        npm ERR! not with npm itself.
        npm ERR! Tell the author that this fails on your system:
        npm ERR!     node npm-rebuild.js
        npm ERR! You can get information on how to open an issue for this project with:
        npm ERR!     npm bugs meteor-dev-bundle
        npm ERR! Or if that isn't available, you can get their info via:
        npm ERR!     npm owner ls meteor-dev-bundle
        npm ERR! There is likely additional logging output above.

        npm ERR! Please include the following file with any support request:
        npm ERR!     /built_app/programs/server/npm-debug.log

        ----------------------------------------------------------------------------

C:\Programs\contract\myappsupload\.deploy>

This is the mup.js file:

module.exports = {
  servers: {
    one: {
      // TODO: set host address, username, and authentication method
      host: 'xxx.xxx.xx.xx',
      username: 'root',
      // pem: './path/to/pem'
       password: 'xxxxxxxxxxxxxxxx'
      // or neither for authenticate from ssh-agent
    }
  },

  app: {
    // TODO: change app name and path
    name: 'schoolapps',
    path: '../',

    servers: {
      one: {},
    },

    buildOptions: {
      serverOnly: true,
    },

    env: {
      // TODO: Change to your app's url
      // If you are using ssl, it needs to start with https://
      ROOT_URL: 'http://schoolapps.com',
      MONGO_URL: 'mongodb://localhost/meteor',
    },

    // ssl: { // (optional)
    //   // Enables let's encrypt (optional)
    //   autogenerate: {
    //     email: 'email.address@domain.com',
    //     // comma separated list of domains
    //     domains: 'website.com,www.website.com'
    //   }
    // },

    docker: {
      // change to 'kadirahq/meteord' if your app is using Meteor 1.3 or older
      image: 'abernix/meteord:base',

      args: [
        //'--link=myCustomMongoDB:myCustomMongoDB', // linking example
        '--memory-reservation 300M' // memory reservation example
      ],
    },

    // Show progress bar while uploading bundle to server
    // You might need to disable it on CI servers
    enableUploadProgressBar: true,
    deployCheckWaitTime: 150
  },

  mongo: {
    version: '3.4.1',
    servers: {
      one: {}
    }
  }
};


问:
Pivot For Dynamic Column Value
May Some One Please help me how to get the below output.
SQL SERVER 2008

```<code>CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material'
</code>```

result for each Generic Name , Design, Material,other, Power and TYPE as Value of the column under Column Name as Desc1, Desc2....DescN

```<code>**Generic Name    DESC1   ,DESC2  ,DESC2, DESC4
RESISTOR        POWER   , Type    DESIGN, Material**
</code>```

答:
Try the following Answer, Hope it helps you:

```<code>CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT INTO #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material'

SELECT MAX(CASE WHEN RN=1 THEN [Generic Name] END)[Generic Name]
    ,MAX(CASE WHEN RN=1 THEN [Description] END)DESC1
    ,MAX(CASE WHEN RN=2 THEN [Description] END)DESC2
    ,MAX(CASE WHEN RN=3 THEN [Description] END)DESC3
    ,MAX(CASE WHEN RN=4 THEN [Description] END)DESC4
FROM(
    SELECT *,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))RN from #TABLE
    )D

DROP TABLE #TABLE
</code>```

Result:

```<code>Generic Name    DESC1   DESC2   DESC3   DESC4
RESISTOR        POWER   Type    DESIGN  Material
</code>```

Title: Pivot For Dynamic Column Value

Body:
May Some One Please help me how to get the below output.
SQL SERVER 2008

CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material'

result for each Generic Name , Design, Material,other, Power and TYPE as Value of the column under Column Name as Desc1, Desc2....DescN

**Generic Name    DESC1   ,DESC2  ,DESC2, DESC4
RESISTOR        POWER   , Type    DESIGN, Material**

Body:
Try the following Answer, Hope it helps you:

CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT INTO #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material'

SELECT MAX(CASE WHEN RN=1 THEN [Generic Name] END)[Generic Name]
    ,MAX(CASE WHEN RN=1 THEN [Description] END)DESC1
    ,MAX(CASE WHEN RN=2 THEN [Description] END)DESC2
    ,MAX(CASE WHEN RN=3 THEN [Description] END)DESC3
    ,MAX(CASE WHEN RN=4 THEN [Description] END)DESC4
FROM(
    SELECT *,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))RN from #TABLE
    )D

DROP TABLE #TABLE

Result:

Generic Name    DESC1   DESC2   DESC3   DESC4
RESISTOR        POWER   Type    DESIGN  Material


问:
Why so much memory?
I have a 1000x1500 pixel bitmap of which I want to make a mutable copy in Android.

When I run the following code...

```<code>// int width = original.getWidth(); // 1000px
// int height = original.getHeight(); // 1500px
final Bitmap result = original.copy(original.getConfig(), true);
original.recycle();
</code>```

...I get an OutOfMemoryError on the copy line:

```<code>java.lang.OutOfMemoryError: bitmap size exceeds VM budget
ERROR/GraphicsJNI(419): VM won't let us allocate 6000000 bytes
</code>```

Why does the copy instruction need 6MB (!) for a 1000x1500 pixel bitmap?

How can I create a mutable bitmap from a non-mutable one in more memory-efficient way?

Edit

BitmapFactory returns inmutable bitmaps. Apparently, the only way of creating a mutable bitmap from an immutable one is to copy it into a new mutable bitmap. In the case of a 1000x1500 bitmap, this apparently requires 12MB (1000x1500x4x2), which causes an OutOfMemoryError in most Android devices.

Is this problem unsolvable in Android then?

答:
To answer your first question:

1000*1500*32/8=6000000

(32 bits/pixel for color information)

To answer your second question: you need to reduce the size of the image, either by processing it in chunks, or be reducing the resolution or color depth.

Title: Why so much memory?

Body:
I have a 1000x1500 pixel bitmap of which I want to make a mutable copy in Android.

When I run the following code...

// int width = original.getWidth(); // 1000px
// int height = original.getHeight(); // 1500px
final Bitmap result = original.copy(original.getConfig(), true);
original.recycle();

...I get an OutOfMemoryError on the copy line:

java.lang.OutOfMemoryError: bitmap size exceeds VM budget
ERROR/GraphicsJNI(419): VM won't let us allocate 6000000 bytes

Why does the copy instruction need 6MB (!) for a 1000x1500 pixel bitmap?

How can I create a mutable bitmap from a non-mutable one in more memory-efficient way?

Edit

BitmapFactory returns inmutable bitmaps. Apparently, the only way of creating a mutable bitmap from an immutable one is to copy it into a new mutable bitmap. In the case of a 1000x1500 bitmap, this apparently requires 12MB (1000x1500x4x2), which causes an OutOfMemoryError in most Android devices.

Is this problem unsolvable in Android then?


问:
How to change the animation direction of ViewController on PopViewController
Is it possible to change the Direction of ViewContoller Pop animation.

Right now when we push VC at the time it shows animation Slide Left-to-Right and on Pop Right-to-Left.

But i want animation Slide Left-to-Right on Pop VC.

I have tried to use UIViewAnimationTransition.

```<code>[UIView  beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.75];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
[UIView commitAnimations];

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelay:0.375];
[self.navigationController popViewControllerAnimated:NO];
[UIView commitAnimations];
</code>```

But it doesn't have the animation i need which is Slide Left-to-Right. This is the animation i get

```<code>typedef enum {
   UIViewAnimationTransitionNone,
   UIViewAnimationTransitionFlipFromLeft,
   UIViewAnimationTransitionFlipFromRight,
   UIViewAnimationTransitionCurlUp,
   UIViewAnimationTransitionCurlDown,
} UIViewAnimationTransition;
</code>```

答:
```<code>let story = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController")  as! SecondViewController

    UIView.beginAnimations("", context: nil)
    UIView.setAnimationDuration(1.0)
    UIView.setAnimationCurve(UIViewAnimationCurve.easeInOut)
    UIView.setAnimationTransition(UIViewAnimationTransition.flipFromRight, for: (self.navigationController?.view)!, cache: false)
    self.navigationController?.pushViewController(story, animated: true)
    UIView.commitAnimations()
</code>```

Body:
Is it possible to change the Direction of ViewContoller Pop animation.

Right now when we push VC at the time it shows animation Slide Left-to-Right and on Pop Right-to-Left.

But i want animation Slide Left-to-Right on Pop VC.

I have tried to use UIViewAnimationTransition.

[UIView  beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.75];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
[UIView commitAnimations];

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDelay:0.375];
[self.navigationController popViewControllerAnimated:NO];
[UIView commitAnimations];

But it doesn't have the animation i need which is Slide Left-to-Right. This is the animation i get

typedef enum {
   UIViewAnimationTransitionNone,
   UIViewAnimationTransitionFlipFromLeft,
   UIViewAnimationTransitionFlipFromRight,
   UIViewAnimationTransitionCurlUp,
   UIViewAnimationTransitionCurlDown,
} UIViewAnimationTransition;


问:
Photo rotated from camera (SAMSUNG device)
i hate this company. All them devices have a lot of bugs. Ok question :
Im trying to fix stupid problem  (which as i know exist more than 5 years)
Its photo taken from camera - rotated on 90 degree.
I have two devices :

```<code>  Nexus 5p and Samsung j2
  Nexus - work perfect. Everything fine.
  Samsung - photo rotated
</code>```

For example :

```<code>Photo size - nexus : Portrate : width 1000, height 1900.  Landscape :
width 1900 , height 1000
</code>```

Lets see on samsung device :

```<code>Photo size  - Portrate: width 1900(?????) height - 1000(????)
rotate to landscape : width 1900 height 1000
</code>```

After some testing : if make photo in landscape mode on samsung device - than everything ok. Photo not rotated

If make photo in PORTRATE - photo rotated on 90 degree. (BUT size of photo as on landscape (HOW ITS POSSIBLE) ?

Anyone know how to fix this stupid bug ? Maybe any can tell me how to detect orientation for camera ? Im using IntentActivity for photo :

```<code>String _path = Environment.getExternalStorageDirectory()
                                    + File.separator + "camera_img.jpg";
                            File file = new File(_path);
                            Uri outputFileUri = Uri.fromFile(file);
                            Intent intent = new Intent(
                                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                            startActivityForResult(intent, CAMERA_REQUEST);
</code>```

Any help  ?
I also add a checker , if its samsung device than rotate. But rotation good only if we create photo in portrate mode. In landscape everything fine. So i need somehow detected in which orientation photo was created. Any one know ?

答:
Are you taking the picture yourself with the camera API ?
If so you can get the orientation with:
Camera1 API :

```<code>CameraInfo cameraInfo = new CameraInfo();
int sensorOrientation = cameraInfo.orientation;
</code>```

Camera2 API :

```<code>CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics characteristics = mCameraCharacteristics;
int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
</code>```

Body:
i hate this company. All them devices have a lot of bugs. Ok question :
Im trying to fix stupid problem  (which as i know exist more than 5 years)
Its photo taken from camera - rotated on 90 degree.
I have two devices :

  Nexus 5p and Samsung j2
  Nexus - work perfect. Everything fine.
  Samsung - photo rotated

For example :

Photo size - nexus : Portrate : width 1000, height 1900.  Landscape :
width 1900 , height 1000

Lets see on samsung device :

Photo size  - Portrate: width 1900(?????) height - 1000(????)
rotate to landscape : width 1900 height 1000

After some testing : if make photo in landscape mode on samsung device - than everything ok. Photo not rotated

If make photo in PORTRATE - photo rotated on 90 degree. (BUT size of photo as on landscape (HOW ITS POSSIBLE) ?

Anyone know how to fix this stupid bug ? Maybe any can tell me how to detect orientation for camera ? Im using IntentActivity for photo :

String _path = Environment.getExternalStorageDirectory()
                                    + File.separator + "camera_img.jpg";
                            File file = new File(_path);
                            Uri outputFileUri = Uri.fromFile(file);
                            Intent intent = new Intent(
                                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                            startActivityForResult(intent, CAMERA_REQUEST);

Any help  ?
I also add a checker , if its samsung device than rotate. But rotation good only if we create photo in portrate mode. In landscape everything fine. So i need somehow detected in which orientation photo was created. Any one know ?

Body:
Are you taking the picture yourself with the camera API ?
If so you can get the orientation with:
Camera1 API :

CameraInfo cameraInfo = new CameraInfo();
int sensorOrientation = cameraInfo.orientation;

Camera2 API :

CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics characteristics = mCameraCharacteristics;
int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);


问:
How to list all contacts with Microsoft Graph?
I am experimenting with the Microsoft Graph API and I set up a project with the QuickStarts on the Microsoft developers site.

I'm currently having problems when trying to list all email contacts associated with the logged account.

My problem seems to reside on how I'm requesting and passing the information to ViewBag as it throws a NullReference exceptions even with the proper front-end listing.

Here is the relevant code:

HomeController.cs

public async Task<ActionResult> GetMyContacts()
{
    try
    {
        // Init GraphServiceClient
        GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
        var contacts = await graphService.GetMyEmailContacts(graphClient);
        ViewBag.Contacts = contacts;

        return View("Graph");
    }
    catch (ServiceException se)
    {
        if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
        return RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + se.Error.Message });
    }
}
```

<p>GraphService.cs</p>

<pre class="lang-cs prettyprint-override"><code>public async Task<IList<Contact>> GetMyEmailContacts(GraphServiceClient graphClient)
{
    User me = await graphClient.Me.Request().Select("mail,userPrincipalName").GetAsync();
    var contacts = me.Contacts;
    return contacts;
}
</code>```

Graph.cshtml

@ViewBag.Contacts```
</div>
<h2>TEST GET CONTACTS</h2>
<div class="col-sm-12">
<p>@Html.Raw(ViewBag.Contacts)</p>
</div>
</code>```

What am I missing here?

答:
In your view, you have to cast it back to the original type. ViewBag is a C# 4 dynamic type. Returned entities are also dynamic unless cast.

```<code>var contactList = ViewBag.Contacts as IEnumerable<Contact>;
</code>```

If you want to display the whole list, it's as simple as this:

```<code>@foreach (var contact in contactList)
{
    <li>@contact</li>
}
</code>```

Body:
I am experimenting with the Microsoft Graph API and I set up a project with the QuickStarts on the Microsoft developers site.

I'm currently having problems when trying to list all email contacts associated with the logged account.

My problem seems to reside on how I'm requesting and passing the information to ViewBag as it throws a NullReference exceptions even with the proper front-end listing.

Here is the relevant code:

HomeController.cs

public async Task<ActionResult> GetMyContacts()
{
    try
    {
        // Init GraphServiceClient
        GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
        var contacts = await graphService.GetMyEmailContacts(graphClient);
        ViewBag.Contacts = contacts;

        return View("Graph");
    }
    catch (ServiceException se)
    {
        if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
        return RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + se.Error.Message });
    }
}

GraphService.cs

public async Task<IList<Contact>> GetMyEmailContacts(GraphServiceClient graphClient)
{
    User me = await graphClient.Me.Request().Select("mail,userPrincipalName").GetAsync();
    var contacts = me.Contacts;
    return contacts;
}

Graph.cshtml

@ViewBag.Contacts

TEST GET CONTACTS

@Html.Raw(ViewBag.Contacts)

What am I missing here?

Body:
In your view, you have to cast it back to the original type. ViewBag is a C# 4 dynamic type. Returned entities are also dynamic unless cast.

var contactList = ViewBag.Contacts as IEnumerable<Contact>;

If you want to display the whole list, it's as simple as this:

@foreach (var contact in contactList)
{
    <li>@contact</li>
}


问:
How to get JSON object from another JSON object in swift 3
how can I get applicationStateJson in below code, I can parse the bellow JSON object from data but can not able to get applicationStateJson from it

```<code>{
applicationStateJson =     {
    "address_status" = 0;
    email = "xxxxxxxx;
    "email_status" = 0;
    "first_name" = xxx;
    "last_name" = "";
    "login_status" = 1;
    loginstype = "<null>";
    mobile = xxxxxx;
    "mobile_status" = 1;
    notifications =         (
    );
    "notifications_size" = 0;
    "otp_status" = 3;
    "profile_id" = "<null>";
    "profile_name" = "virtual_recruiter";
    "user_id" = 454;
    "user_status" = 1;
    "virtual_recruiter_id" =xxx;
};
"error_msg" = "<null>";
status = "<null>";
}
</code>```

code as

```<code>do {
 let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(json)
let applicationStateJson = try json["applicationStateJson"]
} catch { print(error.localizedDescription) }
</code>```

答:
Try with below code

First you need to change in below line, its Dictionary<String, Any> not an AnyObject

```<code>let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, Any>
</code>```

And then get applicationStateJson  by below code

```<code>if let appJson = json["applicationStateJson"] as? Dictionary<String, Any> {
    print(appJson)
    print("Email : \(appJson["email"] as? String ?? "Email not found")") // For get email
}
</code>```

Body:
how can I get applicationStateJson in below code, I can parse the bellow JSON object from data but can not able to get applicationStateJson from it

{
applicationStateJson =     {
    "address_status" = 0;
    email = "xxxxxxxx;
    "email_status" = 0;
    "first_name" = xxx;
    "last_name" = "";
    "login_status" = 1;
    loginstype = "<null>";
    mobile = xxxxxx;
    "mobile_status" = 1;
    notifications =         (
    );
    "notifications_size" = 0;
    "otp_status" = 3;
    "profile_id" = "<null>";
    "profile_name" = "virtual_recruiter";
    "user_id" = 454;
    "user_status" = 1;
    "virtual_recruiter_id" =xxx;
};
"error_msg" = "<null>";
status = "<null>";
}

code as

do {
 let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(json)
let applicationStateJson = try json["applicationStateJson"]
} catch { print(error.localizedDescription) }

Body:
Try with below code

First you need to change in below line, its Dictionary<String, Any> not an AnyObject

let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, Any>

And then get applicationStateJson  by below code

if let appJson = json["applicationStateJson"] as? Dictionary<String, Any> {
    print(appJson)
    print("Email : \(appJson["email"] as? String ?? "Email not found")") // For get email
}


问:
Do I need to delete an static std::map?
In some classes I have an static std::map with pointers inside. My question is if I need to delete at the end of the program or this memory is automatically freed. My concern is if the pointers stored inside are correctly deleted through our destructors when std::map is deleted.

Thanks.

答: If you have a map of pointers, then the answer is 'no', your destructors will not be called, but 'yes', the memory will be freed at the end of process execution. All memory allocated by a process is always freed by the Operating System when a process exits (even if it crashes), but destructors might not be called.</p>

Title: Do I need to delete an static std::map?


问:
IFile to IResource
How can I get an IResource from an IFile or from an absolute path?

I tried with:

```<code>IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
resource = root.findMember(file.getAbsolutePath());
</code>```

But I get a null value.

答: IFile extend IResource, or with other words an IFile is an IResource.

Title: IFile to IResource

Body:
How can I get an IResource from an IFile or from an absolute path?

I tried with:

IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
resource = root.findMember(file.getAbsolutePath());

But I get a null value.


问:
How to detect the TIP of the triangle in image processing with OpenCV?
I am currently working on a project which is image processing with OpenCV and one of its function is to detect the tip of the triangle. I want to detect ONLY the tip of the triangle, how can I detect and what algorithm is the best approach for this? Here is the sample picture of the tip of the triangle</p>

答:
You could try line detection in openCV (https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html) to get the function representations of the edges of the triangle and search for the intersections of these lines.

Once you find the intersections you can calculate the angle between the lines and use a threshold angle value to choose which intersection is the tip you want.


问:
Get list of installed app name in iPhone
How can I get my installed app names for my project. ?
Is it possible to access downloaded app in my newly created app ?
I want to create a app like app locking .</p>

答: You can't access Other third-party apps or System Apps features or permissions via your app. There is no public API available to do so.</p>


问:
Applying a function on sorted array
Taken from the google interview question here

Suppose that you have a sorted array of integers (positive or negative). You want to apply a function of the form f(x) = a * x^2 + b * x + c to each element x of the array such that the resulting array is still sorted. Implement this in Java or C++. The input are the initial sorted array and the function parameters (a, b and c).

Do you think we can do it in-place with less than O(n log(n)) time where n is the array size (e.g. apply a function to each element of an array, after that sort the array)?

答:
```<code>static void sortArray(int arr[], int n, int A, int B, int C)
    {
       // Apply equation on all elements
        for (int i = 0; i < n; i++)
            arr[i] = A*arr[i]*arr[i] + B*arr[i] + C;

        // Find maximum element in resultant array
        int index=-1;
        int maximum = -999999;
        for (int i = 0; i< n; i++)
        {
            if (maximum < arr[i])
            {
                index = i;
                maximum = arr[i];
            }
        }

        // Use maximum element as a break point
        // and merge both subarrays usin simple
        // merge function of merge sort
        int i = 0, j = n-1;
        int[] new_arr = new int[n];
        int k = 0;
        while (i < index && j > index)
        {
            if (arr[i] < arr[j])
                new_arr[k++] = arr[i++];
            else
                new_arr[k++] = arr[j--];
        }

        // Merge remaining elements
        while (i < index)
            new_arr[k++] = arr[i++];
        while (j > index)
            new_arr[k++] = arr[j--];

        new_arr[n-1] = maximum;

        // Modify original array
        for (int p = 0; p < n ; p++)
            arr[p] = new_arr[p];
    }
</code>```

Title: Applying a function on sorted array


问:
Javascript loop through Json
Trying to figure out how to loop through users in the following Json response:

```<code>{ "id": 23, "users": { "26": "user 333", "27": "user 222" } }
</code>```

A normal for-loop is not working, i.e for(i = 0; i <object.users.length; i++). So I started thinking maybe it's not a normal array because there are no [] brackets. But even the simplest operation fails: alert(object.users[0]).

I need help figuring out how I can loop through each user and get both key and value (key:value).

答:
var json = { "id": 23, "users": { "26": "user 333", "27": "user 222" } } ;
for(var ob in json['users']){
 console.log(ob,json['users'][ob]);
}```

Use for- in loop to loop through objects.

Title: Javascript loop through Json

Body:
Trying to figure out how to loop through users in the following Json response:

{ "id": 23, "users": { "26": "user 333", "27": "user 222" } }

A normal for-loop is not working, i.e for(i = 0; i <object.users.length; i++). So I started thinking maybe it's not a normal array because there are no [] brackets. But even the simplest operation fails: alert(object.users[0]).

I need help figuring out how I can loop through each user and get both key and value (key:value).

Body:
var json = { "id": 23, "users": { "26": "user 333", "27": "user 222" } } ;
for(var ob in json['users']){
 console.log(ob,json['users'][ob]);
}

Use for- in loop to loop through objects.


答: The memory is "automatically freed", in the sense that the entire process memory is freed, but the destructors of the objects pointed to will not be called. This can cause a resource leak, if you use RAII.</p>

Title: Do I need to delete an static std::map?

Body:
In some classes I have an static std::map with pointers inside. My question is if I need to delete at the end of the program or this memory is automatically freed. My concern is if the pointers stored inside are correctly deleted through our destructors when std::map is deleted.

Thanks.


问:
catch IndexOutOfBoundsException Exception
I'm trying to catch made up IndexOutOfBoundsException  error in catch block. But every time its returning -1 and not going into catch block

May I know please why its happening ? I want to reach to catch block.

```<code>  public class Mars {

    public int Setname(String Input) {

        int output = 0;

        try {
            output = Input.indexOf("L");
            System.out.println("Error:" + Input.indexOf("L"));

            if (output == -1){

                throw new IndexOutOfBoundsException();
            }

        }

        catch (IndexOutOfBoundsException e) {

            System.out.println("Error:2" + e.getStackTrace());
        }

        return output;

    }

    public static void main(String[] args) {

        Mars O = new Mars();
        O.Setname("London");

    }

}
</code>```

Second thing is: When we write IndexOutOfBoundsException e in catch block, its creating an instance of IndexOutOfBoundsException class ?Am I right ?

So why we can't write like in below manner ? It could be a really silly question, but just for curiosity I want to know.

```<code>catch(IndexOutOfBoundsException e = new IndexOutOfBoundsException())
</code>```

答:
For First Thing Mohamed Said Benmousa's answer is correct

For Second Thing

```<code>IndexOutOfBoundsException e
</code>```

This doesn't create an instance . Its just a reference which is going to point on  IndexOutOfBoundsException object if thrown. Like you passed argument when calling your method.

Body:
I'm trying to catch made up IndexOutOfBoundsException  error in catch block. But every time its returning -1 and not going into catch block

May I know please why its happening ? I want to reach to catch block.

  public class Mars {

    public int Setname(String Input) {

        int output = 0;

        try {
            output = Input.indexOf("L");
            System.out.println("Error:" + Input.indexOf("L"));

            if (output == -1){

                throw new IndexOutOfBoundsException();
            }

        }

        catch (IndexOutOfBoundsException e) {

            System.out.println("Error:2" + e.getStackTrace());
        }

        return output;

    }

    public static void main(String[] args) {

        Mars O = new Mars();
        O.Setname("London");

    }

}

Second thing is: When we write IndexOutOfBoundsException e in catch block, its creating an instance of IndexOutOfBoundsException class ?Am I right ?

So why we can't write like in below manner ? It could be a really silly question, but just for curiosity I want to know.

catch(IndexOutOfBoundsException e = new IndexOutOfBoundsException())

Body:
For First Thing Mohamed Said Benmousa's answer is correct

For Second Thing

IndexOutOfBoundsException e

This doesn't create an instance . Its just a reference which is going to point on  IndexOutOfBoundsException object if thrown. Like you passed argument when calling your method.


问:
Pass an input value into a ngComponentOutlet created component?

I have a component like:

@Component({
  selector: 'app-item',
  template: '
{{title}}
'
})
export class TitleComponent {
  @Input() title:string;
}

@Component({
  selector: 'app-foo',
  template: '<ng-container *ngComponentOutlet="outlet"></ng-container>'
})
export class FooComponent {
  outlet = TitleComponent;
}
```

How do you pass input title value on the ng-container for the TitleComponent or how can I set this value?

答:
An example solution is shown in the ngComponentOutlet documentation, specifically the second example with the @Injectable, as titusfx also mentioned.

Here is what it would look like with your use case:

@Injectable()
class Info {
  title = 'a little hacky';
}

@Component({
  selector: 'app-item',
  template: '
{{info.title}}
'
})
export class TitleComponent {
  // @Input() title:string;
  constructor(public info: Info){ }
}

@Component({
  selector: 'app-foo',
  template: '<ng-container *ngComponentOutlet="outlet; injector: myInjector"></ng-container>'
})
export class FooComponent {
  outlet = TitleComponent;
  myInjector: Injector;
  constructor(injector: Injector){
    this.myInjector = ReflectiveInjector.resolveAndCreate([Info], injector);
  }
}
```

Body:
I have a component like:

@Component({
  selector: 'app-item',
  template: '
{{title}}
'
})
export class TitleComponent {
  @Input() title:string;
}

@Component({
  selector: 'app-foo',
  template: '<ng-container *ngComponentOutlet="outlet"></ng-container>'
})
export class FooComponent {
  outlet = TitleComponent;
}

How do you pass input title value on the ng-container for the TitleComponent or how can I set this value?

Body:
An example solution is shown in the ngComponentOutlet documentation, specifically the second example with the @Injectable, as titusfx also mentioned.

Here is what it would look like with your use case:

@Injectable()
class Info {
  title = 'a little hacky';
}

@Component({
  selector: 'app-item',
  template: '<p>{{info.title}}</p>'
})
export class TitleComponent {
  // @Input() title:string;
  constructor(public info: Info){ }
}

@Component({
  selector: 'app-foo',
  template: '<ng-container *ngComponentOutlet="outlet; injector: myInjector"></ng-container>'
})
export class FooComponent {
  outlet = TitleComponent;
  myInjector: Injector;
  constructor(injector: Injector){
    this.myInjector = ReflectiveInjector.resolveAndCreate([Info], injector);
  }
}


问:
System.Net.Http or dependency missing on release, caused by Google Drive API
I cannot figure this one out, on a release of a program that uploads a file to Google Drive through V3 of the API, an exception, as follows, is throw:

FileNotFoundException: Could not load file or assembly
  'System.Net.Http, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
  system cannot find the file specified.

This does not happen in debug mode but in release mode and published versions. I have removed, then updated, then re added the system.Net.Http references to the project. I have updated the Google API, and have changed a number of settings and references to no avail.

I have no idea what is missing or how to replace it. I know it happens when I call the connection method of the uploading class, but the exception is thrown after the code exits this method.

```<code>    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net;
    using System.Net.Http;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Drive.v3;
    using Google.Apis.Drive.v3.Data;
    using Google.Apis.Services;
    using Google.Apis.Util.Store;
    using System.IO;
    using System.Threading;
    //using Google.Apis.Vision.v1;
    using System.Diagnostics;
    using System.Runtime.InteropServices;

    namespace Rohl
    {
        public class DriveManager
        {
            static string[] Scopes = { DriveService.Scope.Drive};
            static string ApplicationName = "Rohl - Drive Services";
            UserCredential credential;

            public void connector()
            {
                using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;

                    Properties.Settings.Default.DebugWrite.Add(DateTime.Now.ToString("hh.mm.ss.ff") + " CREDENTIALS SAVED TO - " + credPath);
                }

                service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

            }
}
}
</code>```

What am I missing that could cause the program to not be able to find the assembly?

答:
Had exactly the same error on my project. I figured out that after the release the System.Net.Http.dll was missing in the folder where the .exe lies. Try to copy it from the bin\Debug-folder and see if this helps.
Greetings.</p>

Body:
I cannot figure this one out, on a release of a program that uploads a file to Google Drive through V3 of the API, an exception, as follows, is throw:

FileNotFoundException: Could not load file or assembly
  'System.Net.Http, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
  system cannot find the file specified.

This does not happen in debug mode but in release mode and published versions. I have removed, then updated, then re added the system.Net.Http references to the project. I have updated the Google API, and have changed a number of settings and references to no avail.

I have no idea what is missing or how to replace it. I know it happens when I call the connection method of the uploading class, but the exception is thrown after the code exits this method.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net;
    using System.Net.Http;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Drive.v3;
    using Google.Apis.Drive.v3.Data;
    using Google.Apis.Services;
    using Google.Apis.Util.Store;
    using System.IO;
    using System.Threading;
    //using Google.Apis.Vision.v1;
    using System.Diagnostics;
    using System.Runtime.InteropServices;

    namespace Rohl
    {
        public class DriveManager
        {
            static string[] Scopes = { DriveService.Scope.Drive};
            static string ApplicationName = "Rohl - Drive Services";
            UserCredential credential;

            public void connector()
            {
                using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;

                    Properties.Settings.Default.DebugWrite.Add(DateTime.Now.ToString("hh.mm.ss.ff") + " CREDENTIALS SAVED TO - " + credPath);
                }

                service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

            }
}
}

What am I missing that could cause the program to not be able to find the assembly?


问:
Add confusion matrix in naive bayes python code
I would like to ask how to add confusion matrix in naive bayes python code.
I got naive bayes code from
  naive bayes for iris data

i need some change to add confusion matrix.
i have separated code for confusion matrix but i  don't  know where to put this on my code, and i don't know what to replace ??? with what.

```<code>y_actu = pd.Series(???, name='Actual')
y_pred = pd.Series(???, name='Predicted')
df_confusion = pd.crosstab(y_actu, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True)

print df_confusion
</code>```

i'm sorry for my bad english.

答:
I would suggest you use sklearn's confusion_matrix function

```<code>from sklearn.metrics import  confusion_matrix

y_actu = pd.Series(???, name='Actual')
y_pred = pd.Series(???, name='Predicted')

confusionMatrix = confusion_matrix(y_actu, y_pred)
print(confusionMatrix)
</code>```

Documentation here!

Cheers!

Body:
I would like to ask how to add confusion matrix in naive bayes python code.
I got naive bayes code from
  naive bayes for iris data

i need some change to add confusion matrix.
i have separated code for confusion matrix but i  don't  know where to put this on my code, and i don't know what to replace ??? with what.

y_actu = pd.Series(???, name='Actual')
y_pred = pd.Series(???, name='Predicted')
df_confusion = pd.crosstab(y_actu, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True)

print df_confusion

i'm sorry for my bad english.

Body:
I would suggest you use sklearn's confusion_matrix function

from sklearn.metrics import  confusion_matrix

y_actu = pd.Series(???, name='Actual')
y_pred = pd.Series(???, name='Predicted')

confusionMatrix = confusion_matrix(y_actu, y_pred)
print(confusionMatrix)

Documentation here!

Cheers!


问:
Display database table in CodeIgniter
I am trying to display a table using CodeIgniter. I made a function to select all data from one table and display it using a foreach loop when the button is clicked. I am getting this error:

```<code>Fatal error: Call to undefined method CI_DB_mysql_driver::result() in C:\Xampp\htdocs\Auction\application\models\bidding_model.php on line 47
</code>```

This is my controller page:

```<code>public function viewauction()
{
    $this->load->model('bidding_model');
    $data['query'] = $this->bidding_model->viewauction();
    $this->load->view('auction_view', $data);
}
</code>```

This is the model:

```<code>function viewauction()
{
    $query =  $this->db->select('products');
    return $query->result();
}
</code>```

This is the view:

```<code><tbody>
<?php foreach($query as $row): ?>
<tr>
    <td><?php echo $row->product_id; ?></td>
    <td><?php echo $row->auction_id; ?></td>
    <td><?php echo $row->start_time; ?></td>
    <td><?php echo $row->end_time; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</code>```

答:
```<code>function viewauction()
{
    $this->db->select('*');
    $this->db->from('tablename');
    $query = $this->db->get();
    return $query->result();
}
</code>```

Above code will help you.

Title: Display database table in CodeIgniter

Body:
I am trying to display a table using CodeIgniter. I made a function to select all data from one table and display it using a foreach loop when the button is clicked. I am getting this error:

Fatal error: Call to undefined method CI_DB_mysql_driver::result() in C:\Xampp\htdocs\Auction\application\models\bidding_model.php on line 47

This is my controller page:

public function viewauction()
{
    $this->load->model('bidding_model');
    $data['query'] = $this->bidding_model->viewauction();
    $this->load->view('auction_view', $data);
}

This is the model:

function viewauction()
{
    $query =  $this->db->select('products');
    return $query->result();
}

This is the view:

<?php foreach($query as $row): ?>

    <?php echo $row->product_id; ?>
    <?php echo $row->auction_id; ?>
    <?php echo $row->start_time; ?>
    <?php echo $row->end_time; ?>

<?php endforeach; ?>

Body:
function viewauction()
{
    $this->db->select('*');
    $this->db->from('tablename');
    $query = $this->db->get();
    return $query->result();
}

Above code will help you.


问:
How to refresh opencart modification by code
I need to refresh modifications after install module.

```<code>public function install() {
    $this->load->controller('marketplace/modification/refresh');
}
</code>```

I tried this. Its worked but the page redirected to modification listing. How can i do without redirect. I am using opencart 3.

答:
If you don't want to edit modification.php or clone its refresh function, You can use this:

```<code>public function install(){
    $data['redirect'] = 'extension/extension/module';
    $this->load->controller('marketplace/modification/refresh', $data);
}
</code>```

Body:
I need to refresh modifications after install module.

public function install() {
    $this->load->controller('marketplace/modification/refresh');
}

I tried this. Its worked but the page redirected to modification listing. How can i do without redirect. I am using opencart 3.

Body:
If you don't want to edit modification.php or clone its refresh function, You can use this:

public function install(){
    $data['redirect'] = 'extension/extension/module';
    $this->load->controller('marketplace/modification/refresh', $data);
}


答:
You can do this -

var obj = { "id": 23, "users": { "26": "user 333", "27": "user 222" } };
for(var i in obj.users)
 console.log(i+': '+obj.users[i]);```

Title: Javascript loop through Json