text:
Q: turn double square brackets to single How can I remove the double square brackets of a numpy array to single square brackets like a list?
[[0, 3.49, 0, 4.55]]

desired output
[0,3.49,0,4.55]

I have searched through SO looking for numpy array to list , square brackets numpy, not being able to find an answer
to_list() only add commas among the values

A: Are you sure it was a numpy array?
I think just use
my_list[0]

to get the first element (in the first element is [0,3.49,0,4.55])

A: If they are coded as lists, you can just take the [0] element

A: I had this same problem and referencing [0] did not work (it would simply select the 1st element, in this case [0])
I was trying to setup a way to automate iterator "i" in code from here
https://www.datasklr.com/ols-least-squares-regression/interaction-effects-and-polynomials-in-multiple-linear-regression
so I tried
X_inter.iloc[:, np.array(pd.concat([pd.DataFrame(range(0,len(all_data.iloc[:,2:].columns))),pd.DataFrame(pd.Series(i))]).values)]

which would throw an error "Buffer has wrong number of dimensions (expected 1, got 2)"
My np.array would look like this
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

Found a solution here that worked
https://www.quora.com/How-can-I-drop-brackets-in-a-Python-list-in-order-to-go-from-1-2-3-to-1-2-3
test_list = np.array(pd.concat([pd.DataFrame(range(0,len(all_data.iloc[:,2:].columns))),pd.DataFrame(pd.Series(i))]).values)

flattened = []
for sublist in test_list:
    for val in sublist:
        flattened.append(val)

X_inter.iloc[:, flattened]


text:
Q: Set security for Process object in java Can some one tell how can I restrict System properties to be accessed through a process object? If I run the following piece of code through process object , can I throw security exceptions.
System.getProperty("user.home");

Please enlighten me about how to configure the securities for a process object.
In ProcessBuilder class document , in environment method it is written:

A system may not allow modifications to environment variables or may
  forbid certain variable names or values.

So please let me know how to forbid certain variable values.
Updated:
So suppose I am using a Java web application and giving the client side a platform to code. Then how to configure the java security separately for java web application and for client side application.(As I will never want to restrict the web application to get any property of System, whereas I must restrict client side to use these commands for application vulnerability)

A: Create your own security manager and check access for some properties
public class MySecurityManager extends SecurityManager {

@Override
public void checkPropertyAccess(String key) throws SecurityException  {
        if ( key != null && key.equals("some.forbidden_value") {
            throw new SecurityException("some message");
         }
         super.checkPropertyAccess( key );
    }
}

And somewhere else in your code attach your security manager:
System.setSecurityManager( new MySecurityManager() );

redpajama_set_name: RedPajamaStackExchange


text:
Q: not getting appropriate structure I have stored procedure like this:
CREATE PROCEDURE [dbo].[Poll_EDI834_5010]
AS
BEGIN
SELECT     Header.ST01,
           Line.PER04__CommunicationNumber ,
           (SELECT  Member_Ref.REF01_ReferenceIdentificationQualifier
            FROM    EDI834_5010_2000_RefLoop Member_Ref
            WHERE   Member_Ref.Id_Header = Header.BGN02__TransactionSetIdentifierCode
            AND     Member_Ref.Id_Loop2000 = Line.Member_Id
            FOR XML AUTO, ELEMENTS, TYPE),
           VLine.HD01_MaintenanceTypeCode,
           (SELECT  ClaimDTP.DTP01__DateTimeQualifier
            FROM    EDI834_5010_2300_DTPLoop ClaimDTP
            WHERE   ClaimDTP.Id_Header = Header.BGN02__TransactionSetIdentifierCode
            AND     ClaimDTP.Id_Loop2000 = Line.Member_Id
            AND     ClaimDTP.Id_Loop2300 = VLine.Id_Claim
            FOR XML AUTO, ELEMENTS, TYPE)
FROM       EDI834_5010_Header   Header
JOIN       EDI834_5010_2000     Line   ON Header.BGN02__TransactionSetIdentifierCode = Line.Header_Id
JOIN       EDI834_5010_2300Loop VLine  ON Header.BGN02__TransactionSetIdentifierCode = VLine.Id_Header_Id andVLine.Id_Loop2000=Line.Member_Id
FOR XML AUTO, ELEMENTS
END
GO

I am getting data structured like this:
<Header>
     <Line>
        <MemberRef> </MemberRef>
        <MemberRef> </MemberRef>
        <VLine>
           <Claim_DTP>  </Claim_DTP>
           <Claim_DTP>  </Claim_DTP>
         </VLine>
     </Line>
 </Header>

My problem is I want the data to look like this instead:
  <Header>
    <Line>
       <MemberRef> </MemberRef>
       <MemberRef> </MemberRef>
       <VLine>
         <Claim_DTP>  </Claim_DTP>
         <Claim_DTP>  </Claim_DTP>
      </VLine>
       <VLine>
         <Claim_DTP>  </Claim_DTP>
         <Claim_DTP>  </Claim_DTP>
       </VLine>
   </Line>
</Header>

Why are my VLine nodes not repeating? But when I remove subquery Member_Ref I am getting appropriate structure. But I need that subquery. Is there any way to achieve this structure?

A:         CREATE PROCEDURE [dbo].[Poll_EDI834_5010]
AS
BEGIN
        SELECT     Header.ST01,
        Line.PER04__CommunicationNumber ,
        (SELECT  Member_Ref.REF01_ReferenceIdentificationQualifier
         FROM    EDI834_5010_2000_RefLoop Member_Ref
         WHERE   Member_Ref.Id_Header = Header.BGN02__TransactionSetIdentifierCode
         AND     Member_Ref.Id_Loop2000 = Line.Member_Id
         FOR XML AUTO, ELEMENTS, TYPE),
        (SELECT  VLine.HD01_MaintenanceTypeCode,
        (SELECT  ClaimDTP.DTP01__DateTimeQualifier
          FROM    EDI834_5010_2300_DTPLoop ClaimDTP
          WHERE   ClaimDTP.Id_Header = Header.BGN02__TransactionSetIdentifierCode
          AND     ClaimDTP.Id_Loop2000 = Line.Member_Id
          AND     ClaimDTP.Id_Loop2300 = VLine.Id_Claim
          FOR XML AUTO, ELEMENTS, TYPE)
          FROM EDI834_5010_2300Loop VLine
          Where  Header.BGN02__TransactionSetIdentifierCode = VLine.Id_Header_Id andVLine.Id_Loop2000=Line.Member_Id

          FOR XML AUTO, ELEMENTS, TYPE)
FROM       EDI834_5010_Header   Header
JOIN       EDI834_5010_2000     Line   ON Header.BGN02__TransactionSetIdentifierCode = Line.Header_Id
   FOR XML AUTO, ELEMENTS
END
GO

A: not sure about this...
CREATE PROCEDURE [dbo].[Poll_EDI834_5010]
AS
BEGIN
SELECT     Header.ST01,
           Line.PER04__CommunicationNumber ,
           (SELECT  Member_Ref.REF01_ReferenceIdentificationQualifier
            FROM    EDI834_5010_2000_RefLoop Member_Ref
            WHERE   Member_Ref.Id_Header = Header.BGN02__TransactionSetIdentifierCode
            AND     Member_Ref.Id_Loop2000 = Line.Member_Id
            FOR XML AUTO, ELEMENTS, TYPE),
           (SELECT  VLine.HD01_MaintenanceTypeCode,
               (SELECT  ClaimDTP.DTP01__DateTimeQualifier
                FROM    EDI834_5010_2300_DTPLoop ClaimDTP
                WHERE   ClaimDTP.Id_Header = Header.BGN02__TransactionSetIdentifierCode
                AND     ClaimDTP.Id_Loop2000 = Line.Member_Id
                AND     ClaimDTP.Id_Loop2300 = VLine.Id_Claim
                FOR XML AUTO, ELEMENTS, TYPE)
            FOR XML AUTO, ELEMENTS, TYPE)
FROM       EDI834_5010_Header   Header
JOIN       EDI834_5010_2000     Line   ON Header.BGN02__TransactionSetIdentifierCode = Line.Header_Id
JOIN       EDI834_5010_2300Loop VLine  ON Header.BGN02__TransactionSetIdentifierCode = VLine.Id_Header_Id andVLine.Id_Loop2000=Line.Member_Id
FOR XML AUTO, ELEMENTS
END
GO


text: Q: Create bootable SD card with Rufus When create bootable SD card with Rufus utility, should be always selected formatting card (by checking "Quick format" box), or it's possible write linux OS image (.img) without formatting SD card? Because I already formatted new SD card with dedicated SD Memory Card Formatter  tool. If I select "Quick format" box on Rufus, SD card will be formatted repeatedly? What is proper way in this case?


text:
Q: Unable to use generate models with jodatime using Swagger-codegen maven plugin for jersey2 Using the following configuration for the maven swagger-codegen plugin:
        <plugin>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-codegen-maven-plugin</artifactId>
            <version>2.2.2</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <inputSpec>${basedir}/src/main/resources/swagger.yaml</inputSpec>
                        <ignoreFileOverride>${basedir}/.swagger-codegen-ignore</ignoreFileOverride>
                        <language>jaxrs</language>
                        <library>jersey2</library>
                        <configOptions>
                            <sourceFolder>src/main/java</sourceFolder>
                            <apiPackage>com.github.jmccloskey.api</apiPackage>
                            <modelPackage>com.github.jmccloskey.model</modelPackage>
                            <invokerPackage>com.github.jmccloskey.invoker</invokerPackage>
                        </configOptions>
                    </configuration>
                </execution>
            </executions>
        </plugin>

The code generation works, but uses Java Date in the models that are generated. From the swagger-codegen documentation this can be overridden to use JodaTime by adding the following inside the configOptions:
<dateLibrary>joda</dateLibrary>

This is what I am trying to do, but I get a compilation failure:
.../JodaDateTimeProvider.java:[3,41] package com.sun.jersey.core.spi.component does not exist

I think spi is what Jersey1 uses for dependency injection, whereas Jersey2 uses hk2.
I was able to resolve the compilation failure by adding jersey-bundle to my dependencies (along with a bunch of others such as jettison, rome and javax.mail) but had runtime issues in my API:
2. java.lang.IllegalStateException: Unable to perform operation: method inject on com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App
3. java.lang.IllegalStateException: Unable to perform operation: create on org.glassfish.jersey.message.internal.MessageBodyFactory

Mixing in Jersey 1 dependencies is not the right approach.
Is there a way to configure the swagger-codegen maven plugin to use hk2 instead?
For a full sample project see this github repo. Any pointers in the right direction would be appreciated.


text:
Q: Google Chrome crashing on linux when trying to upload *.jpg file I'm on Slackware 13.1, and installed Chrome 5.0.375.126 using sbopkg from slackbuilds. Whenever I open the file upload dialog and select a *.jpg file, the browser immediately crashes, leaving behind a "Segmentation fault" error. I've done the same thing with other files, *.zip, *.png and *.gif and they didn't crash the browser, for some reason it only happens to *.jpg files, so far. How do I fix this?

A: It seems to be a problem with libjpeg 6/7: http://code.google.com/p/chromium/issues/detail?id=30288

A: I had exactly the same problem for long time in ArchLinux. It's an issue with libjpeg linking (different libjpeg version on my system and different was used when building package).
I've switched to chromium (open-source version of chrome) and it works without any problems for long time. And it doesn't spy on you (sending data to google) like Chrome.


text:
Q: Saucelabs - intercept Android/iOS app HTTP(S) traffic Is it possible with Saucelabs to intercept mobile HTTP(S) traffic? I want to verify that a specific set of requests are executed by an iOS and Android app. I'm not looking to modify the requests, just checking for execution. And this has to be done automatically, in CI, without any manual intervention. Thanks!

A: At the moment, using a proxy is probably the best option.
If you were doing desktop tests, you could use Extended Debugging to capture a HAR file, then download it after the test and check the right calls were made.  Unfortunately, at the time of writing, Extended Debugging is only supported for Desktop.


text:
Q: Why do I have to turn off the Firewall in Windows-7 to print to my wireless printer? I cannot print to my wireless printer unless firewall is turned off in windows-7.
This printer works fine from other computers connected to my wireless network.  I thought that it used to work from this laptop also but NOT now and I have no idea why it quit working.
I know that it is the firewall because I can turn it off and the printer works fine from this computer.  Only fails if I have the firewall engaged.

A: I have found the answer to this problem. It only took me six days of pretty steady work. So here is the answer.
I am not sure if this is necessary or not but I left the homegroup first. Then proceeded with this routine.
Open a cmd prompt by clicking on start, type in "cmd prompt" (without the quotation marks) right click on "cmd prompt" at the top of the window and select "Run as Administrator" when command prompt is open type in "secpol" and press enter key. WAIT FOR IT! "Local Security Policy" window should open. (it did on my windows 7 on Toshiba laptop.) Search down left hand list until you find "Windows Firewall with Advanced Security" Click on the little arrow on the left of the listing and expand it showing "Windows Firewall with Advanced Security - Local Group Policy Listing" click on that listing and your profile overview will appear in the right hand column. At the bottom of the list, domain, private, and public profiles, you will see "Windows Firewall Properties" listed in BLUE.  Click on that start with the Domain Profile. Set firewall state to "ON", set inbound connections to "Block" default. Set outbound connections to "Allow" default. Now change to the Private Profile tab at the top of the window and make the same changes as you did for the Domain Profile.  Then change to the Public Profile and make the same changes as you did for the other two profiles.  Then select IPsec Settings, click on "customize" to the right of IPsec defaults and set all to the default setting, click Okay.  click on "not configured" to the right of IPsec exemptions Exempt ICMP from IPsec: and change to "No" default.  Now at IPsec tunnel authorization select "NO" click "apply" then click "OK".  Now you should see that all profiles are set "ON" green check, "block inbound" red IBSM, "Allow Outbound" green check. Close that window, close the command prompt by typing "exit" and enter.  You should now be able to print to your wireless printer.


text:
Q: MongoDB aggregation match nested array I´m striving to get some aggregated data from Mongo DB. I have the following collections:
I´m striving to get some aggregated data from Mongo DB. I have the following collections:
I have 2 collections:
product
 {
        "_id" : ObjectId("5eda578cb9c3fa1ef8c483c5"),
        "brand_name" : "LAVA",
        "short_description" : "Specifications",
        "offer_price" : 20,
        "quantity" : 5,
        "variants" : [
            "5eb9300438d0b83a3088feec",
            "5eb92a7909823240081cd763"
        ],
        "seller_id" : ObjectId("5e994af17a2f9b3a007e247c"),
        "name" : "LAVA X10",
        "createdAt" : ISODate("2020-06-05T14:32:44.582Z"),
        "updatedAt" : ISODate("2020-06-05T14:32:44.582Z")
    },
    {
        "_id" : ObjectId("5eda578cb9c3fa1ef8c483c8"),
        "brand_name" : "LAVA",
        "short_description" : "Specifications",
        "offer_price" : 20,
        "quantity" : 5,
        "variants" : [
            "5eb9300438d0b83a3088feed",
            "5eb92a7909823240081cd763"
        ],
        "seller_id" : ObjectId("5e994af17a2f9b3a007e247c"),
        "name" : "LAVA X11",
        "createdAt" : ISODate("2020-06-05T14:32:44.582Z"),
        "updatedAt" : ISODate("2020-06-05T14:32:44.582Z")
    }

2. attribute
{
    "_id" : ObjectId("5eb92a4d09823240081cd75f"),
    "is_active" : true,
    "name" : "Color",
    "slug" : [
        {
            "is_active" : true,
            "_id" : ObjectId("5eb92a7909823240081cd763"),
            "name" : "Green",
            "updatedAt" : ISODate("2020-06-01T13:47:56.584Z"),
            "createdAt" : ISODate("2020-05-11T10:35:37.357Z")
        },
        {
            "is_active" : true,
            "_id" : ObjectId("5eb92a7909823240081cd764"),
            "name" : "RED",
            "updatedAt" : ISODate("2020-06-01T13:47:39.236Z"),
            "createdAt" : ISODate("2020-05-11T10:35:37.357Z")
        }
    ],
    "createdAt" : ISODate("2020-05-11T10:34:53.642Z"),
    "updatedAt" : ISODate("2020-06-01T13:48:09.194Z"),
    "__v" : 0
},
{
    "_id" : ObjectId("5eb92a5409823240081cd760"),
    "is_active" : true,
    "name" : "Size",
    "slug" : [
        {
            "is_active" : true,
            "_id" : ObjectId("5eb92c4338d0b83a3088feeb"),
            "name" : "M",
            "updatedAt" : ISODate("2020-06-01T13:47:08.993Z"),
            "createdAt" : ISODate("2020-05-11T10:43:15.355Z")
        },
        {
            "is_active" : true,
            "_id" : ObjectId("5eb9300438d0b83a3088feec"),
            "name" : "S",
            "updatedAt" : ISODate("2020-05-11T10:59:16.731Z"),
            "createdAt" : ISODate("2020-05-11T10:59:16.731Z")
        },
        {
            "is_active" : true,
            "_id" : ObjectId("5eb9300438d0b83a3088feed"),
            "name" : "XXL",
            "updatedAt" : ISODate("2020-06-01T13:46:36.417Z"),
            "createdAt" : ISODate("2020-05-11T10:59:16.731Z")
        }
    ],
    "createdAt" : ISODate("2020-05-11T10:35:00.739Z"),
    "updatedAt" : ISODate("2020-06-01T13:47:08.993Z"),
    "__v" : 0
}

I want to this type of result
{
    "_id" : ObjectId("5eda578cb9c3fa1ef8c483c5"),
    "brand_name" : "LAVA",
    "short_description" : "Specifications",
    "offer_price" : 20,
    "quantity" : 5,
    "variants" : [
        "5eb9300438d0b83a3088feec",
        "5eb92a7909823240081cd763"
    ],
 "attributes" : [
        {
            "_id" : ObjectId("5eb92a5409823240081cd760"),
            "is_active" : true,
            "name" : "Size",
            "slug" : {
                "is_active" : true,
                "_id" : ObjectId("5eb9300438d0b83a3088feec"),
                "name" : "S",
                "updatedAt" : ISODate("2020-05-11T10:59:16.731Z"),
                "createdAt" : ISODate("2020-05-11T10:59:16.731Z")
            },
            "createdAt" : ISODate("2020-05-11T10:35:00.739Z"),
            "updatedAt" : ISODate("2020-06-01T13:47:08.993Z"),
            "__v" : 0
        },
        {
            "_id" : ObjectId("5eb92a4d09823240081cd75f"),
            "is_active" : true,
            "name" : "Color",
            "slug" : {
                "is_active" : true,
                "_id" : ObjectId("5eb92a7909823240081cd763"),
                "name" : "Green",
                "updatedAt" : ISODate("2020-06-01T13:47:56.584Z"),
                "createdAt" : ISODate("2020-05-11T10:35:37.357Z")
            },
            "createdAt" : ISODate("2020-05-11T10:34:53.642Z"),
            "updatedAt" : ISODate("2020-06-01T13:48:09.194Z"),
            "__v" : 0
        }
    ]
    "seller_id" : ObjectId("5e994af17a2f9b3a007e247c"),
    "name" : "LAVA X10",
    "createdAt" : ISODate("2020-06-05T14:32:44.582Z"),
    "updatedAt" : ISODate("2020-06-05T14:32:44.582Z")
},
{
    "_id" : ObjectId("5eda578cb9c3fa1ef8c483c8"),
    "brand_name" : "LAVA",
    "short_description" : "Specifications",
    "offer_price" : 20,
    "quantity" : 5,
    "variants" : [
        "5eb9300438d0b83a3088feed",
        "5eb92a7909823240081cd763"
    ],
"attributes" : [
        {
            "_id" : ObjectId("5eb92a5409823240081cd760"),
            "is_active" : true,
            "name" : "Size",
            "slug" : {
                "is_active" : true,
                "_id" : ObjectId("5eb9300438d0b83a3088feed"),
                "name" : "XXL",
                "updatedAt" : ISODate("2020-06-01T13:46:36.417Z"),
                "createdAt" : ISODate("2020-05-11T10:59:16.731Z")
            },
            "createdAt" : ISODate("2020-05-11T10:35:00.739Z"),
            "updatedAt" : ISODate("2020-06-01T13:47:08.993Z"),
            "__v" : 0
        },
        {
            "_id" : ObjectId("5eb92a4d09823240081cd75f"),
            "is_active" : true,
            "name" : "Color",
            "slug" : {
                "is_active" : true,
                "_id" : ObjectId("5eb92a7909823240081cd763"),
                "name" : "Green",
                "updatedAt" : ISODate("2020-06-01T13:47:56.584Z"),
                "createdAt" : ISODate("2020-05-11T10:35:37.357Z")
            },
            "createdAt" : ISODate("2020-05-11T10:34:53.642Z"),
            "updatedAt" : ISODate("2020-06-01T13:48:09.194Z"),
            "__v" : 0
        }
    ]
    "seller_id" : ObjectId("5e994af17a2f9b3a007e247c"),
    "name" : "LAVA X11",
    "createdAt" : ISODate("2020-06-05T14:32:44.582Z"),
    "updatedAt" : ISODate("2020-06-05T14:32:44.582Z")
}

// ------------ Here variants array values are attribute's slug ID -----------------
Please Help Me
Please let me know how?

A: That's not very effective data design: one of your collections uses ids of parts of documents in other collection. First of all you need to consider having slug._id: 1 index for attributes. Then to fetch products with included attributes which have filtered slugs use something like
db.product.find(...).map(function(prod){
  prod.attributes = [];
  for(sid in prod.variants){
    var attr = db.attributes.find({'slug._id': sid});
    attr.slug = attr.slug.find(function(slug){return slug._id == sid});
    prod.atributes.push(attr);
  }
  return prod;
})


text:
Q: call variable from while loop in PHP
<?php
// Create connection
$con=mysqli_connect("localhost","root","root");
mysql_select_db("test") or die( "Unable to select database");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

 //***************************** table 1 detail ***********

$query = "SELECT * FROM fraud WHERE a_number=" . $_GET["aNun_id"];
echo "<title>" . $_GET["aNun_id"] . "</title>";
echo "

    Date & Time
      A Number
      B Number
    Status

";

$result=mysql_query($query) or die (mysql_error());
while($row=mysql_fetch_array($result))
{
  echo "
";
  echo "" . $row['date'] . "	";
  echo "" . $row['a_number'] . "	";
  echo "" . $row['b_number'] . "	";
  echo "" . $row['status'] . "	";
  echo "
";
}
echo "
";

//***************************** table 2 detail ***********

//Here i'm trying to use bNum_id in below query
$query = "SELECT * FROM fraud WHERE b_number=" . $_GET["bNun_id"];
echo "

    Date & Time
      A Number
      B Number
    Status

";

$result=mysql_query($query) or die (mysql_error());

while($row=mysql_fetch_array($result))
{
  echo "
";
  echo "" . $row['date'] . "	";
  echo "" . $row['a_number'] . "	";
  echo "" . $row['b_number'] . "	";
  echo "" . $row['status'] . "	";
  echo "
";
}
echo "
";

//connection close
mysqli_close($con);
?>

Here in table one , I used aNun_id to get the data from another PHP file with "GET" command.
In the table two, I want bNun_id to show its related data in that table. How do i call bNun _id data to the second table from table one. Pls help me..

A: Are those two tables in the same page?
If so, You need to append the bNum_id to the same query string to use both aNum_id & bNum_id.
 echo "" . $row['b_number'] . "	";


text:
Q: php-cgi cpu usage is super high I am getting constantly high and wildly fluctuating CPU usage % for php-cgi commands as seen via "top" on my Centos server..
I have a server density account and it seems that this is a common trend:
User - PID - CPU % - MEM % - VSZ - RSS - TT - Stat - Started - Time - Command

500 - 6389 - 22.4 - 3 - 271136 - 32380 - ? - S - 20:26 - 0:40 - /usr/bin/php-cgi

Seems there are about 6 or so of those records in my processes list at any given check-in.
Any ideas what's causing this? I have fast_cgi installed and the module is loading.. Not sure why it isn't handling this though.
Any help would be greatly appreciated!
Ryan

A: php-cgi is responsible for actually running all your code.  It's very normal to see these taking up resources all the time.  If you're not seeing additional traffic to your website, this may be an indication that you have gotten hacked (people sending large amounts of spam or DDoS attacks via a compromised webserver will use lots of CPU).
I would suggest you stop using php-cgi and switch over to PHP-FPM.  This would give you better visibility into what exactly is going on.  It can also make things more efficient, as PHP-FPM workers can share one instance of an APC cache, while this may not be the case depending on how your php-cgi installation is configured.  PHP-FPM also lets you enable the 'slow log', which captures a snapshot of what exactly is executing whenever a request takes longer then X seconds.  This is very helpful for troubleshooting poor performance.

A: php-cgi handles the fcgi requests. So it probably means that your PHP is doing some processing. One PHP process can easily go to 100% for some requests on some hardware (I know from my bad server). You should watch if this matches with your requests and and examine them.


text:
Q: Convert 3D drawing to 2D drawing In Autocad Using C# I have to convert 3D drawing to 2D drawing. So I have to create a tool to automate this.
I don't know how to start and where I can get the materials.
Please give some idea to create this tool.
I am using Autocad2007 and I have to create the tool in C#.

A: AutoCAD Express Tools has a method called "Flatten" that is supposed to handle this.  However anyone who has actually used it knows it doesn't always get the job done.
This is certainly feasible, and you can use the in-process AutoCAD libraries natively in C# to walk through the entities.  (AcMdg.dll, AcDbMdg.dll)
I would approach this by entity type.  Each entity handles the z-axis differently in AutoCAD, so I'd group them into buckets beforehand and deal with them in batches.  Lines are easy, as you can change the z-axis on the start and end points to 0, and polylines have an elevation if I remember correctly.  3D polylines will need each vertex walked through and set individually.  Circles can have the center point set directly to z = 0... you see what I'm getting at.  Go through the AutoCAD documentation and get yourself a strategy for every entity type you'll encounter.
This will get tricky with things like blocks, because then you'll have the block definition itself to deal with too.  Natively 3D entities like surfaces, faces and extrusions are tougher still.  You'll ultimately have to decide what can be tossed out, and what you can recreate from primitives.
If it was a simple task, AutoDesk may have already pushed something out half-decent.  I think this is within your reach if you are willing to approach the problem with a strategy.


text:
Q: How to Pull Out Twitter Summary Data in other areas of my template? I am curious on how www.gigaom.com is able to callout the summary data of their articles. In addition I am trying to figure out how the summary autoposts when you select the tweet this button and the author's twitter gets tweeted as well.
I suspect the latter is available via twitter cards, but how can I get the summary data to show before the post content. A custom field? Micro-data?
Here are two examples of what I am talking about...
http://gigaom.com/2013/09/07/from-the-founder-of-aptera-tiny-and-stackable-ultra-efficient-organic-farms/
http://gigaom.com/2013/09/07/an-mlb-photographer-shows-you-how-to-instagram-in-the-big-leagues/
Any feedback is appreciated.


text:
Q: C# audio device enumeration and muting Since DirectSound is deprecated and XAudio2 removed enumeration, what is the "right" method for a C# application to enumerate and modify audio devices on Windows 7 and above?
I've seen solutions that use NAudio, CSCore, or other libraries and wrappers.  Are there bare-metal solutions for C#?


text:
Q: AngularJS - Using Nested JSON Objects in Sum of NG-Repeat totals I have adapted some code from an answer to a similar question I found searching here. Can someone please point me in the right direction on how to fix this code...
I am trying to to sum the values of a filtered column in ng-repeat. It works great for the first level of nested JSON but will not work on the second level..
The JSON provided is just an example..The real JSON is coming from a source that I have no control over the structure of the JSON itself.
My code is below..Help Please!!!

angular.module("turfApp", [])
            .filter('sumOfValue', function () {
                return function (data, key) {
                    debugger;
                    if (angular.isUndefined(data) || angular.isUndefined(key))
                        return 0;
                    var sum = 0;

                    angular.forEach(data, function (v,k) {
                        sum = sum + parseInt(v[key]);
                    });
                    return sum;
                }
            }).controller("turfController", function ($scope) {
                $scope.items = [{
                    "id": { "t": 1 }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
                    "details": "test11",
                    "quantity": 2,
                    "price": 100
                }, {
                    "id": { "t": 2 }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
                    "details": "test12",
                    "quantity": 5,
                    "price": 120
                }, {
                    "id": { "t": 3 }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
                    "details": "test3",
                    "quantity": 6,
                    "price": 170
                }, {
                    "id": { "t": 4 }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
                    "details": "test3",
                    "quantity": 8,
                    "price": 70
                }, {
                    "id": { "t": 5 }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
                    "details": "test5",
                    "quantity": 2,
                    "price": 160
                }, {
                    "id": { "t": 6 }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
                    "details": "test6",
                    "quantity": 9,
                    "price": 100
                }]
            });

        <input type="text" class="form-control" ng-model="searchFilter.id.t" placeholder="Search by ID" />

                    Id
                    Details
                    Quantity
                    Price

{{item.id.t}}

{{item.details}}

{{item.quantity}}

{{item.price}}

{{item.quantity * item.price}}

Sum ID -- {{resultValue | sumOfValue:'id.t'}}

Sum Quanitity -- {{resultValue | sumOfValue:'quantity'}}

A: The error is in the way you pass the 'id.t' in:

Sum ID -- {{resultValue | sumOfValue:'id.t'}}

This way the filter sumOfValue will try to get the value of parseInt(v['id.t']) which is undefined always! resulting in the NaN that you are seeing.
To fix this, you need to update your sumOfValue filter to read the proper value in the nested json, as shown in the following example:

angular.module("turfApp", [])
  .filter('sumOfValue', function() {
    return function(data, key, innerKey) {
      debugger;
      if (angular.isUndefined(data) || angular.isUndefined(key))
        return 0;
      var sum = 0;

      angular.forEach(data, function(v, k) {
        if (innerKey) {
           sum = sum + parseInt(v[key][innerKey]);
        } else {
           sum = sum + parseInt(v[key]);
        }
      });
      return sum;
    }
  }).controller("turfController", function($scope) {
    $scope.items = [{
      "id": {
        "t": 1
      }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
      "details": "test11",
      "quantity": 2,
      "price": 100
    }, {
      "id": {
        "t": 2
      }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
      "details": "test12",
      "quantity": 5,
      "price": 120
    }, {
      "id": {
        "t": 3
      }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
      "details": "test3",
      "quantity": 6,
      "price": 170
    }, {
      "id": {
        "t": 4
      }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
      "details": "test3",
      "quantity": 8,
      "price": 70
    }, {
      "id": {
        "t": 5
      }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
      "details": "test5",
      "quantity": 2,
      "price": 160
    }, {
      "id": {
        "t": 6
      }, //NESTED "T" VALUE WILL NOT COMPUTE IN TOTALS
      "details": "test6",
      "quantity": 9,
      "price": 100
    }]
  });

  <input type="text" class="form-control" ng-model="searchFilter.id.t" placeholder="Search by ID" />

        Id
        Details
        Quantity
        Price

{{item.id.t}}

{{item.details}}

{{item.quantity}}

{{item.price}}

{{item.quantity * item.price}}

Sum ID -- {{resultValue | sumOfValue:'id':'t'}}

Sum Quanitity -- {{resultValue | sumOfValue:'quantity'}}


text:
Q: how to search a specific tag in xml file with python I have a very big and complicated xml file which i want to get a text_body from it. i need to skip other trees and branches and only get a specific part that they look like this:
<req id="1">
    <text_body>
        Upon the USB being plugged in the system shall be able to be deployed and operational in less than 1 minute.
    </text_body>
</req>
<req id="2">
    <text_body>
    The system shall be able to handle 1000 customers logged in concurrently at the same time.
    </text_body>
</req>
<req id="CO-1">
    <text_body>
        Must use a SQL based database. SQL standard is the most widely used database format. Restricting to SQL allows easy of use and compatibility for Web Store.
    </text_body>
</req>
<req id="CO-2">
    <text_body>
        Compatibility is only tested and verified for Microsoft Internet Explorer version 6 and 7, Netscape Communicator Version 4 and 5. Other versions may not be 100% compatible. Also other browsers such as Mozilla or Firefox may not be 100% compatible.
    </text_body>
</req>
<req id="3">
    <text_body>
The system shall adhere to the following hardware requirements:
    <itemize>
        <item>4GB Flash ram chip</item>
        <item>128MB SDRAM</item>
        <item>Intel XScale PXA270 520-MHz chipset</item>
        <item>OS: Apache web server</item>
        <item>Database: MySQL</item>
    </itemize>
    </text_body>
</req>

i need to get the string in text_body but how can i write my code like 'return string with any id'. as you can see there are different ids. and in last one there is also a itemsize inside text_body that i don`t need it. there are similar questions like Q1 and Q2 i tried to get help from therm but they didn't return what i needed. how can i achieve this?
UPDATE
i need a output like this:
requirment 1: first text_body
requirment 2: seconf text_body

A: Is this what you're looking for ?
from bs4 import BeautifulSoup

soup = BeautifulSoup(open('test.xml').read(), features='lxml')
for text_body in soup.find_all('text_body')[:2]:
    print(text_body.get_text().strip())

Output
Upon the USB being plugged in the system shall be able to be deployed and operational in less than 1 minute.
The system shall be able to handle 1000 customers logged in concurrently at the same time.

A: You can use Python's built-in library for handling xml files:
import xml.etree.ElementTree as ET

tree = ET.parse('your/xml_file.xml')
root = tree.getroot()
text_body_strings = [x.find('text_body').text for x in root.findall('req')]

You might find you'll need to do some text cleaning on text_body_strings but that's a different topic.
Documentation on this package can be found here.


text:
Q: Incorrect key file for table on Windows I have seen from other posts that the issue I'm having relates to disk space:
Incorrect key file for table 'C:\Windows\TEMP\#sql72c_28e1c_2.MYI'; try to repair it

But I am using a Windows box with 1.58GB free on the C:\ drive and only 44mb of files in the C:\Windows\Temp folder. The total size of the 2dbs which I'm querying are 650mb and the query only links 12 tables.
I'm running WAMP server so my question is apart from the obvious that the query is generating too much data for the space, is there any other reason why this error could be occurring?

A: Queries would write to temporary tables (in this case to C:\Windows\TEMP) if the intermediate result-set would be larger than what MySQL would keep in memory. (In the EXPLAIN for the query, this is represented as 'using temporary')
This particular query has an IN() clause in it, and changing the list of values in the IN() clause meant we managed to get an error code 28 (out of space) out of MySQL.
Seems that Windows Server allocates space beyond what is reported as available so the drive never gets completely full. Freeing up space on the C: made the problem go away entirely since the table index doesn't get corrupted when building the temporary table.


text:
Q: Git push with PAT(Personal access Token) I'm trying git clone and push in a docker file. I have succeed to clone git repository with a Personal Access token like mentioned in this link Cannot clone git from Azure DevOps using PAT.
But I could not achieve make git push with using PAT to our company repositories.
The below code working for clone
git config --global http.extraheader "AUTHORIZATION: Basic VXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX3Xx"
git clone --depth 1 http://tfsXXX/tfs/XXXXX/XXXXGIT/_git/XXXXXXX
Could Someone help me How I can achive git push with PAT?

A: As I mentioned here, you can try and use your PAT as user: http://PAT@tfs2017:8080/tfs
Or keep your AUTHORIZATION: Basic header, but, as mentioned there, do base64 encode your PAT.
Note that http.extraheader might work better with Git 2.25 (Q1 2020).

A: I was able to get through this error by ensuring that my token had full repo access. I did a simple git push, without header switches. When prompting for my password, I used the PAT and successfully pushed to my repo.


text:
Q: Using tkinter, how do i tell my script to use IDLE editor? I have a Tkinter (3.8) program. When testing it in IDLE I select "Show report" from the menu and it automatically uses the IDLE Shell to output the data. I can then print the data from the Shell. However, when I open the program from a desktop shortcut and I select "Show report" it does not open any Shell to output the data and consequently I cannot print the formatted data. The code for the Run_Report which is called from the menu item "Show report" is shown below. What should I add to it to open the IDLE Shell window to display the data?
def Run_Report():

    sPrinciple=e_SelectInv.get()

    Sql=("SELECT Principle as Investment, RptDate as Report_Date, printf('%,.2f',RptVal) as Report_Value, printf('%.2f',ExchRate) as Exchange_Rate, printf('%,d',RptVal*ExchRate) as Total_Value FROM MyInv WHERE Principle = ?" +
             "order by Id Asc")

    conn = sqlite3.connect(r'/home/bushbug/Databases/TrackMyInv')
    curs = conn.cursor()
    curs.execute(Sql,(sPrinciple,))
    col_names = [cn[0] for cn in curs.description]
    rows = curs.fetchall()

    x = PrettyTable(col_names)
    x.align[col_names[0]] = "l"
    x.align[col_names[1]] = "r"
    x.align[col_names[2]] = "r"
    x.align[col_names[3]] = "r"
    x.align[col_names[4]] = "r"
    x.padding_width = 1

    for row in rows:
        x.add_row(row)

    print (x)
    tabstring = x.get_string()
    output=open("export.txt","w")
    output.write("Population Data"+"n")
    output.write(tabstring)
    output.close()

Help will be greatly appreciated.


text:
Q: Initializing an object without new operator in java Whats the difference between these two constructors.
Circle (Point2D center, double radius) {
    this.center = center;
    this.radius = radius;
}

Circle (Point2D center, double radius) {
    this.center = new Point2D(center.getX(), center.getY());
    this.radius = radius;
}

Heres the Point2D class. Both versions of the constructors are working just fine. I am just confused whats the difference.
class Point2D {
double x;
double y;

Point2D () {
    x = 0;
    y = 0;
}

Point2D (double x, double y) {
    this.x = x;
    this.y = y;
}

void setX (double x) {
    this.x = x;
}

void setY (double y) {
    this.y = y;
}

void setXY (double x, double y) {
    this.x = x;
    this.y = y;
}

double getX () {
    return x;
}

double getY () {
    return y;
}

double distance (Point2D p) {
    double x1 = p.getX();
    double y1 = p.getY();
    return Math.sqrt(Math.pow(x1 - x, 2) + Math.pow(y1 - y, 2));
}

double distance (double x, double y) {
    return Math.sqrt(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2));
}

}
Also the Circle class has 2 fields center and radius. center is type Point2D and radius is type double. I tried compiling and running both versions of the constructor. Both works well. So i am confused which one will be better to use and why, also the difference because in first one i havent used the new operation to initialize the center object.

A: second constructor uses defensive copy (witch is produced by Point2D constructor call) of the original center instance  to prevent further mutation (changes) of the input instance that may be very confusing and produce bugs

So i am confused which one will be better to use and why

the second approach is more safe because your Point2D class is mutable. It uses more memory (to hold additional defensive copy) but in real complex projects there are more pros for this design practice than cons.
If you can make Point2D class immutable then it will be ok to use the first constructor.

A: The second constructor creates a new Point instance - this.center = new Point2D(center.getX(), center.getY()); instead of keeping a reference to the instance passed to it. This means that if the passed center is later modified, the changes doesn't affect the Circle instance.
The second constructor is usually safer, since it has a truly private Point instance as the center of the Circle, while the first constructor shares the center with the caller of the constructor.
You can see the difference with this code :
Point2D point = new Point2D(10.0, 20.0);
Circle circle = new Circle (point, 4.0);
point.setX (5.0);
System.out.println(circle); // assuming you override toString to display the properties
                            // of the Circle

If you use the first constructor, after this code is executed, your circle will have a center of (5.0,20.0), while if you use the second constructor, the circle will have a center of (10.0,20.0);

A: Point2D is not immutable, i.e. has properties which can be changed after the point was constructed.
The first constructor of Circle just uses the Point2D object - now the caller could change the point object which would also affect the circle.
The second constructor of Circle makes a copy of the Point2D object. If the circle keeps the point object private it cannot be changed from outside.

A: this.center = center, you using parameter of center object.
this.center = new Point2D(center.getX(), center.getY()), you create new object of Point2D with parameter center value.


text:
Q: Hide Listtemplate from Create Dialog in PowerShell I want to set the "Hidden" attribute for a listtemplate to hide it from the create list dialog. I need a solution where I can switch visibility of listtemplates on a per web basis. First I tried this:
$web.ListTemplates["Project Document Library"].Hidden = $true

Unfortunately the "Hidden" attribute is readonly. According to MSDN the attribute is defined in the SchemaXml attribute of the listtemplate. So I tried this:
$template=$web.ListTemplates["Project Document Library"]
[xml]$schema=$template.SchemaXml
$schema.ListTemplate.SetAttribute("Hidden", "TRUE")
$template.SchemaXml=$schema

Found out that SchemaXml is readonly as well.
Thank you for every hint about how to hide listtemplates...
Regards,
Friedrich

A: The suggestion above, although acheiving the desired effect will need to be done on all servers in the farm and is unlikely to survive an upgrade / patch.  It's not therefore generally a good idea to do this.
Using PowerShell - If you grab the ID of the list template feature
$myWeb = (Get-SPSite "http://MySite").OpenWeb()
$featureToDisable = Get-SPFeature -Web $myWeb | ?{$_.DisplayName -eq "DocumentLibrary"}

Check that you have only one element in $featureToDisable.  Now, you will have the Identity of the list feature that although installed at farm level has a scope of Web.  This can now be disabled ...
$featureToDisable | Disable-SPFeature -Url $myWeb.Url

If you want it to be enabled, then you will have to get a reference to the feature at the farm level and then pipe this to the Enable-SPFeature commandlet with similar parameters. e.g.
$featureToEnable = Get-SPFeature | ?{$_.DisplayName -eq "DocumentLibrary"}
$featureToEnable | Enable-SPFeature -Url $myWeb.Url


text:
Q: Present participle to join sentences Here are two sentences which have been transformed into two different kinds of sentence having a different structure to the first version:

1a) All the employees are huge basketball fans. That makes it a very fun winter.
  1b) He couldn't give me a straight answer. This leaves a lot of room for doubt.
2a) All the employees are huge basketball fans, making it a very fun winter.
  2b) He couldn't give me a straight answer, leaving a lot of room for doubt.

Source: http://www.writeexpress.com/emphasis.html
I think it's the use of present participle(ing form) connecting two different sentences into one sentence. Isn't it? Do we use such sentences to show the result of first clause to the second clause ? Or why we use such sentences ?
I think we use such sentences to emphasize our writing(as per the website content refers to), But I don't know what kind of emphasize it is.

A: From your linked website:

Relative clauses can also be used to add subordinate information.

The two examples are of additional information, meaning that it would be fine to leave out this information, even if it is interesting.  Linking with the present participle gives no more or less emphasis than using other kinds of linking.

I plan to go to the doctor tomorrow, making it the first time in a while I've been.
I plan to go to the doctor tomorrow, where I hope I get a clean checkup.
I plan to go to the doctor tomorrow, if I can get there with all the traffic.

With all of these, the second part is subordinate information, but all are of (more or less) equal emphasis.  You can even put two (or more) in the same sentence:

I plan to go to the doctor tomorrow, making it the first time in a while I've been -- if I can get there with all the traffic.


text:
Q: jboss-web.xml unable to migrate I am migrating my project from jboss to websphere 8.5
As, I am new to this project, I was told to use the jboss-to-Websphere migration tool which lists the changes I need to make.
I have a warning saying that jboss-web.xml should not be used..
As I am anyway converting from jboss to websphere, would I need to use jboss-web.xml?
Can I delete it because I am not able to migrate the jboss-web.xml anyway?


text:
Q: Using switch inside a function, should break be used after a return true? function newLinks($a,$b,$c,$d,$e,&$links) {

    switch ($a) {
        case '00':
        $links = "Under Process";
        return true;
           break;

        case '01':
        $links = "Processed";
        return true;
            break;

        case '10':
        $links = "Deleted. Under Process";
        return true;
           break;

        case '11':
        $links = "Deleted. Processed";
            return true;
            break;

        default:
        return false;
    }
}

Is break needed after return true?
Because I do something like this:
if ( newLinks($a,$b,$c,$d,$e,$links) ) {
    echo $links;
} else {
    echo 'Failed';
}

A: Break is unecessary in this case as the function immediately terminates after returning the value so the break statement would never be reached anyway.

A: No, you won't need the break;, as the function is not executing further after a return call.

A: well you can leave the breaks for clarity to separate the cases. However this can cause bigger issues in the future, because you may not notice the returns.
Why not set a variable in each case, and return once after the switch function is over? In my opinion this will make the code much clearer.

A: The return statement will just pull it off the function. You don't need the break statement in this case.

A: Just like some pals said, break isn't need btw


text:
Q: Discord.js memberlist with the specified role command I have this memberlist command which works but if I will say a role that is not created on the server it will not send the if(!rrole) quote it will send the embed for mention the id, and also if I will try to run the command with an existing role it will not send anything and will give me an error which says Cannot read property 'id' of undefined
module.exports = {
    name: 'memberlist',
    description: 'shows the member list with the specified role',
    async execute(message, args, Discord) {
        const role = message.mentions.roles.first() || message.guild.roles.cache.get(args[0])
        const embe = new Discord.MessageEmbed()
        .setDescription(`${message.author.username} Mention the role or put the role ID`)
        .setColor("RANDOM")
        .setTimestamp()
      if(!role) return message.channel.send(embe);
        const rid = message.content.split(' ').splice(1).join(' ');
        const rrole = message.guild.roles.cache.find(val => val.id === rid);
        if (!rrole) return message.channel.send({embed: {description: `${message.author.username} \`${rid}\`
is not a role on this server`,
color: "RANDOM", timestamp: new Date()}});
        const members = await message.guild.members.fetch().then((member) => {
            if (Array.isArray(member)) {
              return member(
                (m) =>
                `• **${m.displayName}**
                      (${m.user.tag} - ${member.user.id})`
              )
            } else {
              return `• **${member.displayName}**
                           (${member.user} - ${member.user.id})`
            }
          })
        if(!members)
        return message.channel.send({embed: {description:
`there are no members that currently have **${role.name}** role`, color: "RANDOM", timestamp: new Date()}});
        const embed = new Discord.MessageEmbed()
        .setColor("RANDOM")
        .addField({
            name: `List of ${members}`,
            value: `${message.guild.roles.cache.get(role).members.map(m=> "• " +
`${m.user.username}` + "#" + m.user.discriminator + `\n(${m.user.id})`).join('\n')}
            that have the role \`${role.name}\``,
            description: members,
            maxPerPage: 20,
            page: Number(message.arg),
        });
        message.channel.send(embed)
    }
}


text:
Q: In Kinect SDK v2.0 how do I map a pixel in the color image to a voxel in the depth image? I know how to go the other way around. What I am looking for is, given a (x,y) coordinate in the pixel space (of the 1920x1080 image), how do I get the corresponding (if available) (x,y,z) (in meters) of the depth image. I realize that there are more pixels than voxels and it could be possible not to find any, but Microsoft's SDK has a CoordinateMapper class. This exposes the MapColorFrameToCameraSpace function. If I use that, I can get an array of points in the camera space (x,y,z) but I am unable to figure out how to extract the mapping for a specific pixel.

A: You probably need to use

CoordinateMapper.MapDepthFrameToColorSpace

Find the color space coordinates of all depth point.
Then, compare your pixel coordinate (x, y) with these color space coordinates. My solution is to find the closest point (might have better way), because the mapped coordinates are floats.
If you use C#, here is the code. Hope it helps!
private ushort GetDepthValueFromPixelPoint(KinectSensor kinectSensor, ushort[] depthData, float PixelX, float PixelY)
    {
        ushort depthValue = 0;
        if (null != depthData)
        {
            ColorSpacePoint[] depP = new ColorSpacePoint[512 * 424];

            kinectSensor.CoordinateMapper.MapDepthFrameToColorSpace(_depthData, depP);

            int depthIndex = FindClosestIndex(depP, PixelX, PixelY);

            if (depthIndex < 0)
                Console.WriteLine("-1");
            else
            {
                depthValue = _depthData[depthIndex];
                Console.WriteLine(depthValue);
            }
        }
        return depthValue;
    }

    private int FindClosestIndex(ColorSpacePoint[] depP, float PixelX, float PixelY)
    {
        int depthIndex = -1;
        float closestPoint = float.MaxValue;
        for (int j = 0; j < depP.Length; ++j)
        {
            float dis = DistanceOfTwoPoints(depP[j], PixelX, PixelY);
            if (dis < closestPoint)
            {
                closestPoint = dis;
                depthIndex = j;
            }
        }
        return depthIndex;
    }

    private float DistanceOfTwoPoints(ColorSpacePoint colorSpacePoint, float PixelX, float PixelY)
    {
        float x = colorSpacePoint.X - PixelX;
        float y = colorSpacePoint.Y - PixelY;
        return (float)Math.Sqrt(x * x + y * y);
    }


text:
Q: Failed to register window when using local WNDCLASSEX variable If I put the WNDCLASSEX wcex variable definition out of main function (as global variable) the class will be registered successfully
#include <windows.h>
WNDCLASSEX wcex;
int main()
{
    wcex.cbSize = sizeof ( WNDCLASSEX );
    wcex.lpszClassName = "Success" ;

    if ( !RegisterClassEx ( &wcex ) )
    {
        MessageBox ( NULL, "Failed to register window class.", "Error", MB_OK );
    }
}

But If I put it inside the main function, It will not be registered
#include <windows.h>
int main()
{
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof ( WNDCLASSEX );
    wcex.lpszClassName = "Success" ;

    if ( !RegisterClassEx ( &wcex ) )
    {
        MessageBox ( NULL, "Failed to register window class.", "Error", MB_OK );
    }
}

I can't figure out the reason, kindly help in this issue.
Thanks in advance.

A: Objects with static storage duration are zero-initialized1). Your second example is semantically different in that wcex (automatic storage duration) holds random values. To match the semantics, use WNDCLASSEX wcex = { 0 }; instead.

1) Assuming you are using a C++ compiler. The rules for C are different.


text:
Q: JUnit Testing for attribute values within in Stream This question is related to my previous question at JUnit assertions within in Java 8 stream.
If I have 3 objects, how do I verify the values of the objects' attributes within a stream? My previous question answered how to test for the presence of them, but I now need to test for each individual attribute's value. Can someone give me a code snippet?

A: You can filter the properties by the expected values and count the resulting entries. This number must be equal to the original size.
List<Integer> expected = Arrays.asList(1, 2, 3);
long count = objects.stream()
    .map(MyObject::getId)
    .filter(id -> expected.contains(id.intValue()))
    .count();
Assert.assertEquals(objects.size(), (int) count);

If you want to check all properties in one stream, do it like this:
long count = objects.stream()
    .filter(o-> expectedIds.contains(o.getId().intValue()))
    .filter(o-> expectedNames.contains(o.getName()))
    // and so on
    .count();


text:
Q: Passing callback objects to WCF service methods Is it possible to pass callback objects (with callback methods) to a wcf service method?
Let's presume i have the following class:
class Callback
{
     public Callback(){}
     public int GetSomeData(int param)
     {
       return param;
     }
}

Is it possible somehow to make a call like :
WCFServiceProxy proxy = new WCFServiceProxy();
Callback myCallback = new Callback();
proxy.SomeMethod(myCallback);

and have the service call GetSomeData() implemented on the client side?
Or what would be a working solution for this?

A: see Duplex Services

A: Yes, you can do that.  You have to define a secondary interface that serves as the callback contract.
[ServiceContract]
public interface ICallback
{
    [OperationContract(IsOneWay=true)]
    void InvokeCallback();
}

[ServiceContract(CallbackContract=typeof(ICallback)]
public interface IContract
{
    [OperationContract]
    void DoSomething();
}
[ServiceBehavior]
public class MyService : IContract
{
    void DoSomething() { }
}

That's the basic approach.  I would strongly suggestion looking at Juval Lowy's website, IDesign.net.  His downloads section has several examples of how to do this.


text:
Q: Increase height of reflected object Want to reflect an image, and my code looks like
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       height="500" width="500"
                       creationComplete="init(event)">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <fx:Script>
        <![CDATA[

            import flash.filters.BlurFilter;

            import mx.core.UIComponent;
            import mx.events.FlexEvent;

            private var loader:Loader = new Loader();
            private var picture:BitmapData;

            private var reflection:BitmapData;
            private var reflectionHolder:Bitmap;

            protected function init(event:FlexEvent):void
            {
                loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
                loader.load(new URLRequest("assets/rectangle.png"));
            }

            private function onComplete (event:Event):void
            {
                trace("loaded!");
                var loaderInfo:LoaderInfo = LoaderInfo(event.target);
                picture = new BitmapData(loaderInfo.width, loaderInfo.height, false, 0xFFFFFF);
                picture.draw(loaderInfo.loader);
                img.source=picture;
                trace(picture.height,picture.width);
            }

            private function createReflection():void
            {
                reflection=new BitmapData(picture.width,picture.height,true,0x00ffffff);

                var flipMatrix:Matrix = new Matrix();
                flipMatrix.rotate(Math.PI);
                flipMatrix.scale( -1, 1 );
                flipMatrix.translate(0, picture.height);

                reflection.draw(picture, flipMatrix);

                for (var i:int = 0; i < picture.height; i++)
                {
                    var rowFactor:Number = Math.max(0, 1 - (i / picture.height));
                    for (var j:int = 0; j < picture.width; j++)
                    {
                        var pixelColor:uint = reflection.getPixel32(j,i);
                        var pixelAlpha:uint = pixelColor>>24&0xff;
                        var pixelRGB:uint = pixelColor&0xffffff;
                        var resultAlpha:uint = pixelAlpha*rowFactor;
                        reflection.setPixel32(j, i, resultAlpha << 24 | pixelRGB);
                    }
                }

                reflection.applyFilter(reflection, reflection.rect, new Point(0, 0), new BlurFilter(4, 4, 3));

                reflectionHolder=new Bitmap(reflection);
                reflectionHolder.y=img.y+img.height;
                reflectionHolder.x=img.x;
                reflectionHolder.width = img.width;
                reflectionHolder.height = img.height;

                var uIComponent:UIComponent = new UIComponent();
                uIComponent.addChild(reflectionHolder);
                this.addElement(uIComponent);
            }

            protected function btn_clickHandler(event:MouseEvent):void
            {
                createReflection();
            }
        ]]>
    </fx:Script>
        <s:Group height="100%" width="100%">
            <s:BorderContainer backgroundColor="0x0d0d0d" height="100%" width="100%"/>
            <s:Image id="img" height="100" width="200" />
            <s:Button id="btn" click="btn_clickHandler(event)" />
        </s:Group>
</s:WindowedApplication>

it shows result but the out put was not perfect...

Objective:- Reflected object should be same as the real Object and Have Some Distance From Real Object.

A: It will be very much code to show in one answer. Actually, I searched my very old archives, and I found my old class for reflection (2009 year). It will create reflection for you, It supports animated objects, and also distance from object to start of reflection. With only 2 lines of code:
var test:Sprite = new Sprite();
test.graphics.beginFill(0x990099);
test.graphics.drawRect(0, 0, 100, 50);
addChild(test);

test.x = test.y = 50;

//Reflection
//test - object that will be reflected
//40 - alpha, 40%
//200 - ratio, max value 0xFF or 255, with 0xFF you will see full object in reflection
//-1 - update frame rate, for animated objects
//0 - some dropoff... actually I don't remember it, don't use it by passing zero, It affects reflection bounds
//10 - distance to the reflection in pixels...
var vars:ReflectVars = new ReflectVars(test, 40, 200, -1, 0, 10);
var reflect:Reflect = new Reflect(vars);

And a result:

if you are interested in the class, I could move it to GitHub.

A: flipMatrix.translate(0, picture.height);

try changing this to
flipMatrix.translate(0, picture.height + 20);

OR
 reflectionHolder.y=img.y+img.height;

try changing this to
   reflectionHolder.y=img.y+img.height + 20;

for adding space between reflection & real picture


text:
Q: Meta "apple-itunes-app" doesn't work I've written an html page with the Apple meta to link at my app in the App Store:
<meta name="apple-itunes-app" content="app-id=MY_APP_ID" app-argument="myschema:http://example.com">

The documentation
(https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/PromotingAppswithAppBanners/PromotingAppswithAppBanners.html)
says that with "app-argument" the app fires application:openURL:sourceApplication:annotation: method and pass as url the app-argument.
The method doesn't been called.
The documentation of the methods say to use new method  application:openURL:options:, nothing change.
I read in other answer that this meta works only with the release app version (so isn't debuggable), so I put an hidden file log in the app and log at first line of method to be sure that the problem isn't my code in the method.
I tried in with ios11 and ios11.1
Any suggestion?

A: The documentation link you included specifically shows "app-argument" should be part of the value given to the content attribute and not an attribute itself. Notice where the quotation marks are:
<meta name="apple-itunes-app" content="app-id=myAppStoreID, affiliate-data=myAffiliateData, app-argument=myURL">


text:
Q: Найти сумму простых делителей числа N При вводе любого значения ничего не выводится
#include <stdio.h>
#include <conio.h>

int main()
{
    int n, sum = 1;
    if (scanf("%lf", n) == 0)
    {
        printf("Incorrect input value");
    }
    else
    {
        for (int i = 2; i <= n; i++)
        {
            int count = 0;
            if (n % i == 0)
            {
                for (int j = 2; j <= i - 1; j++)
                {
                    if (i % j == 0)
                    {
                        count += 1;
                        break;
                    }
                    else
                    {
                        sum += i;
                    }
                }
            }
            else
            {
                break;
            }
        }
    }
    printf("%i", sum);
}

A: У Вас есть несколько логических ошибок в коде:

*

*Почему переменная sum инициализированная значением 1? По идее должно быть 0.

*Ввод значения через scanf происходит по адресу. К тому же у Вас она ожидает значение с плавающей запятой, а не целое значение. Корректный вызов примерно такой: scanf("%d", &n).

*Добавление делителя к сумме должно происходить после проверки числа на простоту, а не в ней. Т.е. строка sum += i; должна быть за пределами вложенного цикла и выполняться только если count == 0.

*Веткой else {break;} Вы завершаете искать делители после первого не простого делителя. Эта ветка вообще не нужна.

По итогу Ваш код должен иметь примерно такой вид:
#include <stdio.h>

int main()
{
    int n, sum = 0;
    if (scanf("%d", &n) == 0)
    {
        printf("Incorrect input value");
    }
    else
    {
        for (int i = 2;i <= n; i++)
        {
            int count = 0;
            if (n % i == 0)
            {
                for (int j = 2; j <= i - 1; j++)
                {
                    if (i % j == 0)
                    {
                        count += 1;
                        break;
                    }
                }
                if (count == 0)
                {
                    sum += i;
                }
            }
        }
    }
    printf("%i", sum);
    return 0;
}

Это Ваш код с минимальными изменениями. В таком виде его не очень просто понять с первого взгляда из-за непонятных имён переменных и нагромождении всего в одной функции. Вот для примера Я набросал код, который не тянет на идеальную реализацию, но понять его намного проще (правда без ввода данных с клавиатуры):
#include <stdio.h>
#include <stdbool.h>

// Функция проверки числа на простоту
bool isPrime(int n)
{
    for(int i = 2; i * i <= n; i++)
    {
        if (n % i == 0)
        {
            return false;
        }
    }
    return true;
}

int main(void)
{
    // Наше входное значение
    int input = 122;

    // Сразу инициализируем сумму двойкой, если наше число чётное,
    // иначе инициализируем нулём
    unsigned long long sum = input % 2 ? 0ULL : 2ULL;

    // Цикл начинается с 3, потому что двойку мы уже учли в инициализации суммы
    // и теперь удобно идти только по нечётным числам
    for (int currentDivisor = 3; currentDivisor <= input; currentDivisor += 2)
    {
        // Если число делится на текущий проверяемый делитель без остатка
        // и этот делитель является простым числом, то добавляем его к сумме
        if (input % currentDivisor == 0 && isPrime(currentDivisor))
        {
            sum += currentDivisor;
        }
    }
    printf("Sum: %llu\n", sum);
    return 0;
}

A: Я бы делал так:
int main()
{
    int n, sum = 0;
    if (scanf("%d",&n)==0) return 1;
    if (n%2 == 0)
    {
        sum += 2;
        while(n%2 == 0) n/=2;       // Делим, пока делится.
    }

    for (int i = 3; i*i <= n; i+=2) // Только по нечетным, четным n быть  уже не может
    {
        if (n%i == 0)
        {
            sum += i;
            while(n%i == 0) n /= i; // Делим, пока делится. Так и n уменьшается
        }                           //  что ускоряет работу...
    }
    if (n > 1) sum += n;            // Если после этого что-то осталось — то это простое
    printf("%d\n", sum);
}

Но встает вопрос о кратных делителях. Их не надо учитывать? Например, 18 = 2*3*3. Надо ли 3 считать один раз или два?


text:
Q: How Can I Transfer a File Using Remote Desktop Connection Using VBScript? I've spent the better part of the afternoon trying to figure this out. I have to upload a file to a connected computer via Remote Desktop Connection using a Script Written in VBSCript.  I was going to use FTP, but found out that I can't.
Right now I have
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile "C:\blahdiddyblah\blahdiddy.zip", "fubar.networkname.blah.com\directory

When I run this I get a bad login or password error I understand this is because it doesn't give me a way to login to remote desktop before it tries the upload.
I've tried something something similar to what's below, except with the password included as part of the string, in that case it throws a "path not found" error.
Option Explicit
Dim sComputer, sUsername
sComputer = InputBox("Please enter the Computer Name or IP")
sUsername = InputBox("Please Enter the Users Login ID")

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile "\\servername\path\servers.lst" _
   , "\\" & sComputer & "\c$\Documents and Settings\" & sUsername & "\Local Settings

A: OK, so what I've done here is use the net use command from windows which makes the Remote Desktop Connection, and basically wrap it in VBScript.
Set WshShell = CreateObject("WScript.Shell")

WshShell.Run("net use \\destinationServerAddress /user:domain\UserName PW")

//Allow  Sleep while connection is made, otherwise it will fail because it has not had the opportunity to login yet.
WScript.Sleep 20000

Set fso = CreateObject("Scripting.FileSystemObject")

//Make sure you have admin rights for the folder, and it is shared. This means right click, and going into Sharing Options in windows.
fso.CopyFolder "SourceFldr", "\\ServerFolder/Fubar", true


text:
Q: forEach loop with if and else statements So the title might not be the best description of my problem because I don't really know how to sum up the problem. I have a forEach loop for each event in my database and each one is classified as type = to either "trip", "ropes course", or "other". I have a section for each type of event, but I would like a way where if there are no events in the section I can not display the bannertron header and if there are no events in the whole database I can display different HTML. My code also seems very WET and I would love any suggestions on how to DRY up this page.
<% include partials/header %>

Upcoming Trips

  <% events.forEach(function(event){ %>
  <% if(event.type === "trip"){ %>

<%= event.title %>

    <%= event.startdate %> -
    <%= event.enddate %>

Location: <%= event.location %>

<%= event.description %>

    <% if(currentUser && (currentUser.admin === true)){ %>
      <a href="/calendar/<%= event._id %>/edit" class="btn btn-warning">Edit
      <form action="/calendar/<%= event._id %>?_method=DELETE" method="POST">
        <button class="btn btn-danger">Delete</button>
      </form>
    <% } %>

    <% } %>
  <% }); %>

Upcoming Climbing Days

  <% events.forEach(function(event){ %>
  <% if(event.type === "ropescourse"){ %>

<%= event.title %>

    <%= event.startdate %> -
    <%= event.enddate %>

Location: <%= event.location %>

<%= event.description %>

    <% if(currentUser && (currentUser.admin === true)){ %>
      <a href="/calendar/<%= event._id %>/edit" class="btn btn-warning">Edit
      <form action="/calendar/<%= event._id %>?_method=DELETE" method="POST">
        <button class="btn btn-danger">Delete</button>
      </form>
    <% } %>

    <% } %>
  <% }); %>

Other Events

  <% events.forEach(function(event){ %>
  <% if(event.type === "other"){ %>

<%= event.title %>

    <%= event.startdate %> -
    <%= event.enddate %>

Location: <%= event.location %>

<%= event.description %>

    <% if(currentUser && (currentUser.admin === true)){ %>
      <a href="/calendar/<%= event._id %>/edit" class="btn btn-warning">Edit
      <form action="/calendar/<%= event._id %>?_method=DELETE" method="POST">
        <button class="btn btn-danger">Delete</button>
      </form>
    <% } %>

    <% } %>
  <% }); %>

<% include partials/footer %>

Ideally, I would be able to loop through the events, check which type it is, put it in its respective area, and if there are none of a type, display some text like "no events scheduled" and if there are no events in total, display something else.

A: If this was me, I would split the events up into 3 different arrays in the node file, instead of sorting it all out inside of an ejs file. The Array.prototype.filter command would be useful for this. The nice thing about it is it returns a new array, with only items that return true for the function you pass in. It does not alter the original array, just passes a new one in. You can do something like
var trips = events.filter(function(event){
   return event.type == "trip";
});
//do similar for "rope course", and for "other" you could do something like
return event.type != "trip" && event.type != "rope course"
// for the return statement.

You can do a
if(events.length == 0){
// show different html file
} else {
// show the html file with events, passing in the arrays
}

Make sure you pass all the arrays into the ejs file. For each array, you can do a similar
if(trips.length != 0){
// show banner and stuff
}

And do it for all three.
Hope this helps!


text:
Q: firefox interprete wrong my string i'm converting a chrome extension to firefox, and i got the browser.action badge not showing properly when empty. I traced it and it seems firefox interprete an empty chain "" like this :

0[object Object]0

while in chrome i get it like this

arg = 0

function updateCounter(arg) {
    if (arg == 0)
        arg = "";
    chrome.browserAction.setBadgeText({ text: arg.toString() });
}
chrome.storage.onChanged.addListener(function(changes, namespace) {
  var updatedValues
  chrome.storage.local.get({"count": 0, "countDailymotion": 0, "tweetCount": 0, "countFacebook": 0}, function(items){
  updateCounter(items.count + items.countDailymotion + items.tweetCount + items.countFacebook)
  })
});

which causes the browseraction badge to have the value

0[ob

any idea what this is about?


text:
Q: Refresh filters when new data comes in I have a Google Spreadsheet with multiple sheets. We paste a table of data into sheet1 and all the other sheets have filters based basically on the 'membernumber' value in one of the columns (so that the mass data that gets imported gets sorted by our individual members). We then want to send an email with an updated table for each individual member (so therefore my script will access each individual sheet and copy the filtered table of data to the email message body).
But my question is for one of the early parts of this script: How can I make my Apps Script automatically refresh the filters in all of our sheets after we've imported the new data in sheet1? Right now we go manually and click the filter icon and re-select the member's number, or 0 if they don't have data for that day. It's killing me.
I know apps script doesn't have an AutoFilter method, but maybe with the Sheet API I can refresh them? I think this may be the method I need to call.
Let's say I have a sheet, would I just write:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("example");
sheet.updateFilterView({"fields": *}); //since I want to update all filters, all fields on each sheet

I really wish the Google sheets API had some examples!


text:
Q: "not in this scope" error in cpp function calling I was trying to implement mergesort in cpp. However, the Dev-cpp 5.6.1 reports some "not in this scope" error. It said, "lo", "mid", and "hi" was not declared in this scope. Can you tell me why this happens? Thanks.
#include<iostream>
using namespace std;
void merge(int nums[], int lo, int mid, int hi) {
    int n1 = mid - lo + 1;
    int n2 = hi - mid + 1;
    /*Other implementation code omitted*/
}
int main() {
    /*code to Input numbers into nums[]*/
    merge(nums, 0, 4, 9);
    return 0;
}

A: When reading error messages that involve syntax errors, it is important to pay the most attention to the very first one. This is because the C++ compiler is not obligated to stop at the first error, and more errors may be produced as a consequence of the first.
In your original code, you have a syntax error in your declaration of the nums parameter to your merge() function:
#include<iostream>
using namespace std;
int nums[10];
void merge(int[] &nums, int lo, int mid, int hi) {
    int n1 = mid - lo + 1;
    int n2 = hi - mid + 1;
    /*Other implementation code omitted*/
}
int main() {
    /*code to Input numbers into nums[]*/
    merge(nums, 0, 4, 9);
}

You have since edited your program to remove that syntax error, but with this original code, I see the following error messages:
x.cc:3: error: expected ',' or '...' before '&' token
x.cc: In function 'void merge(int*)':
x.cc:4: error: 'mid' was not declared in this scope
x.cc:4: error: 'lo' was not declared in this scope
x.cc:5: error: 'hi' was not declared in this scope
x.cc: In function 'int main()':
x.cc:3: error: too many arguments to function 'void merge(int*)'
x.cc:11: error: at this point in file

You reported the was not declared in this scope errors, but failed to mention the first one, which is pointing out the syntax error for nums. Because of this syntax error, the compiler failed to parse the rest of the function parameters, so it reported those identifiers as having no visible declaration.
Fixing this error removes the others. This is because the parser for the function prototype now picks up the rest of the function arguments, so those are now in scope for the rest of the function.


text:
Q: How to index for missing values in cosmosDB? Let's assume I need to verify every document in a CosmosDB collection has AnImportantProperty set up (= property exists, may have explicit value null). Most of them do, but for "reasons", some of them may not.
I can include the new property to indexing policy, so I can easily find which documents are OK with an index-covered query:
select * from c where is_defined(c.AnImportantProperty)

But the opposite query (which is what I'm really interested in) does not seem to benefit from the index:
select * from c where NOT is_defined(c.AnImportantProperty)

Is there a way to write an index/query to find documents with missing property without a full scan?
EDIT:
For example, I've heared some second-hand rumors about negated indexes and a mysterious "v2 index". Both may indicate there is (or will be) a solution to this scenario.

A: Currently (July 2019) there does NOT seem to be a way to write such a query.
All hope is not lost though, as according to Azure Cosmos DB Team comment for the feature request it is in planned stage.
UPDATE:
The feature is now completed as reported by https://devblogs.microsoft.com/cosmosdb/april-query-improvements/:

Queries with inequality filters or filters on undefined values can now be run more efficiently. Previously, these filters did not utilize the index. When executing a query, Azure Cosmos DB would first evaluate other less expensive filters (such as =, >, or <) in the query. If there were inequality filters or filters on undefined values remaining, the query engine would be required to load each of these documents. Since inequality filters and filters on undefined values now utilize the index, we can avoid loading these documents and see a significant improvement in RU charge.
Here's a full list of query filters with improvements:

*

*Inequality comparison expression (e.g. c.age != 4)

*NOT IN expression (e.g. c.name NOT IN ('Luis', 'Andrew', 'Deborah'))

*NOT IsDefined

*Is expressions (e.g. NOT IsDefined(c.age), NOT IsString(c.name))

*Coalesce operator expression (e.g. (c.name ?? 'N/A') = 'Thomas')

*Ternary operator expression (e.g. c.name = null ? 'N/A' : c.name)

If you have queries with these filters, you should add an index for the relevant properties.

A: hardly. i cannot think of any since you are effectively listing all except known value. but, i would suggest a bit different approach.

*

*introduce type property on all of your documents

*classes/objects that differ in some property  can (i won't say should although i mean it) be considered of different type (even if one just inherits other)

*store those without property as type="someType" and those with type="someOtherType"

*query for those of according type you need

*if its not enough, introduce subtype
i'd probably try something like that. anything that avoids scanning too much.


text:
Q: Java: insert element in the middle of custom made generic vector I am trying to write a code to insert a string/integer/null to the middle of a generic vector in JAVA. But this part of code doesn't compile. What might be the problem? Thank you. I'm also adding error messages.
public synchronized void addToPosition (T element, int index) {
    if (index+1 == size-1) {
        ensureCapacity();
    }
    System.out.println("Add element to position:");
    Scanner scanner = new Scanner(System.in);
    index = scanner.nextInt();
    if (index < 0 || index > this.index-1) {
        throw new IndexOutOfBoundsException();
    }
    T[] newElementData = (T[]) new Object [size];
    for (i = 0; i < index; i++) {
        newElementData[i] = elementData[i];
    }
    System.out.println("Which element to add?");
    element = (T) scanner.nextLine();
    newElementData[index] = element;
    for (i = index+1; i < this.index; i++) {
        newElementData[i] = elementData[i+1];
    }
    elementData = newElementData;
    this.index++;
}

error messages

A: As you said in the comments, you call the addToPosition() method like so:
vectorList.addToPosition();

while the method signature is the following:
public synchronized void addToPosition (T element, int index) {

So they don't match. For example, you can get rid of the parameters:
public synchronized void addToPosition () {
    T element;  // the values you will read later from user input
    int index;


text:
Q: httpRequest inside a Promise I use the following code (simplified below for example's sake_ to get all users in my database, then access an external API which returns data which I want to save in the user's row in the database.
It does not seem to work... The user data is not saved. I'm new to Parse... so what am I doing wrong?
Parse.Cloud.job("updateToken", function(request, status) {

    Parse.Cloud.useMasterKey();
    var query = new Parse.Query(Parse.User);

    query.find().then(function(results) {

        var promises = [];

        _.each(results, function(user) {

                promises.push(function() {

                    Parse.Cloud.httpRequest({
                      url: "http://www.example.com/",
                      success: function(httpResponse) {

                        user.set("authSave", httpResponse.text);
                        return user.save();

                      },
                      error: function(httpResponse) {
                        user.set("authSave", "testFail");
                        return user.save();
                      }
                    });
                });
        });

        Parse.Promise.when(promises);
    }).then(function(){
        status.success("YAY!");
    });

});

A: Because the httpRequest is asynchronous, the functions that your passing to your array of promises will all be complete before the httpRequest's call their callbacks.
You want to use the promise returned from the httpRequest method and at that to the array instead.
Like this
Parse.Cloud.job("updateToken", function(request, status) {

    Parse.Cloud.useMasterKey();
    var query = new Parse.Query(Parse.User);

    query.find().then(function(results) {

        var promises = [];

        _.each(results, function(user) {

            promises.push(Parse.Cloud.httpRequest({
                    url: "http://www.example.com/"
                }).then(function(httpResponse) {
                    user.set("authSave", httpResponse.text);
                    return user.save();
                }, function(error) {
                    user.set("authSave", "testFail");
                    return user.save();
                })
            );
        });

        Parse.Promise.when(promises);
    }).then(function(){
        status.success("YAY!");
    });
});

I'm sorry if that's not perfect as I didn't test.
But it should lead you in the right direction.

A: Didn't take time to check, but he function handling query.find.then should return a promise.
Try with :
query.find.then(function(results) {

   ...

   return Parse.Promise.when(promises);

}).then (function(){
    status.success("YAY!");
});


text:
Q: Using completion function in Term::ReadLine::Gnu I want to make a console and change the automatic completion function when I press tab but I want to differentiate between two cases:

*

*If I press tab and the beginning of the command matches a list I supplied in an array, the auto complete will be according to this array.

*If I press tab and the command isn't recognized from the list I supplied, I want the generic completion function to work, so t hat it will auto complete directories and file names in the current directory.

Is it possible?
Thanks a lot.
Edit: I'm trying to do it inside a perl script. I saw this example:
rl_attempted_completion_function
A reference to an alternative function to create matches.
The function is called with TEXT, LINE_BUFFER, START, and END. LINE_BUFFER is a current input buffer string. START and END are indices in LINE_BUFFER saying what the boundaries of TEXT are.
If this function exists and returns null list or undef, or if this variable is set to undef, then an internal function rl_complete() will call the value of $rl_completion_entry_function to generate matches, otherwise the array of strings returned will be used.
The default value of this variable is undef. You can use it as follows;
use Term::ReadLine;
...
my $term = new Term::ReadLine 'sample';
my $attribs = $term->Attribs;
...
sub sample_completion {
    my ($text, $line, $start, $end) = @_;
    # If first word then username completion, else filename completion
    if (substr($line, 0, $start) =~ /^\s*$/) {
        return $term->completion_matches($text,
                                         $attribs->{'username_completion_function'});
    } else {
        return ();
    }
}
...
$attribs->{attempted_completion_function} = \&sample_completion;

completion_matches(TEXT, ENTRY_FUNC)
What I want to do is that in case when tab is pressed it recognizes a substring from an array I provide, the auto completion will be from that array (if there are multiple matches it will give all of them like a regular unix console).
Otherwise, I want the auto completion to be file recognition.

A: The subroutine used internally by Term::ReadLine::Gnu to provide the default completion is filename_completion_function, which you can call directly from your custom subroutine:
use Term::ReadLine;

my $term = new Term::ReadLine 'MyTerm';
$term->Attribs->{'completion_entry_function'} = \&my_completion;
my $ans = $term->readline('How can I help you? ');

sub my_completion {
    my ($text, $state) = @_;
    if (my_test) {
        return my_custom_stuff;
    }
    else {
        return Term::ReadLine::Gnu->filename_completion_function($text, $state);
    }
}


text:
Q: How to animate fragment from bottom I have an activity, I want to add the Fragment on activity then when i click a button Fragment should appear from bottom with animation .

A: Hi you can add fragment in your activity in this way, add this part of code in you onClick() method:
FragmentTransaction mfragmentTransaction = getFragmentManager().beginTransaction();

//add an animation, you can create your custom animation. Show below
mfragmentTransaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
MFragment mFragment = new MFragment();
mfragmentTransaction.replace(R.id.MFragment, mFragment);
mfragmentTransaction.addToBackStack(null).commit();

slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set>
  <translate xmlns:android="http://schemas.android.com/apk/res/android"
   android:fromXDelta="100%"
   android:toXDelta="0"
   android:interpolator="@android:anim/decelerate_interpolator"
   android:duration="300"/>
</set>

slide_out_right.xml
<set>
  <translate xmlns:android="http://schemas.android.com/apk/res/android"
   android:fromXDelta="-100%"
   android:toXDelta="0"
   android:interpolator="@android:anim/decelerate_interpolator"
   android:duration="300"/>
</set>

This is an example that animate the fragments from left to right. You can play with xml values to change the animation direction as you want. ;)

A: You can use this animation.
<?xml version="1.0" encoding="utf-8"?>
 <set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
       android:fromYDelta="75%p"
       android:toYDelta="0%p"
       android:fillAfter="true"
       android:duration="500" />
</set>

A: Translation through code
 TranslateAnimation anim = new TranslateAnimation(0, 0, 0, 500);
 anim.setDuration(200);
 balllayout.startAnimation(anim);

balllayout are the layout which is animated.


text:
Q: How can I use the reference parameter of the inner abstract class in JAVA There are an inner interface, an inner abstract class and an inner class in the outer class.
When I call the outerMethod() method of the OuterClass,
the method of AKindBiz class can only print the contents of the list.
Why the method of abstract class (CommonKindBiz) can't print anything?
public class OuterClass {

    public void outerMethod( ) throws Exception{
        ArrayList<String> list = new ArrayList<String>();
        list.add("1111");
        list.add("2222");

        KindBiz biz = new AKindBiz();
        biz.execute(list);
    }

    public interface KindBiz
    {
        public void execute( ArrayList<String> inputList) throws Exception;

        public void preExec( ArrayList<String> inputList) throws Exception;
        public void exec( ArrayList<String> inputList) throws Exception;
        public void postExec( ArrayList<String> inputList) throws Exception;
    }

    abstract public class CommonKindBiz implements KindBiz
    {

        public void execute( ArrayList<String> inputList) throws Exception{
                System.out.println("KindBiz.CommonKindBiz.execute ### inputList1 : " + inputList ); // Nothing printed.

                this.preExec(inputList);
                this.exec(inputList);
                this.postExec(inputList);
        }

        public void preExec( ArrayList<String> inputList) throws Exception
        {
                System.out.println("KindBiz.CommonKindBiz.preExec ### inputList  : " + inputList );  // Nothing printed.
        }

        public abstract void exec( ArrayList<String> inputList) throws Exception;

        public void postExec( ArrayList<String> inputList) throws Exception
        {
                System.out.println("KindBiz.CommonKindBiz.postExec ### inputList : " + inputList );  // Nothing printed.
        }
    }

    public class AKindBiz extends CommonKindBiz
    {
        @Override
        public void exec( ArrayList<String> inputList) throws Exception
        {
                System.out.println("KindBiz.AKindBiz.exec ### inputList  : " + inputList ); // "1111", "2222" printed.
        }

    }

}

Thank you in advance.

A: System.out.prinfln("KindBiz.CommonKindBiz.execute ### inputList1 : " + inputList ); // Nothing printed.

that line seems to be the issue. It is println(). Everywhere in your code you have prinfln(). Replace those with println()
Update:
As RC and subash pointed out, your methods declare that they will take 2 parameters but you only give them 1 when you call them. You need to give them 2 or change the signature of your method.
Please use an IDE. These errors like mismatch of parameters can very easily be pointed out by IDE and with a proper description of what is wrong and how to go about fixing them.

A: I edited your code to make it compile.
I tested it, and all lines are printed. I do not believe there is a problem.


text:
Q: Understanding Recursion using flow of control through recursion calls for Merge Sort I am studying the flow of control using recursion in Merge Sort.
The particular algorithm I used is:
MergeS(ar, p, r){

 1. if p<r{
 2.    k = floor[(p+r)/2]
 3.    MergeS(ar, p , k)
 4.    MergeS(ar, k+1, r) //in the schematic diagram I have written this as mergeS(,,)
 5.    Merge(ar, p ,k, r)
 6. }
 7.}

Merge(ar, p, k, r){

 8.  n1 = k-p+1
 9.  n2 = r-p
 10. let L[1...n1+1] and R[1....n2+1] be new arrays

 11. for i=1 to n1
 12.   L[i] = ar[p+i-1]

 13. for j=1 to n2
 14.   R[j] = ar[k+j]

 15. L[n1+1] = Infinity
 16. R[n2+1] = Infinity

 17. i = 1
 18. j = 1

 19. for t = p to r
 20.   if L[i] <= R[j]
 21.     A[t] = L[i]
 22.     i = i+1
 23.   else
 24.     A[t] = R[j]
 25.     j = j+1
 30. }

MergeS(ar, k+1, r) is exactly same as merge(ar, k+1, r). I used the lowercase m in the latter only for better visual clarity in the schematic diagram.
For understanding purpose, I took an array example-- 43, 32, 56, 12, 4.
The flow of recursion calls is schematically shown below till the first call to Merge is made and the code inside that block is executed.
---1:MergeS(ar, 0, 5)-----
if(0<5):true ; set k=(0+5)/2

---Pause 1:MergeS(ar, 0, 5)-----Call-->2:MergeS(ar, 0, 2)---------
if(0<2):true ; set k=(0+2)/2

---Pause 2:MergeS(ar, 0, 2)-----Call-->3:MergeS(ar, 0, 1)---------
if(0<1):true ; set k=(0+1)/2

---Pause 3:MergeS(ar, 0, 1)-----Call-->4:MergeS(ar, 0, 0)---------
if(0<0):false

---Resume 3:MergeS(ar, 0, 1)-----Call-->5:mergeS(ar, 0+1, 5)---------
if(1<5):true ; set k=(1+5)/2

---Pause 5:mergeS(ar, 0+1, 5)-----Call-->6:MergeS(ar, 1, 3)---------
if(1<3):true ; set k=(1+3)/2

---Pause 6:MergeS(ar, 1, 3)-----Call-->7:MergeS(ar, 1, 2)---------
if(1<2):true ; set k=(1+2)/2

---Pause 7:MergeS(ar, 1, 2)-----Call-->8:MergeS(ar, 1, 1)---------
if(1<1):false

---Resume 7:MergeS(ar, 1, 2)------Call-->9:mergeS(ar, 1+1, 5)---------
if(2<5):true ; set k=(2+5)/2

---Pause 9:mergeS(ar, 2, 5)--------Call-->10:Merge(ar, 2, 3)---------
if(2<3):true ; set k=(2+3)/2

---Pause 10:Merge(ar, 2, 3)-------Call-->11:Merge(ar, 2, 2)----------
if(2<2):false

---Resume 10:MergeS(ar, 2, 3)-----Call-->12:mergeS(ar, 2+1, 5)----------
if(3<5):true ; set k=(3+5)/2

---Pause 12:mergeS(ar, 2+1, 5)------Call-->13:MergeS(ar, 5, 5 )---------
if(5<5):false

---Resume 12:mergeS(ar, 2+1, 5)-------Call-->Merge(ar, 3, 4, 5)----------
n1 = 4-3+1=2
n2 = 5-4=1

for(i = 0 to i=1):
  iteration1:
    L[0] = ar[3+0-1]= ar[2] //value 56 is assigned to ar[2]
  iteration2:
    L[1] = ar[3+1-1] = ar[3] //value 12 is assigned to ar[3]

for(j=0 to j=0):
  iteration1:
    R[0] = ar[4+0] = ar[4] //value 4 is assigned to ar[4]

x = 0;
y = 0;

for(t=0 to t=1):
  iteration1:
   /* if(L[0]<= R[0]) //56<=4:false */
   else
     ar[0] = R[0] //4 is assigned to ar[0]
     y = y+1
  iteration2:
   if(L[0]<=R[1]): //56<=infinity
     ar[1] = L[0] // 56 is assigned to ar[1]

After the preceding step, I got a value 4 in ar[0] and a value 56 in ar[2]. My guess is that this is wrong.
I need help understanding where I went wrong and and an explanation for that.

A: The indices in the algorithm in the question need to be modified in the code for simpler use. I am not saying that the algorithm is wrong, it's absolutely correct, only needs modification.
The tweaked code of Merge:
 private static void Merge(int[] ar, int p, int k, int r) {

    int n1 = k-p+1;
    int n2 = r-k;
    int[] L = new int[n1+1];
    int[] R = new int[n2+1];

    for(int i=0; i<n1; i++){
        L[i] = ar[p+i]; // p+i and not p+i-1
    }
    for(int i=0; i<n2; i++){
        R[i] = ar[k+i+1]; //k+1+i and not k+i
    }

    // Use of Tnteger.MAX_VALUE
    L[n1]=Integer.MAX_VALUE;
    R[n2]=Integer.MAX_VALUE;

    int i = 0;
    int j = 0;

    for(int t=p; t<=r; t++){ //carefully set initialization and t<=r and not simply t<r
        if(L[i]<r[j]){
            ar[t] = L[i];
            i++;
        }
        else{

              ar[t] = R[j];
              j++;
            }
        }
    }
}

The correct flow of recursion calls is shown below:(the changes from the above flow of control diagram are italicised)
---1:MergeS(ar, 0, 5)-----
if(0<5):true ; set k=(0+5)/2

---Pause 1:MergeS(ar, 0, 5)-----Call-->2:MergeS(ar, 0, 2)---------
if(0<2):true ; set k=(0+2)/2

---Pause 2:MergeS(ar, 0, 2)-----Call-->3:MergeS(ar, 0, 1)---------
if(0<1):true ; set k=(0+1)/2

---Pause 3:MergeS(ar, 0, 1)-----Call-->4:MergeS(ar, 0, 0)---------
if(0<0):false

---Break 4:MergeS(ar, 0, 0)-----Call-->5:mergeS(ar, 0+1, 1)---------
if(1<_1_):_false_ ;

---Break 5:mergeS(ar, 0+1, 1)-----Call-->Merge(ar,0,0,1)
After the execution of Merge function with parameters ar, 0, 0, 1, the elements at first two indices of the array 43 32 56 12 4 are swapped.
Maintaining a stack of function calls came in handy.


text:
Q: I can't install the HomeBrew I tried to reinstall the HomeBrew but it refuse me

 Warning: The Ruby Homebrew installer is now deprecated and has been rewritten in
Bash. Please migrate to the following command:
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

sudo: /etc/sudoers is owned by uid 502, should be 0
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin
Need sudo access on macOS (e.g. the user MyMac to be an Administrator)!
sudo: /etc/sudoers is owned by uid 502, should be 0
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin

What could I do next?

A: /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

worked for me, lmk the output with a screenshot if not.