text:
Q: Generating an array of random points in java with no duplicates I am fairly new to Java, and I want to generate an array of random (x,y) coordinates of length 'number' that contains no duplicates. x or y values can be repeated, but there must be no repeated (x,y) coordinates. The output does not have to be Points, simply some way of holding x,y values for coordinates.
I can generate an array of random points, and have tried using a Set to ensure there are no duplicate values, but have run into problems. I tried using the condition "while (set.size)" and the 'add' method which should disallow duplicates, to create an output of the correct size which contains unique points.
This is the code:
Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test=new Point();

do{
    test.x=position.nextInt(xx);
    test.y=position.nextInt(yy);
    //xx and yy are the random number limits called from another part of the code
    set.add(test);
}
while (set.size()<number);

List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();

This outputs an array of the correct length, but every element is the same. Can anyone offer any help?
Thanks

A: test points to the same variable in space everytime you loop, to fix that create a new instance inside the loop - not just once before it:
Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test;

do{
    test = new Point();
    test.x=position.nextInt(xx);
    test.y=position.nextInt(yy);
    //xx and yy are the random number limits called from another part of the code
    set.add(test);
}
while (set.size()<number);

List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();

A: You are modifying the same point object. However, since you change X and Y every time, you also changing hash code and equality of the point, so you end up placing the same object multiple times in the set. Interesting case.
try
do{
   test = new Point();
   test.x=position.nextInt(xx);
   test.y=position.nextInt(yy);
   //xx and yy are the random number limits called from another part of the code
   set.add(test);
}
while (set.size()<number);

A: Value select Randomly but not repeated
    Random rndm = new Random();
    String[] selectedNumber = new String[15];
    String[] sequanceNumber = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"};

    //*****FIRST LOOP START*****//
    for(byte a = 0; a < 15;){

        int temp = rndm.nextInt(15)+1;

        //*****SECOND LOOP START*****//
        for(byte b = 0; b < 15; b++){

            String s4 = temp+"";

            //*****CHECKING CONDITION START*****//
            if(s4.equals(sequanceNumber[b]) ){

                selectedNumber[a] = s4;

                String s1 = sequanceNumber[b];
                s1 = s1.replace(s1, " ");
                sequanceNumber[b] = s1;

                a++;

            }
            //*****CHECKING CONDITION END*****//
        }
        //*****SECOND LOOP END*****//
    }
    //*****FIRST LOOP END*****//

    //*****PRINT ALL RANDOM VALUES BUT NOT REPEATED VALUES*****//
    System.out.println(Arrays.toString(selectedNumber));


text:
Q: How to show hint only in Header in TVirtualStringtree? I want to show Hint only when user moves mouse over Header in TVirtualStringTree, not over Data nodes. Right now I can only show it Data nodes and not in Header, with this code:
procedure TForm1.FormCreate(Sender: TObject);
begin
  VirtualStringTree1.Header.Columns.Add.Text := 'Brand';
  VirtualStringTree1.Header.Columns[0].Width := 100;
  VirtualStringTree1.Header.Columns.Add.Text := 'Model';
  VirtualStringTree1.Header.Columns[1].Width := 100;

  // Set the Hint text
  VirtualStringTree1.Hint := 'Click to sort by Car brand';

  // Show Header
  VirtualStringTree1.Header.Options := VirtualStringTree1.Header.Options + [hoVisible];

  // Enable Hint in Header
  VirtualStringTree1.Header.Options := VirtualStringTree1.Header.Options + [hoShowHint];

  // Disable the Hint in Data nodes
  VirtualStringTree1.ShowHint := False;
end;

With this code there is no hint displayed anywhere, not in Data nodes and not in Header.
If I set:
// Enable Hint in Data nodes
VirtualStringTree1.ShowHint := True;

In this case the Hint is shown in Data nodes, but not in Header even if [hoShowHint] is added to Header.Options.
How can I show hint only in  Header and not in Data nodes - so user can see 'Click to sort by Car brand' only when mouse is over Header and not over Data nodes?

A: To show hints in TVirtualStringTree (in the following VST) column headers:

*

*With column editor open, select a column in the editor.

*In Object Inspector locate the Hint property and enter text

*With the VST selected look for property Header - Options - hoShowHint and set to true.

*With the VST selected look for property ShowHint and set to true.

*To show a hint in the "data" area, enter the hint text in the Hint property. To not show a hint in the "data" area, clear the Hint property.
In your code you are missing the lines where you enter the text for the column header hints:
  VirtualStringTree1.Header.Columns[0].Hint := 'Hint for first column header';

and similar for the other columns.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to run Cloud Messaging for Android sample application on Android Studio Followed ,steps given on https://developers.google.com/cloud-messaging/android/start ,but could not run successfully,giving below error while compiling.
Error:failed to find Build Tools revision 22.0.1
install.build.tools Install Build Tools 22.0.1 and sync project


text:
Q: Why when I set overflow property to hidden, then a pseudo element goes away? Here is my code:

.user_inbox{
  position:absolute;
  background-color: #fff;
  border-radius:2px;
  -o-border-radius:2px;
  -moz-border-radius:2px;
  -webkit-border-radius:2px;
  -ms-border-radius:2px;
  box-shadow: 0px 0px 6px #ccc;
  -o-box-shadow: 0px 0px 6px #ccc;
  -moz-box-shadow: 0px 0px 6px #ccc;
  -webkit-box-shadow: 0px 0px 6px #ccc;
  -ms-box-shadow: 0px 0px 6px #ccc;
  width:  310px;
  direction:ltr;
  left:53px;
  top:63px;
  border:1px solid #CCC;
  z-index:5000;
  height:100%;
  max-height:55%;
  min-height:180px;
  right: 53px;
  top: 65px;
  /* overflow:hidden; */
}
.user_inbox:after{
  background-color: #fff;
  box-shadow: -2px 2px 2px 0 rgba( 178, 178, 178, .4 );
  -o-box-shadow: -2px 2px 2px 0 rgba( 178, 178, 178, .4 );
  -moz-box-shadow: -2px 2px 2px 0 rgba( 178, 178, 178, .4 );
  -webkit-box-shadow: -2px 2px 2px 0 rgba( 178, 178, 178, .4 );
  -ms-box-shadow: -2px 2px 2px 0 rgba( 178, 178, 178, .4 );
  content: "\00a0";
  display: block;
  height: 12px;
  width:  12px;
  margin-left:18px;
  position:absolute;
  top:-5px;
  transform:rotate(135deg);
  -moz-transform:rotate(135deg);
  -ms-transform:rotate(135deg);
  -webkit-transform:rotate(135deg);
  -o-transform:rotate(135deg);
  background-color: #F7F7F7;
  right: 18px;
}

.title{
  background-color: #F7F7F7;
  display:block;
  width; 100%;
  height: 20px;
  text-align: center;
  padding: 5px;
}

  there is a title

Now please remove that comment which is around this line: overflow:hidden; (I mean please make that line uncomment) .. then suddenly that up-arrow will be vanished.
Ok well, I need both that up-arrow and this property overflow:hidden;. How can I handle that?

A: overflow:hidden is game-over for a child element trying to pop out of it's parent overflow boundary.
Instead create an inner container that will overflow (hidden)

.overflow{
  position: relative;
  overflow:hidden;
  height: inherit;
  width: inherit;
  background: #cf5;
}

.user_inbox{
  position:absolute;
  background-color: #fff;
  border-radius:2px;
  box-shadow: 0px 0px 6px #ccc;
  width:  310px;
  direction:ltr;
  left:53px;
  top:63px;
  border:1px solid #CCC;
  z-index:5000;
  height:100%;
  max-height:55%;
  min-height:180px;
  right: 53px;
  top: 65px;
}
.user_inbox:after{
  background-color: #fff;
  box-shadow: -2px 2px 2px 0 rgba( 178, 178, 178, 0.4 );
  content: "\00a0";
  display: block;
  height: 12px;
  width:  12px;
  margin-left:18px;
  position:absolute;
  top:-5px;
  transform:rotate(135deg);
  -moz-transform:rotate(135deg);
  -ms-transform:rotate(135deg);
  -webkit-transform:rotate(135deg);
  -o-transform:rotate(135deg);
  background-color: #F7F7F7;
  right: 18px;
}

.title{
  background-color: #F7F7F7;
  display:block;
  width; 100%;
  height: 20px;
  text-align: center;
  padding: 5px;
}

    there is a title

or on the "bottom" (underneath the title);

.overflow{
  position: relative;
  overflow:hidden;
  width: inherit;
  background: #cf5;
  max-height:55%;
  min-height:180px;
}

.user_inbox{
  position:absolute;
  background-color: #fff;
  border-radius:2px;
  box-shadow: 0px 0px 6px #ccc;
  width:  310px;
  direction:ltr;
  left:53px;
  top:63px;
  border:1px solid #CCC;
  z-index:5000;
  /*height:100%;
  max-height:55%;
  min-height:180px; */
  right: 53px;
  top: 65px;
}
.user_inbox:after{
  background-color: #fff;
  box-shadow: -2px 2px 2px 0 rgba( 178, 178, 178, 0.4 );
  content: "\00a0";
  display: block;
  height: 12px;
  width:  12px;
  margin-left:18px;
  position:absolute;
  top:-5px;
  transform:rotate(135deg);
  -moz-transform:rotate(135deg);
  -ms-transform:rotate(135deg);
  -webkit-transform:rotate(135deg);
  -o-transform:rotate(135deg);
  background-color: #F7F7F7;
  right: 18px;
}

.title{
  background-color: #F7F7F7;
  display:block;
  width; 100%;
  height: 20px;
  text-align: center;
  padding: 5px;
}

  there is a title


text:
Q: Keras takes long time to fit model I am running a simple mnist python script from here
It seems the program stop at this line:
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)

enter image description here
It takes about >=30 mins ...
Some people say its about GPU memory here.
I am using RTX 3080, cuda 11.2, cudnn 7.6, can someone help me?

A: RTX 3080 cards are based on the Ampere architecture for which compatible CUDA version start with 11.x, cuDNN version starts with 8.x and Tensorflow version 2.4.
You can try to upgrade cuDNN version accordingly, your issue will be resolved. For more details you can refer CuDNN support matrix.


text:
Q: sphinx raises reference exception I am using autofunction to document the following function in python:
def my_func(param1, param2):
"""
:param param1: desc1
:param param2: desc2
:raises :exc:`MyException`: desc3
"""
# the function

The problem is that I can't reference :exc:MyException inside the  raises block.


text:
Q: Android Camera2 API Image Color space I used this Tutorial to learn and try understand how to make a simple picture taking android app using the Camera2 API. I have added some snippets from the code to see if you all can help me understand some questions I have.
I am trying to find out how the image is saved as. Is it RGB, or BGR?
Is it stored in the variable bytes?
ImageReader reader = ImageReader.newInstance(width,height,ImageFormat.JPEG, 1);

@Override
public void onImageAvailable(ImageReader reader) {
      Image image = null;
      try {
            image = reader.acquireLatestImage();
            ByteBuffer buffer = image.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.capacity()];
            buffer.get(bytes);
            save(bytes);
      }

A: The image is received in JPEG format (as specified in the first line). Android uses YUV (to be more exact, YCbCr) color space for JPEG. Jpeg size is variable, it is compressed with lossy compression, and you have very little control over the level of compression.
Normally, you receive a JPEG buffer in onImageAvailable() and decode this JPEG to receive a Bitmap. You can get pixels of this Bitmap as an int array of packed SRGB pixels. The format for this array will be ARGB_8888.
You don't need JNI to convert it to BGR, see this answer.
You can access Bitmap objects from C++, see ndk/reference/group/bitmap. There you can find the pixel format of this bitmap. If it was decoded from JPEG, you should expect this to be ANDROID_BITMAP_FORMAT_RGBA_8888.

A: The variable bytes contains an entire compressed JPEG file.  You need to decompress it to do anything much with it, such as with BitmapFactory.decodeByteArray or ImageDecoder (newer API levels).
It's not an uncompressed array of RGB values in any sense.  If you want uncompressed data, the camera API supports the YUV_420_888 format, which will give you uncompressed 4:2:0 YUV data; still not RGB, though.


text:
Q: Unable to connect my postgres database using Docker I am using Docker but it does not work. I don't understand why...
Here is my docker-compose.yml :
# docker-compose.yml
version: '3'
services:
  database:
    image: "postgres" # use latest official postgres version
    env_file:
      - database.env # configure postgres
    volumes:
      - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down
volumes:
  database-data: # named volumes can be managed easier using docker-compose

Here is my database.env :
# database.env
POSTGRES_USER=admin
POSTGRES_PASSWORD=pass
POSTGRES_DB=db

I typed that and I got that:
$ docker-compose up
2021-01-15 19:57:11.683 UTC [1] LOG:  database system is ready to accept connections

So it is good.
Then that:
docker-compose run database bash

I tried that, but I got that:
$ su - postgres
$ psql --host=localhost --username=admin --dbname=db
psql: error: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

Whereas if I type in my terminal linux that:
$ sudo su -
$ su - postgres
$ psql --host=localhost --username=admin --dbname=db

I have to enter the password and it works...
Why ist that and what can I do?

A: docker-compose run launches a new container.  Within that container, localhost is that container, not the other database container that's already running.  As described in Networking in Compose, you can use the existing database container's service name from the docker-compose.yml file as a host name; so one way to connect to the database is
sudo \                         # launching containers can require root permission
docker-compose run database \  # start a new container
psql \                         # with psql as the main command
  --host=database \            # connecting to the existing database container
  --username=admin \
  --dbname=db

Assuming you've published ports: from your container
services:
  database:
    image: postgres
    ports:         # These two lines are very routine;
      - 5432:5432  # do you already have them?

then you can also connect to the database using the host's IP address and the first ports: number.  This is indistinguishable from running the database server directly on the host.  Since you make a TCP connection to connect to the database, you don't need to be any particular user to do it.
# without needing sudo at all
psql \                # launch the client directly on the host
  --host=localhost \  # connecting to a database on the same machine
  --username=admin \
  --dbname=db
# --port=5432         # needs to match first ports: number; this is the default

(You might be thinking of docker-compose exec, which is a debugging tool that can get a shell or otherwise run a command against a running container.  You shouldn't normally need that to interact with a database, though; you just need an ordinary client library or command-line tool like psql.)


text:
Q: Can I get copies of Ubuntu 13.04 on CD's to give our Free Software Club members? I want the new Ubuntu 13.04 to give to our club members for free. Can get them?
I have a club named 'Free Software Club'  with 100+ members. We discuss free software, Linux, Python and give training.

A: If you mean Ubuntu Desktop go to Download Ubuntu Desktop and burn it to CD.
For Ubuntu Server got to Download Ubuntu Server


text:
Q: I have just installed 13.04 and am confused buy the security pass-phrase/encryption options I included both the security options in my installation. The one was a pass-phrase I chose and the other was a pass phrase generated buy Ubuntu.
What are the each for? I have never had to use the code that was generated, when would I ever need to use it? I am confused.
I now have to enter a code when I turn on and my regular log in. Do I need them both?
Can one be removed and if so what is the best one to deactivate?

A: I assume you are referring to your user password and the hard disk encryption password.
The first one is required before the encrypted volume is even mounted. If you have encrypted your home (that is, the place where user files reside, your desktop and all), then you need it to access your home directory.
The second is your login password. In Ubuntu, this is necessary not only for logging in, but also for doing administrative tasks (like modifying or updating the system), remotely accessing your machine etc.
If you want to disable one of them, then I'd suggest choosing the option for automatic login. You cannot log in automatically if your home directory does not exist (almost). Go to Settings / User Accounts and set the "Automatic Login" option to "ON".

You will still need your password for accessing your machine remotely, logging in from a text console or performing administrative tasks (and this is a good thing).
Let me now shortly explain the necessity of having both passwords in general. You see, many Ubuntu machines are servers where many users can log in. Such a machine, if it has encrypted home directories, requires one password at a start-up to mount the home of all the users; then when users log in, they need to enter their respective passwords.
Furthermore, mounting the hard drive partitions is a process that happens usually once at boot time, and is completely independent from the process of user authentication at log in. For example, you can take out the disk with the home directories and attach it to another machine (or a miscreant might do it). Then you can only access the data on the hard disk with your encryption password.
P.S. That said, I don't encrypt my hard disks. I only have a small encrypted directories where I store the really sensitive data.

A: The generated one will be used when you need to mount to your home folder outside the Operating system or need to recover your home directory...because it has been encrypted. Suppose that your operating system became unstable or broken. How can you get in to the encrypted /home folder to recover your private files?
Of course with the help of the pass phrase that has been generated.


text:
Q: how to select a portion of data by a condition in Altair chart I would like to filter a portion of data I have on a condition. Is it possible with Altair?
I am using the below code to plot a chart.
alt.Chart(deliveries).mark_bar().encode(
    alt.X('batsman', sort=alt.EncodingSortField(field='sum(batsman_runs)', op='count', order='descending')),
    alt.Y('sum(batsman_runs)'),
    tooltip=['batsman', 'sum(batsman_runs)']
).properties(height=600, width=3000).interactive()

But since this has lot of data, there are many bars in my chart. I would like to restrict the bars in my chart by giving a condition like showing data for those batsman who scored above 4000 runs.
I tried using transform_filter(), but is not working with aggregate functions( I am using 'sum' here).
alt.Chart(deliveries).mark_bar().encode(
    alt.X('batsman', sort=alt.EncodingSortField(field='sum(batsman_runs)', op='count', order='descending')),
    alt.Y('sum(batsman_runs)'),
    tooltip=['batsman', 'sum(batsman_runs)']
).properties(height=600, width=3000).interactive().transform_filter(datum.sum(batsman_runs) > 4000)

Is there a way to achieve this functionality of filtering required data by giving a condition?

A: In order to reference an aggregate within a filter transform, it needs to be computed within an aggregate transform rather than in the encoding shorthand.
Something like this should work:
alt.Chart(deliveries).transform_aggregate(
    total_runs='sum(batsman_runs)',
    groupby=['batsman']
).transform_filter(
    "datum.total_runs > 4000"
).mark_bar().encode(
    alt.X('batsman:Q', sort=alt.EncodingSortField(field='total_runs', op='count', order='descending')),
    alt.Y('total_runs:Q'),
    tooltip=['batsman:Q', 'total_runs:Q']
).properties(height=600, width=3000).interactive()


text:
Q: override Magento_Catalog in 2.2 I want to override prices in catalog module.
What I did was to test on actual phtml
 vendor/magento/module-catalog/view/base/templates/product/price/final_price.phtml

It works as intended.
Now, to do it properly, I left file as it was originally and copied files and directory into my theme, made same modifications. Path where I copied files:
app/design/frontend/mysite/test/Magento_Catalog/base/templates/product/price/final_price.phtml

But changes are not being applied. is that the path I have to use?

A: Correct Folder path:

app/design/frontend/Vendor/theme/Magento_Catalog/templates/product/price/final_price.phtml

There should be no base folder in it.
Don't forget to static:content:deploy and flush:cache.

A: You need to have a theme installed and setup in the backend: from Content/Configuration, you should be able to see if the theme is aplied correctly
Only need to do static:content:deploy if you are in production mode.
I have tried out on a demo site locally installed:

*

*prices have several templates and they are used all in different use cases:

--> the one that worked for me tonight is base/templates/product/price/amount/default.phtml
--> I suggest you may copy the files under the folder base/templates/product/price and after test with your data in your catalog, you will see which templates are needed in your theme
--> I attach a screenshot of my theme folder for you to compare


text:
Q: How do I avoid "Something came up" error using ConnectivityManager.requestNetwork when the screen is off? I've got a Foreground Service (extends androidx.core.app.JobIntentService) that gets work enqueued when a push notification comes in. Its job is to connect to the Wi-Fi AP of an IoT device and download a video file. It is supposed to do this whether the screen is on or off.
In its onHandleWork method, it calls startForeground, acquires a PARTIAL_WAKE_LOCK and a WIFI_MODE_FULL WifiLock. All that has been working fine.
For API <29 I use the WifiManager to add my network and enable it, then use ConnectivityManager.registerNetworkCallback with a NetworkCallback that sniffs the network to see if its our device before doing the work. This has also been working mostly fine, videos download automatically without user interaction.
Now for API 29+, I am using WifiNetworkSpecifier to make a NetworkRequest for ConnectivityManager.requestNetwork() as described here: https://developer.android.com/guide/topics/connectivity/wifi-bootstrap. According to the docs it checks all my boxes.  It works fine when the user initiates a connection in the app.  The Bypassing user approval part seems to work as advertised after the User has pressed Connect once.  But I have two problems:

*

*If requestNetwork is invoked when the screen is off, even when it succeeds and I get the network and download the file and release the network, when the screen is turned back on, the user is met with an error message "Something came up. The application has cancelled the request to choose a device."  It really kills the magic. Does anyone know how to work around this?

*requestNetwork always causes the "Device to use with App Name" dialog to be shown, which can be disruptive and confusing when the user is not near the IoT device and there is no connection to be made.  Is there a right way to know if my device's AP is in range without involving the User?
Not sure if it's worth mentioning, but I've tried these tests with ACCESS_FINE_LOCATION and ACCESS_BACKGROUND_LOCATION granted and it didn't make a difference.


text:
Q: PHP PDO - Using prepared statements causes server error I have a PHP website that I've spend some time developing using a XAMPP localhost environment. It works great when I test it locally but unfortunately the same can not be said for when I try running it on the web server space that I've rented.
When I uploaded my finished site and tried visiting it I was greeted with 'server error 500' and after some hours of bug-hunting frustration I have pinpointed what causes the error. It turned out that executing prepared statement causes the server errors, and I have no idea why. The following code will cause a server error:
try {$db = new PDO("mysql:host=hostname;dbname=dbname", "username", "password");}
catch(PDOException $e) {echo $e->getMessage();}
$temp = $db->prepare("SELECT * FROM users WHERE username=?");
$temp->execute(["theusername"]);  //It's this line that causes the error.

The following code does the same thing but without a prepared statement; it works without any problems with the web host:
try {$db = new PDO("mysql:host=hostname;dbname=dbname", "username", "password");}
catch(PDOException $e) {echo $e->getMessage();}
$temp = $db->query("SELECT * FROM users WHERE username='username'");

Both of them work fine when run locally with XAMPP. Anyone have any idea why the web host gives me server errors if I try to use prepared statements?
Edit:
My XAMPP installation runs PHP 5.6.11 and my web host runs 5.3.29

A: As @chris85 alluded to, if you change to:
$temp->execute(array("theusername"));

this may cure the problem.


text:
Q: Check user is locked in LDAP? I need to verify if the user account in the LDAP is locked
I am using below code
const int ADS_UF_LOCKOUT = 0x00000010;
DirectoryEntry entry = new DirectoryEntry (_path, domainAndUsername, pwd);
if (((int)entry.Properties["useraccountcontrol"].Value & ADS_UF_LOCKOUT) == 1)
{
    return true;
}

But if the user account is locked , I am receiving , "Login Failed: Bad username /password"
Please Help.

A: If you want to determine if a user account is locked, then you can't use the user account information that you're checking for to determine this fact - because the user account is locked, you will be denied access.
You will not be told that the reason for being unable to log on is due to the account being locked, that would be considered excessive information disclosure.
If you want to determine if the reason for not being permitted to log on is due to the account being locked then you will need an already logged on account that can check the account lock state instead of trying from the failed connection.

A: You can use attribute lockout time for it too: it is 0 if user is not locked. (Connect to AD using administrator credentials).
DirectoryEntry _de = new DirectoryEntry (_path, domainAdmininstratorName, pwd); // get user as directory entry object
object largeInteger = _de.Properties["lockoutTime"].Value; // it's a large integer so we need to get it's value by a little bit complex way
long highPart =
            (Int32)
                largeInteger.GetType()
                    .InvokeMember("HighPart", BindingFlags.GetProperty, null, largeInteger, null);
long lowPart =
            (Int32)
                largeInteger.GetType()
                    .InvokeMember("LowPart", BindingFlags.GetProperty, null, largeInteger, null);
long result = (long) ((uint) lowPart + (((long) highPart) << 32));
if (result == 0)
{
   // account is not locked
}
else
{
 // account is locked
}


text:
Q: Asp.net Core 2.0 Razor Pages Ajax Post I am trying to just jquery ajax call to retrieve a list of users from a Razor page.
Users.cshtml.cs page:
public ActionResult OnPostList(string FirstName, string LastName,string IsActive)
{
        var data=(from s in _db.SecurityUser
                 where s.FirstName.Contains(FirstName) && s.LastName.Contains(LastName) && (IsActive=="" || (IsActive =="Y" && s.IsActive==true) || (IsActive == "N" && s.IsActive == false))
                 select s).OrderBy(s=>s.FirstName);
        return new JsonResult(data);
}

JS Call:
$.ajax({
    type: "POST",
    url: "/Security/Users?handler=List",
    data: JSON.stringify({
        FirstName: $("#txtFirstName").val(),
        LastName: $("#txtLastName").val(),
        IsActive: $("#ddActive").val()
    }),
    contentType: "application/json",
    dataType: "json",
    success: function (response) {
        var d = response.d;
        var tblBody = $("#tblUsers > tbody");
        tblBody.empty();
        $.each(d, function (i, item) {
            var modifiedDate = new Date(parseInt(item.ModifiedDate.substr(6)));
            var $tr = $('
').append(
                $('').html("Edit"),
                $('').text(item.FirstName),
                $('').text(item.LastName),
                $('').text(item.IsActive ? "Yes" : "No")
            ).appendTo(tblBody);

        });
    },
    failure: function (response) {
        alert(response.d);
    }

});

When it calls I get a 400 error back.  Trying to figure out what I am doing wrong.

A: for .net core 2.1 the solution from this blog helped
https://www.thereformedprogrammer.net/asp-net-core-razor-pages-how-to-implement-ajax-requests/
if the page does not contain form with method post, add antiforgery token @Html.AntiForgeryToken()
and you can start to fire ajax request, important part is to set headers here.
$.ajax({
                type: "POST",
                url: "/Customers?handler=Delete",
                data: { id: id },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                // AntiforgeryToken is required by RazorPages
                headers: {
                    RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
                }
            })
            .done(function () {
                alert("success");
            })
            .fail(function () {
                alert("error");
            });

A: By default, Razor Pages are designed to be protected CSRF attacks.
You must properly inject the antiforgery token into your ajax request.
See the Documentation.
In ASP.NET Core 2.0 it looks like this...
First place this code into the top of your razor view:
// At the top of your page
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@functions{
    public string GetAntiXsrfRequestToken()
    {
        return Xsrf.GetAndStoreTokens(Context).RequestToken;
    }
}

Then in your ajax request, set the token header.
$.ajax({
    type: "post",
    headers: {
        "RequestVerificationToken": '@GetAntiXsrfRequestToken()'
    },
    url: '@Url.Action("Antiforgery", "Home")',
    success: function (result) {
        alert(result);
    },
    error: function (err, scnd) {
        alert(err.statusText);
    }
});

A: Your URL formation for Ajax request is correct. One thing to note down is, Razor Pages are designed to be protected from (CSRF/XSRF) attacks. Hence, Antiforgery token generation and validation are automatically included in Razor Pages. I believe that is the problem here. Your page may have antiforgery token present on the page if you have form tag in your HTML. But you need to pass the same in your Ajax request.
First, add antiforgery token using @Html.AntiForgeryToken(), if not present.
Then, modify your Ajax request to send the same in request header.
Like,

beforeSend: function (xhr) {
       xhr.setRequestHeader("XSRF-TOKEN",
          $('input:hidden[name="__RequestVerificationToken"]').val());
},

Read this post Handle Ajax Requests in ASP.NET Core Razor Pages  to know more about making ajax request with ASP.NET Core razor pages.

A: Mark your OnPostList with HttpPost attribute and change your URL in ajax call to /Security/OnPostList

A: add     [HttpPost] in Action
  [HttpPost]
    public ActionResult OnPostList(string FirstName, string LastName,string IsActive)
    {
            var data=(from s in _db.SecurityUser
                     where s.FirstName.Contains(FirstName) && s.LastName.Contains(LastName) && (IsActive=="" || (IsActive =="Y" && s.IsActive==true) || (IsActive == "N" && s.IsActive == false))
                     select s).OrderBy(s=>s.FirstName);
            return new JsonResult(data);
    }

Used this Script in     Users.cshtml.cs

A: I had bad experiences with $.ajax, I used $.post instead.
I used validateAntiforgeryToken but its not necessary
    $("#emailSubmit").click(function () {

        $.post("/Projects/SendInvite",
            {
                Email: $("#email").val(),
                Message: $("#message").val(),
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
            }

        )
        return false;

    });

And this is net core action:
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult SendInvite(string Email, string Message)
{

        //MailTest();
        var json = new List<string>
        {
        Email,
        Message
        };
        return new JsonResult(json);
   }


text:
Q: MS Graph API for onPremisesExtensionAttributes Quick summary: I'm trying to query MS Graph to grab extensionAttribute1 from any user that I search for. I know that I can run the query below to get an entire list of Extension Attributes but I only want to call on a specific one.
https://graph.microsoft.com/beta/users/<UserUPN>?$select=onPremisesExtensionAttributes
I'm struggling to figure out how or if it's possible to query for a sub-property.
I am able to get the info that I want through the PowerShell SDK but would like to be able to grab the info from the API if possible.
Please and thanks for any guidance.

A: I think that calling something like this should work
/beta/users/<UserUPN>/onPremisesExtensionAttributes/extensionAttribute1

It will return value just for only extensionAttribute1


text:
Q: The function $\overline{z}$ has no power series expansion on a disk
I'm confused as to how to prove this theorem, would appreciate any hints.

A: If $f$ has a power series expansion in some disk centered at the origin then $f$ would be holomorphic in that disk. As $f'(0)$ does not exist this can't happen.

A: If $f(z) = \overline{z}$ had a power series expansion at $0$ with positive radius of convergence $R$, then in particular that power series converges to $z$ when $z \in (-R,R)$ is real. The real function $g(x) = x$ has only one power series at $0$, namely $x$.$^{1}$ So the original power series for $f(z)$ must have been $z$, but then $z$ is not equal to $\overline{z}$ when $z$ is not real, contradiction.

$^{1}$ This we know from real analysis. Specifically, we can show that a function can have at most one power series converging to it on an interval around $0$: if we suppose that the two power series $\sum_{i \ge 0} a_i x^i$ and $\sum_{i \ge 0} b_i x^i$ converge to the same function on an interval around $0$, then repeatedly taking derivatives we get $a_i = b_i$ for all $i$.
In particular $x$ can have at most one power series converging to it; since $x$ itself is a power series ($0 + x + 0x^2 + 0x^3 + \cdots)$, that is the only one.


text:
Q: Is this always true that if the angle in degrees is negative, its radian counterpart will also be negative and vice-versa? I want to know : if the angle in degrees is negative, will its radian counterpart will also be negative, or can it be anything(positive/negative)?
I know that 180 degrees = pi radians.
but, does -180 degrees = -pi radians? Isn't pi just a measurement?

A: Yes. As you noted, the conversion from radians to degrees is just multiplication by a positive constant, so they will always have the same sign. But in many cases, the angle $\theta$ acts the same as $\theta+360^\circ $, so in this case, a positive radian amount might act the same as a negative degree amount.


text:
Q: Javascript Toggle Display In Array I'm really new to Js, and so i'm trying to customize a wordpress plugin but without success.
I'm using a plugin for events, that groups each element into list items, and i would like to have a button on each
* that displays/hides the event description, i've looked for some Js code, but i can't make it work, already tried with for, if and forEach, and can't seem to make it work.
Right now it's working, but instead of toggling each element, when you press the button it toggles all the descriptions.
Any help?

 Program Title

 00:00

<button onclick="toggle_visibility()">Description</button>

show description is here

 Program Title

 00:00

<button onclick="toggle_visibility()">Description</button>

show description is here

 Program Title

 00:00

<button onclick="toggle_visibility()">Description</button>

show description is here

 Program Title

 00:00

<button onclick="toggle_visibility()">Description</button>

show description is here

```

A: It affects all the descriptions because they all have the same class name. The toggle visibility function literally toggles all of them at once. If you want to make it more specific, you have to come up with unique ids for every description. For example;

Description here

If you have 5 divs, then make sure the id="description" are different. They could be description1 description2, etc. And then, for their corresponding button, just put:
<button onclick="toggle_visibility("description1")">Description

You have to change the description1 to description2 and so on for every button.
And your toggle_visibility function:
function toggle_visibility(id) {
    var thediv = document.getElementById(id);
    thediv.style.display = (thediv.style.display == 'none') ? 'block' : 'none';
}


text:
Q: Bind data to component with Vuex I'm new to vue.js and I'm trying to use vuex. Here is my issue:
I have a list of articles (which is a component) linked with a store with v-for="article in articles and a computed property:
computed: {
        articles() {
            return this.$store.state.articles
        }
    }

So here is the data in my store:
 state: {
    articles: [{
        title: "Article 1",
        id: 1,
        description: "Article 1",
      }, {
        title: "Article 2",
        id: 2,
        description: "Article 2",
      }
     }]
}

When I click on an article, I want it to redirect to the article page template (which is a component) with <router-link :to="{path: '/article/'+article.id}"></router-link>.
What I'm trying to do is bind the data of the correct article in the articlePage template.
The issue is that if I apply the same computed property to my articlePage.vue component with a v-for, I will display all of the article on the same page. I would like to display only the matching id component.
How can I do that?
Thank you for your time :)

A: From your comments I understand that you use vue-router module
So in your routes.js (or structure ) your must have something like this
const router = new VueRouter({
   routes: [
    { path: '/articles', component: articlesPage },
    { path: '/article/:id', component: articlePage }
  ]
})

Then in your articlePage component you can extract ":id" like this:
this.$route.params.id

because vue-router gives you access to the object $route with methods and properties
Check more here https://router.vuejs.org/guide/essentials/dynamic-matching.html
then you can use it to search the articles array and find the data and present them
e.x.
computed:{
   selectedArticle(){
     var article_id = this.$route.params.id;
     var articles = this.$store.state.articles;
     var article = null;
     for(var a=0;a<articles.length;a++){
         if(articles[a].id == article_id ){
           article = articles[a];
           break;
         }
     }
     return article;
   }
}


text:
Q: expo-screen-orientation ScreenOrientation listener not firing I'm trying to rotate the Screen on button clicks using expo-screen-orientation.
I can rotate the Screen from PORTRAIT-UP to LANDSCAPE-RIGHT, but not viceversa because the current Orientation is always PORTRAIT-UP even when the screen is on landscape.
These are my issues:

*

*ScreenOrientation.addOrientationChangeListener() is not firing.

*ScreenOrientation.getOrientationAsync() always returns 1 (PORTRAIT-UP) even if the actual orientation is either LANDSCAPE-RIGHT or LANDSCAPE-LEF

*ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP) doesn't work because of the above point I guess.

Please see my code below.
  useEffect(() => {
    const subscription = ScreenOrientation.addOrientationChangeListener((evt) => {
      console.log("firing");
      setOrientation(evt.orientationInfo.orientation);
    });

    return () => {
      ScreenOrientation.removeOrientationChangeListener(subscription);
    };
  }, []);

const rotateUp = async () => {
    await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP); //This should rotate from LANDSCAPE_RIGHT to PORTRAIT_UP, but it doesn't work because it thinks the screen is already on PORTRAIT_UP
  };

  const rotateLeft = async () => {
    await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE_RIGHT); //This works and rotate the Screen to LANDSCAPE_RIGHT
    const currentOrientation = ScreenOrientation.getOrientationAsync(); //This return 1 (PORTRAIT_UP)
    console.log(currentOrientation);
  };

Does this library works only in Expo managed apps?
I couldn't find useful documentation on this, some help would be appreciated!


text:
Q: sql query to perform for each unique identifier So I have a table like this:
________________________________________
phone_number  |  phone_vendor  |  status

67834         | A              | OPEN
23836         | B              | OPEN
87483         | C              | CLOSED
72377         | A              | OPEN
63637         | B              | OPEN

I need to find the count of phone_numbers of each unique phone_vendor in OPEN status, something like:
A | 2
B | 2
C | 0

using group by I don't get the vendors whose OPEN count is already exhausted (as C in above example)
What could be a suitable query?
Also, I can't use CASE as there will be multiple vendors.
Query attempt:
SELECT status, count(phone_number) AS count
FROM phone_number_table
WHERE status = 'OPEN'
GROUP BY phone_vendor, status

A: Try this:
SELECT SUM(CASE WHEN status = 'OPEN' THEN 1 ELSE 0 END) AS count, phone_vendor
FROM yourtable
Group by phone_vendor

SQL Demo: http://sqlfiddle.com/#!9/17e753/4

A: You could check for status and sum
  select phone_vendor, sum(case status when 'OPEN' then 1 else 0 end) my_count
  from my_table
  group by phone_vendor


text:
Q: delphi in vista i have one problem
when i run my program in delphi7
have one error message

"unknown table type - permission denied - file:c:\PDOXURS.NET   direcory C:\"

i dont know of make
tk for one answer

A: On Vista, normal users do not have write-access to c:\, so you get the Permission Denied error message when trying to use Paradox since it needs to write to some files.
Two Good Options:

*

*Change the Net Dir in the BDE Admin to a path the user has access to

*

*BDE Admin

*Configuration

*Drivers => Native Paradox

*Change Net Dir

*Apply

*Adjust the access rights on the required files on c:\ to allow the user access

and one bad option:

*

*Run the program as Administrator

A: Something else to be aware of is the virtual store.  It may contain a copy of your BDE configuration, which you will probably want to delete.  I'm currently not in front of a vista machine but the path is something like \users\username\appdata\local\virtual store  (or something similar).  There will then be a subdirectory for program files\common files\borland shared\bde - you will want to delete the files in here.


text:
Q: Try/except not working with twisted starttls given cert/key mismatch So my twisted mail receiver is working nicely. Right up until we try to handle a case where the config is fubarred, and a mismatched cert/key is passed to the certificate options object for the factory.
I have a module, custom_esmtp.py, which includes an overload of ext_STARTLS(self,rest) which I have modified as follows, to include a try/except:
    elif self.ctx and self.canStartTLS:
            try:
                self.sendCode(220, 'Begin TLS negotiation now')
                self.transport.startTLS(self.ctx)
                self.startedTLS = True
            except:
                log.err()
                self.sendCode(550, "Internal server error")
                return

When I run the code, having passed a cert and key that do not match, I get the following call stack:
Unhandled Error
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 220, in _dataReceived
    rval = self.protocol.dataReceived(data)
  File "/usr/local/lib/python2.7/site-packages/twisted/protocols/basic.py", line 454, in dataReceived
    self.lineReceived(line)
  File "/usr/local/lib/python2.7/site-packages/twisted/mail/smtp.py", line 568, in lineReceived
    return getattr(self, 'state_' + self.mode)(line)
  File "/usr/local/lib/python2.7/site-packages/twisted/mail/smtp.py", line 582, in state_COMMAND
    method('')
--- <exception caught here> ---
  File "custom_esmtp.py", line 286, in ext_STARTTLS
    self.transport.startTLS(self.ctx)
  File "/usr/local/lib/python2.7/site-packages/twisted/internet/_newtls.py", line 179, in startTLS
    startTLS(self, ctx, normal, FileDescriptor)
  File "/usr/local/lib/python2.7/site-packages/twisted/internet/_newtls.py", line 139, in startTLS
    tlsFactory = TLSMemoryBIOFactory(contextFactory, client, None)
  File "/usr/local/lib/python2.7/site-packages/twisted/protocols/tls.py", line 769, in __init__
    contextFactory = _ContextFactoryToConnectionFactory(contextFactory)
  File "/usr/local/lib/python2.7/site-packages/twisted/protocols/tls.py", line 648, in __init__
    oldStyleContextFactory.getContext()
  File "/usr/local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 1429, in getContext
    self._context = self._makeContext()
  File "/usr/local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 1439, in _makeContext
    ctx.use_privatekey(self.privateKey)
OpenSSL.SSL.Error: [('x509 certificate routines', 'X509_check_private_key', 'key values mismatch')]

Line 286 of custom_esmtp.py is the self.transport.startTLS(self.ctx). I've looked through all the twisted modules listed in the stack, at the quoted lines, and there are no other try/except blocks.... So my understanding is that the error should be passed back up the stack, unhandled, until it reaches my handler in custom_esmtp.py? So why is it not getting handled - especially since the only except I have is a "catch all"?
Thanks in advance!

A: If you want this error to be caught, you can do:
from OpenSSL import SSL

# ...

try:
    # ...
except SSL.Error:
    # ...

Perhaps the syntax changes a bit. I can't check because I don't use this precise package, but the idea is that you have to declare the import path of the exceptions you want to catch.


text:
Q: How do i push objects into the same array? I am having trouble applying objects to my array, every time i push the object into the array a new array is created.
I have made some edits at the bottom of the question.
I need an array of objects to look like this
var arr = [{name: 'bent', town: 'kansas'}, { name:'benny', town:'vegas'}];

Insted mine looks like this
var arr = [0:{name: 'bent', town: 'kansas'}1:{ name:'benny', town:'vegas'}]

PHP
$stmt = $dbCon->prepare("SELECT ctc_coins_name, "
        . " ctc_coins_town "
        . " FROM ctc_coins ");
$stmt->execute();
$result_coins = $stmt->fetchAll();

$coins = [];
foreach ($result_coins as $result) {
    $coins[] = [
        'name' => $result['ctc_coins_name'],
        'twon' => $result['ctc_coins_town]
    ];
}
echo json_encode($coins);

Javascript
function update_local_coins() {
    var http = new XMLHttpRequest();
    var url = "pages/ajax/getCoins.php";
    http.open("POST", url, true);
    http.onreadystatechange = function () {
        if (http.readyState === 4 && http.status === 200) {
            if (this.responseText) {
                jsonObj = JSON.parse(this.responseText);
                console.log(jsonObj);
                var coins = [];
                for (var l in jsonObj) {
                    coins.push(jsonObj[l]);
                }
                console.log("COINS");
                console.log(coins);
            } else {
                alert("Noobs");
            }
        }
    };
    http.send();
}

I have tried this with no luck
coins.concat(jsonObj[l]) 'returns empty array'
coins.push.apply(coins, jsonObj[l]) 'returns empty array'
coins.push(jsonObj[l]) 'returns the example array'

EDIT:
console.log(jsonObj);
(13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0
:
{name: "Bitcoin", usd: "5622.73", btc: "1.00000000"}
1
:
{name: "Ethereum", usd: "338.81", btc: "0.06013390"}
2
:
{name: "Litecoin", usd: "58.65", btc: "0.01040990"}
3
:
{name: "Dash", usd: "307.31", btc: "0.05454360"}
4
:
{name: "Golem", usd: "0.21", btc: "0.00003759"}
5
:
{name: "NEM", usd: "0.21", btc: "0.00003674"}
6
:
{name: "Neutron", usd: "0.15", btc: "0.00002686"}
7
:
{name: "DigiByte", usd: "0.01", btc: "0.00000175"}
8
:
{name: "Siacoin", usd: "0.00", btc: "0.00000074"}
9
:
{name: "Linda", usd: "0.00", btc: "0.00000005"}
10
:
{name: "LiteDoge", usd: "0.00", btc: "0.00000001"}
11
:
{name: "ArcticCoin", usd: "0.05", btc: "0.00000922"}
12
:
{name: "NoLimitCoin", usd: "0.13", btc: "0.00002321"}
length
:
13
__proto__
:
Array(0)

EDIT: php echo json
[{"name":"Bitcoin","usd":"5622.73","btc":"1.00000000"},{"name":"Ethereum","usd":"338.81","btc":"0.06013390"},{"name":"Litecoin","usd":"58.65","btc":"0.01040990"},{"name":"Dash","usd":"307.31","btc":"0.05454360"},{"name":"Golem","usd":"0.21","btc":"0.00003759"},{"name":"NEM","usd":"0.21","btc":"0.00003674"},{"name":"Neutron","usd":"0.15","btc":"0.00002686"},{"name":"DigiByte","usd":"0.01","btc":"0.00000175"},{"name":"Siacoin","usd":"0.00","btc":"0.00000074"},{"name":"Linda","usd":"0.00","btc":"0.00000005"},{"name":"LiteDoge","usd":"0.00","btc":"0.00000001"},{"name":"ArcticCoin","usd":"0.05","btc":"0.00000922"},{"name":"NoLimitCoin","usd":"0.13","btc":"0.00002321"}]

A: Your objective was to get the array of objects received in the AJAX response.
As I said in my first comment to your question, you already got this in this line
jsonObj = JSON.parse(this.responseText);

Now, you seem to think that you have received an object(with numbers being fields, and the objects being values). But this is just how console.log behaves :)
As for your final question regarding a way to confirm that is indeed an array, all you need to do is check the string representation of the result of JSON.parse() i.e use JSON.stringify. Below example demonstrates this.
EDIT: Have updated code snippet with demonstration of findMatches() posted in the comment.

        var s = '[{"name":"Bitcoin","usd":"5622.73","btc":"1.00000000"},{"name":"Ethereum","usd":"338.81","btc":"0.06013390"},{"name":"Litecoin","usd":"58.65","btc":"0.01040990"},{"name":"Dash","usd":"307.31","btc":"0.05454360"},{"name":"Golem","usd":"0.21","btc":"0.00003759"},{"name":"NEM","usd":"0.21","btc":"0.00003674"},{"name":"Neutron","usd":"0.15","btc":"0.00002686"},{"name":"DigiByte","usd":"0.01","btc":"0.00000175"},{"name":"Siacoin","usd":"0.00","btc":"0.00000074"},{"name":"Linda","usd":"0.00","btc":"0.00000005"},{"name":"LiteDoge","usd":"0.00","btc":"0.00000001"},{"name":"ArcticCoin","usd":"0.05","btc":"0.00000922"},{"name":"NoLimitCoin","usd":"0.13","btc":"0.00002321"}]';

        var arrayOfObjects = JSON.parse(s);

        var stringifiedArray = JSON.stringify(arrayOfObjects);

        document.getElementById("op").innerText = stringifiedArray;

        function findMatches(arr, searchString) {
            const matches = [];
            arr.forEach(obj => {
                for(const key in obj) {
                if (obj[key].includes(searchString)) {
                    matches.push(obj[key]);
                }
            }
        });
            return matches;
        }

    var matches = findMatches(arrayOfObjects, "Lite");

    document.getElementById("mr").innerText = JSON.stringify(matches);


text:
Q: Float value in SLIM query table comparison I am fairly new to Fitnesse. I am using the Subset Query Table. It works fine except when I have to compare a float value. Is there a any way I can compare the values to certain level of accuracy ?
For instance the test should pass when I compare 4.12 to 4.1234. But right now, it looks like it is making a string comparison and it fails. Is there anyway I can override the validation part ?

A: You can use the tilde character to mean 'approximately equal to', e.g. ~=4.12
See http://fitnesse.org/FitNesse.UserGuide.SliM.ValueComparisons for more details.

A: To achieve approx comparison of Double and Float values, I have override the fixture class as the following:
public class ApproxColumnFixture extends ColumnFixture {

    @Override
    public void check(Parse cell, TypeAdapter a) {
        if (a.type == Double.class) {
            super.check(cell, new ApproxDoubleAdapter(a));
        } else if (a.type == Float.class) {
            super.check(cell, new ApproxFloatAdapter(a));
        } else {
            super.check(cell, a);
        }
    }
}

The two TypeAdapter class use both relative value epsilon and absolute value precision for comparison.  The precision is detected from the expected input, so that 23.099 has precision 0.001. They also expect special values, such as "nan" for NaN, and "inf" for +/-Infinitive.  Here is one example:
public class ApproxDoubleAdapter extends TypeAdapter {
    public final Double ZERO = new Double(0.0);

    private final double epsilon;
    private int precisions = -1;

    public ApproxDoubleAdapter(final TypeAdapter classDoubleAdapter, double epsilon) {
        this.target = classDoubleAdapter.target;
        this.fixture = classDoubleAdapter.fixture;
        this.field = classDoubleAdapter.field;
        this.method = classDoubleAdapter.method;
        this.type = classDoubleAdapter.type;
        this.isRegex = classDoubleAdapter.isRegex;

        this.epsilon = epsilon;
    }
    public ApproxDoubleAdapter(final TypeAdapter adapt) {
        this(adapt, 0.0001);
    }

    public Object parse(String s) throws Exception {
        if ((s == null) || s.equals("null")) {
            return null;
        }
        if (s.equals("0")) {
            return ZERO;
        }
        if (s.equals("nan")) {
            return Double.NaN;
        }
        if (s.equals("inf")) {
            return Double.POSITIVE_INFINITY;
        }
        precisions = s.indexOf(".");
        if (precisions >= 0) {
            precisions = s.length() - 1 - precisions;
        }
        return new Double( Double.parseDouble(s) );
    }

    public boolean equals(Object a, Object b) {
        if (a == null) {
            return (b == null);
        }
        if (b == null) {
            return (a == null);
        }
        if ((a.getClass() != Double.class) || (b.getClass() != Double.class)) {
            return false;
        }
        double aV = (Double) a;
        double bV = (Double) b;
        if (Double.isNaN(aV)) {
            return Double.isNaN(bV);
        }
        if (Double.isNaN(bV)) {
            return Double.isNaN(aV);
        }
        if (Double.isNaN(aV)) {
            return Double.isNaN(bV);
        }
        if (Double.isInfinite(aV)) {
            return Double.isInfinite(bV);
        }
        if (Double.isInfinite(bV)) {
            return Double.isInfinite(aV);
        }
        final double diff = Math.abs(aV - bV);
        if (diff <= Math.abs(aV + bV) * epsilon) {
            return true;
        }
        if (precisions > 0) {
            return diff <= Math.pow(10, precisions);
        } else if (aV == 0.0) {
            return diff < epsilon;
        } else {
            return false;
        }
    }
}


text:
Q: Compass Extension equivalent of config.rb At the end of my Compass config.rb I have a little snippet that generates a random number. This works. And I can get it working when I have the snippet there and the Sass in my projects Sass folder.
I'm trying to create an extension out of this functionality, But I don't know where to put the code so that my mixins in extensions/my-extension/stylesheets/, and hopefully any Sass file that imports the extension have access to it.
I've tried extensions/my-extension/lib/whatever.rb but I'm still getting errors. I've also tried putting the snippet in config.rb, but keeping the mixins/Sass in the extension, but that also doesn't work.
In both of these cases the error I'm getting is that Undefined operation: "random() times 1%".)
Where is the place analogous to the end of the config.rb, but for extensions?
Do I need to import it into my extensions' Sass somehow?

A: Check out this tutorial, particularly the subsection of "Advanced Layout Options" entitled "Library File Location". It lists three different options:

*

*my_extension/compass_init.rb

*my_extension/lib/my_extension.rb (NOTE: You must use this one if you're distributing as a rubygem.)

*my_extension/my_extension.rb

Adding your random number function to any of these files should work.


text:
Q: Displaying state list in JSX I have some simple code:
class App extends React.Component {
  state = {
    letters: ["a", "b", "c"]
  };

  addLetter = () => {
    const { letters } = this.state;
    letters.push("d");
    this.setState({ letters });
  };

  render() {
    return (

        <button onClick={this.addLetter}>Click to add a letter</button>

letters: {this.state.letters}

    );
  }
}

render(<App />, document.getElementById("root"));

Working example here.
When I click the button, the letter 'd' should be added to the letters in state. This works as intended. However, the letters do not update on the page as one would expect when state changes.
It's worth noting that:

letters: {this.state.letters.reduce((a, l) => a + l, "")}

or:

letters: {this.state.letters.toString()}

do update the page as expected.
Why is this?

A: You need to replace the letter's state (the array), instead of mutating it (working example). According to the react docs: Do Not Modify State Directly.
When you're converting the array to a string, the current string is different from the previous string because strings are immutable. The array however stays the same array even if you add another item to it.
Example:

const a = [1, 2, 3];
const strA = a.toString();
a.push(4);
const strB = a.toString();

console.log(a === a); // true
console.log(strA === strB); // false

Solution: create a new array from the old one.
addLetter = () => {
  const { letters } = this.state;
  this.setState({ letters: [...letters, 'd'] });
};

A: You have got an answer though. Would like to explain it a bit further.
You are basically not changing the state ever. And react only detects the changes in state. Now tricky part is that you might be thinking that you are updating the array object and hence changing the state but that's not true. The original array reference is never changed in state and hence no change. So, to solve this in es6 you could use ... operator as follows in your addLetter declaration.
addLetter = () => {
    const { letters } = this.state;
    letters.push("d");
    this.setState({ letters:[...letters] });
  };

... operator basically clones the original object and is a short hand operator from es6.
You could use clone method as well e.g. Object.assign.
Hope it helps!

A: I've forked and fixed your code here: https://codesandbox.io/s/ywnmr47q8z
1) You have to mutate the new state
2) you have to call .join("") to build string from array. now it is working


text:
Q: Using ActionLInk from inside a helper template cshtml page Why doesn't Html.ActionLink work in the below code?  This is a page in the app_code folder,
that I am trying to call from index.cshtml
LogOnUserControl.cshtml
    @helper DisplayUserControl(){
            if (Request.IsAuthenticated ) {
        Welcome @User.Identity.Name!
        [ {@Html.ActionLink("","","")}  ]

    }
    else {
        [{@Html.ActionLink("","","") }]

    }
    }

this is the line of code from index.cshtml.  The call itself works, if I remove the Html.ActionLink statements the site loads fine.  Is it that you can't use them in a nested page like this? How else can I generate dynamic links?
index.cshtml
@LogOnUserControl.DisplayUserControl()

A: What's the idea with this action links? Why are you passing empty strings as arguments? I suppose you want to generate SignIn, SignOut links, don't you?
Also if you want to use HTML helpers inside shared helpers that you put in the App_Code folder you will need to pass them as arguments because they are not available:
@using System.Web.Mvc.Html

@helper DisplayUserControl(System.Web.Mvc.HtmlHelper html) {
    if (html.ViewContext.HttpContext.User.Identity.IsAuthenticated) {

            Welcome

                @html.ViewContext.HttpContext.User.Identity.Name

            !

        [@html.ActionLink("SignOut", "Login")]
    }
    else {
        [@html.ActionLink("SignIn", "Login")]
    }
}

and to call the helper:
@LogOnUserControl.DisplayUserControl(Html)

Personally I never use such helpers (the ones you put in the App_Code folder). Can't see any use for them when you have partial views, editor/display templates and Html.Action helpers.
So for example you could define a partial (~/Views/Shared/_LogOnUserControl.cshtml):
@if (User.IsAuthenticated) {

        Welcome

            @User.Identity.Name

        !

    [@Html.ActionLink("SignOut", "Login")]
}
else {
   [@Html.ActionLink("SignIn", "Login")]
}

which you would include in your layout:
@Html.Partial("_LogOnUserControl")


text:
Q: How to correctly write a merge sort algorithm with the use of a temporary list I'm writing a merge sort with recursion, but it doesn't print out the correct message, however when I'm hand writing through the code, it seems right. could anyone help me to find out why?
def mergeSort1(arr):

  if len(arr)<=1:  #base case
    return arr
  else :
    breakN =len(arr)//2
    left = arr[:breakN]
    right = arr[breakN:]
    mergeSort1(left)
    mergeSort1(right)
    i=j=0
    temp = []
    while i<len(left) and j<len(right):
      if left[i] <= right[j]:
        temp.append(left[i])
        i += 1
      else:
        temp.append(right[j])
        j += 1
    while i < len(left): # extend the list in case there's any missing
      temp.append(left[i])
      i += 1
    while j < len(right):
      temp.append(right[j])
      j += 1
    #print(temp)
    return temp

code to get the result:
arr = [9,7,3,6,2]
mergeSort1(arr)
print(arr)

and the result:
[9, 7, 3, 6, 2]

I then looked up at the code from other people, I found the problem might lie in temp[], so I added a print(temp) at the back of else statement(see above code), and it prints out the following:
[7, 9]
[2, 6]
[3, 6, 2]
[3, 6, 2, 9, 7]

It shows the first and second answer is what I want, could anyone please help me find out why ?

A: Since you are not modifying the input list arr in-place and are returning a new list temp instead, you should assign the returning value of the function to a variable.
Change:
mergeSort1(left)
mergeSort1(right)

to:
left = mergeSort1(left)
right = mergeSort1(right)

And change:
mergeSort1(arr)
print(arr)

to:
print(mergeSort1(arr))

Alternatively, you can modify the input list in-place, in which case you can assign temp back to arr in-place using slice assignment.
Change:
return temp

to:
arr[:] = temp


text:
Q: Javascript scrolling menu that starts only after a certain ways down the page I want a scrolling menu that begins at a certain part of the page (like under the header), but stays there till you scroll down and it hits the top of your browser window, then follows you down the rest of the page.
Anyone have any clue how to do this? I can't find it anywhere on the net. I've seen others similar to it, but none that move to the top of the window.
There's a great example on gmail when you are viewing an email. The toolbar stays at the top of the email box, but once you scroll past the email box, it follows you down the page.
I know that position:absolute;top:0; will make it stay at the top without the fluid motion (I hate it because it looks sloppy).
** edit **
I really only need to know how to detect that the menu div is at the top of your page. I can do a mock thing where if you scroll down how ever far the menu div is, it will start scrolling down, but I'd rather actually get whether the menu div is past the browser window or not.

A: It's a mixed position of fixed and absolute, you will handle.scroll event and switch between that.
You can find an example here
Creating a floating box which stays within a div


text:
Q: Why is module.exports=router is needed? In my node.js server conf file, I set app.use('/user', user.js), which maps /user route to a user.js file.
Then I create subrouting in my user.js file to handle my get or post requests.
My question is: what's the responsibility of module.exports=router at the end of this file?
If I remove it, routing stops working, so I don't understand if it is here to tell my server conf file that there are sub paths in user.js?
var express = require('express');

var user = require('../../models/user');
var db = require('../../models/index');

var router = express.Router();

router.get('/addUser',function (req, res, next) {
  db.user.create(req.body)
    .then(user => res.json({

      data: user,

    }))
    .catch(error => res.json({
      error: true,
      data: [],
      error: error
  }));
});
module.exports = router;

A: When you do
var user = require('../../models/user');

the user object would get whatever is being exported from the module in user.js. So in user.js, the module.exports=router is mapping a router and all logic that's required to map /user (along with the right callbacks etc...)
If you remove it, your require statement can't acquire an exported object from that module, which is why it would fail. Your user object will be nullified effectively.
Check out here for more info: https://www.tutorialsteacher.com/nodejs/nodejs-module-exports

A: A router cannot listen(PORT) for requests on its own. The router is useful when you have lots of routes. It's useful for separating your app into multiple modules.
const app = express()
app.listen(port)

app is listening for the requests(not the Router) while your user.js is just a separate js file with some codes.
In module.export ,module is a variable that represents the current module and export is an object. Anything you assign to the module.exports will be expose as a module.
copied: Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node.js application.
Once you do module.export = Router Now you have a newly created module. In nodeJs, you need to require a module before use it. const user = require('./user.js') will do that process. Once you require the node module into your app, you need to tell it to execute by app.use('/' , user)
Or you can do something like below too
in your user.js file,
var user = require('../../models/user');
var db = require('../../models/index');

module.export = (app) =>{
  app.get('/addUser',function (req, res, next) {
  db.user.create(req.body)
    .then(user => res.json({

      data: user,

    }))
    .catch(error => res.json({
      error: true,
      data: [],
      error: error
  }));
 });
}

in your main index.js,
const app = express()
require('./user.js')(app)


text:
Q: Running a linux command in Dockerfile throwing error This is my Dockerfile content and it keeps throwing me error in running this statement. Any idea what am I doing wrong. I just want to dump ENV VARS into a file for React build on the container.
FROM node:12
WORKDIR /usr/src/app
COPY . .
RUN printenv | grep REACT_APP_ > client/.env
# RUN ["printenv", "|", "grep", "REACT_APP_", ">", "client/.env"]
RUN npm run setup
RUN npm run build:all

EXPOSE 3005
CMD [ "npm", "run", "start:prod" ]

Error: ERROR: Service '<name>' failed to build: The command 'printenv | grep REACT_APP_ > client/.env' returned a non-zero code: 1
I have spent many hours with no luck. Help appreciated.

A: So there's a couple things to consider:

*

*Make sure the client dir exists.  It doesn't come in the node:12 image by itself

*Make sure the env has a variable that will allow the grep REACT_APP_ to find something.  If it does not, grep will return 1 and the docker image build will halt.  1 is normal return code when grep finds nothing, so it's not an error (and thus nothing more is printed).  But the docker build treats it as an error since it's nonzero, and thus the build stops.

Also to read on EXIT CODES on man grep page,

EXIT STATUS Normally the exit status is 0 if a line is selected, 1 if
no lines were selected, and 2 if an error occurred.

Here's a test I did that passes (slightly modified, just based on the considerations above):
FROM node:12
WORKDIR /usr/src/app
COPY . .
RUN mkdir client
ENV REACT_APP_1 1
RUN printenv | grep REACT_APP_ > client/.env
RUN cat client/.env

The output I get is this:
$ docker build -t test .
Sending build context to Docker daemon  2.048kB
Step 1/7 : FROM node:12
 ---> 28faf336034d
Step 2/7 : WORKDIR /usr/src/app
 ---> Running in 753293fa6257
Removing intermediate container 753293fa6257
 ---> 3a04798b1b9f
Step 3/7 : COPY . .
 ---> 3dd0d465a6e2
Step 4/7 : RUN mkdir client
 ---> Running in d513df2a0a34
Removing intermediate container d513df2a0a34
 ---> d46aa5200ae7
Step 5/7 : ENV REACT_APP_1 1
 ---> Running in af81940a90fb
Removing intermediate container af81940a90fb
 ---> 6169ad694a4d
Step 6/7 : RUN printenv | grep REACT_APP_ > client/.env
 ---> Running in 365020eeb2e5
Removing intermediate container 365020eeb2e5
 ---> b6ef574c48c8
Step 7/7 : RUN cat client/.env
 ---> Running in a6a69d6ba6c2
REACT_APP_1=1
Removing intermediate container a6a69d6ba6c2
 ---> 0814306133f0
Successfully built 0814306133f0
Successfully tagged test:latest


text:
Q: Saved state exception I'm getting the following exception with my app.  I believe this happens when the user leaves the app for a long time then returns to it.  I am unable to replicate it however it is showing up in my crash logs a lot.  I have no idea why this is happening so any suggestions are greatly appreciated.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.MyActivity}: java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2237)
at android.app.ActivityThread.access$600(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4974)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
at java.util.ArrayList.get(ArrayList.java:306)
at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1764)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:198)
at com.myapp.MyActivity.onCreate(MyActivity.java:235)
at android.app.Activity.performCreate(Activity.java:4538)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2158)
... 11 more

Line 235 is the following:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    // line 235

My onSaveInstanceState() is pretty simple:
@Override
public void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);

    state.putInt("id1", id1);
    state.putInt("id2", id2);
    state.putInt("id3", id3);
    state.putInt("id4", id4);

}

A: I ran into this same problem, I believe it a bug with android. Take a look at this thread for a possible solution http://code.google.com/p/android/issues/detail?id=22404

A: I got the exact same problem, I followed the advice given in Kenny's link:
I used the following:
FragmentManager.enableDebugLogging(true);

This will display in the logs all the calls on the FragmentManager (fragments added, deleted, hidden etc.).
It allowed me to see what was wrong in my case, one of the fragments in my app was sometimes not saved properly in the instance and its content was null.
Then the crash happened with the same error log when the app tried to restore this null fragment from the instance.
In my case this fragment was a little special and created automatically. To be sure not to get the error again, I removed the fragment from the FragmentManager before exiting the Activity.

A: I had the same problem, occurring with orientation changes, but it only happened with older Android versions (4.0.4), newer versions like 4.4.2 were fine. I want to share with you how I fixed it.
As Kenny and Yoann suggested, I used
FragmentManager.enableDebugLogging(true);

and found out that too much removing has been done. I had to remove ft.remove(df) from my code and now it's fine with both versions mentioned above. This is my code:
if (savedInstanceState != null) {
    final FragmentTransaction ft = getFragmentManager().beginTransaction();
    final DialogFragment df = (DialogFragment) getFragmentManager().findFragmentByTag("tag");
    if (df != null) {
        df.dismiss();
        // ft.remove(df);
        frag = new MyDialogFragment();
        frag.show(getFragmentManager(), "tag");
    }
    ft.addToBackStack(null);
    ft.commit();
}

For the sake of completeness, this is what I have done in onSaveInstanceState(final Bundle outstate):
if (frag != null) {
    getFragmentManager().putFragment(outState, "tag", frag);
}


text:
Q: extract BNF grammar rules from yacc file I have a yacc file describing a certain language for which i am developing an Editor using IMP (eclipse project).I am using LPG as a parser generator, so I needed to extract a BNF rules from my yacc file. the yacc file i received contains rules and actions. However, I wanted to extract only the rules of the grammar description to be used in LPG. one way of doing this is by manually extracting the rules and reformatting it to BNF syntax (or may be writing a program to convert it to the way i want it). I was wondering if there is an automated way of doing this. I read in some blogs that bison could help but i couldn't exactly find the appropriate commands. does anybody knows how to deal with this problem.
I can't really post the yacc file i have since it is confidential. but i could give an example as follows
argExprList:
       assignExp
          {
            // some rules here
          }
        | assignExpList ',' assignExp
            {
              //some other rules here
            }
        ;

what i wanted it to be converted to is simply like
argExpList ::= assignExp|assignExpList ',' assignExp

A: Bison can help, if you're prepared to do some post-processing.
If you run bison with the -v option, it will produce a file called filename.output (where filename is the basename of the .y file); that file contains a copy of the grammar and a description of every state. The grammar does not have actions, and it has one production per line. But you'll need to do some work:

*

*Every production is numbered. You'll need to remove those numbers.

*If there are mid-rule actions, they will show up as oddly-named empty non-terminals. The names will be something like $@8 or @2. You'll need to delete these tokens and their corresponding empty productions.

*Empty productions are (at least in one recent version of bison) shown as /* empty */. That might not be your preference.

*It does not change : to ::=
I've extracted grammars from yacc/bison files in this way, and it's very straight-forward; you can make all the above changes with a simple sed or awk script.


text:
Q: Docker terminal size I'm running docker 17.12.0-ce under ubuntu 16.04 Server
After doing docker exec -it ... bash the terminal (putty) size change.
Before stty size gives 60 180 after 0 0
So after entering the 80st character the next ones are placed at the begining of the line (not on the next line).

There is a solution ?  Something to configure in docker daemon ?

A: This is a known bug in Docker. The fix was merged on 8th June 2018, so should be in some future Docker release.


text:
Q: Kotlin mutableListOf with several entries I want to to fill a list with several entries. So far I only have one entry:
val someAttributes: List<Product.MyAttribute> = mutableListOf(Product.MyAttribute("ATTRIBUTE A", listOf("3")))

This is MyAttribute:
  data class MyAttribute(
    var key: String = "",
    var values: List<String> = ArrayList()
  )

What's the correct syntax in Kotlin to add several entries to a mutableList?

A: val someAttributes = mutableListOf(
  Product.MyAttribute("ATTRIBUTE A", listOf("3")),
  Product.MyAttribute("ATTRIBUTE B", listOf("4")),
  Product.MyAttribute("ATTRIBUTE C", listOf("5"))
)

A: Use add for a single item, or addAll if you have several. You can pass in an index to say where you want them inserted, otherwise they're added to the end of the list
someAttributes.add(newAttr)
someAttributes.addAll(listOf(coolAttr, radAttr))

If you just want to add them all when you initialise the list, just pass them all in as parameters - mutableListOf takes a vararg, i.e. a variable number of arguments (you just separate them with commas)
someAttributes = mutableListOf(attr1, attr2, attr3)


text:
Q: Query CustomObject Description and check if empty via Apex I've been searching around for a few hours for what I initially thought should be a very simple thing.
I want to write some Apex code that will iterate through all of the objects and fields in my org and check the Descriptions.
I can iterate through the objects and fields and get names, and other bits BUT NOT description. Is there any way to do this?
I want to create a test class that checks descriptions that were newly created (and eventually ALL descriptions) and checks to see that:

*

*they are not empty,

*they are comprised of more than just the field name,

*they are greater than a certain number of characters.

I want to do this to be able to enforce descriptions being filled in on creation of new fields. Nothing more frustrating than empty descriptions, or descriptions like this: Name of Field: "Do XYZ", description: "Does XYZ" ....aaarggh #$@##*&# !!!!!

A: You cannot do this from within Apex today.
However, Salesforce is building Apex Metadata Api which should help building something like this possible. That api and its GA is still little far away.
The only option now is to develop an external tool to achieve this using Salesforce Metadata Api.

A: You could jump out to the Tooling API CustomObject and CustomField. You can do this with either SOAP or the REST API. For the latter there is an existing community wrapper project.
The SOQL queries could be as simple as:
Select Id,DeveloperName,Description from CustomObject
Select Id,TableEnumOrId,DeveloperName,Description from CustomField

Either way (SOAP/REST), this will cost you a Callout to get the data. Hence it won't be directly accessible in a Testing context. You would need to persist the data somewhere before running the test to make it accessible. At which point you would need to consider if the solution is starting to cause more problems than you started out with.

As an alternative, you could look at automating the check with something like the sfdx command line.
E.g. Get the list of custom objects in the org.
sfdx force:schema:sobject:list -c custom -u DevHub

Get the metadata for that custom object. In my case Fruit__c
sfdx force:schema:sobject:describe -s Fruit__c -u DevHub


text:
Q: What is the probability that the bacteria population eventually dies out? A jar begins with one bacteria. Every minute, every bacteria turns into 0,
1, 2, or 3 bacteria with a probability of 25% for each case (dies, does
nothing, splits into 2, or splits into 3). What is the probability that the
bacteria population eventually dies out?

A: Let $p$ be the probability of the bacteria dying out(it also means tht none of its offspring remains alive),
So the probability of this bacteria dying out = either itself dies out or the bacterias generated by it also dies out
So we have,$p=\frac{1}{4}+\frac{1}{4}p+\frac{1}{4}p^2+\frac{1}{4}p^3$
(Reason: Cases may be either the bacteria itself dies out then there is no question of its offspring, or it remains as it is(with the probaility ($1/4$ ) and then it itself dies out (along with its next generation with the probability $p$ ,or it turns into 2 (with the probaility ($1/4$ )and then both of these diesout with its next generation with prob. $p^2$ and similarly for the case when it turns into 3 bacteria.)
$\Rightarrow p^3+p^2-3p+1=0$
$\Rightarrow (p-1)(p^2+2p-1)=0$
$\Rightarrow (p^2+2p-1)=0$(As $p\ne1$ otherwise 'everything falls apart'.Truly, I cant see why it cant be 1, just my mind says so)
$\Rightarrow p=-1+\sqrt{2}$or $p=-1-\sqrt{2}$
As p cant be -ve so the answer is $p=\sqrt{2}-1$


text:
Q: Calendar Events - retrieve Attachment Url Here is a link: https://developers.google.com/calendar/v3/reference/events#resource-representations
On the bottom of you can see:
"attachments": [
    {
      "fileUrl": string,
      "title": string,
      "mimeType": string,
      "iconLink": string,
      "fileId": string

I have in my Google calendar many events, some with attachments which are pictures.
I want to append all the events with the fileurl to the sheet.
How can I do that?
This is a part of my code:
for(var x=0;x<events.length;x++){
    var messages = event.getTitle();
    var idEvent = event.getId();
    var eventStart = event.getStartTime();
    var eventEnd = event.getAllDayEndDate();
  //  var eventPictureURL = ?????
    sheet.appendRow([messages,idEvent,eventStart]);
  }

I want this as the result.
sheet.appendRow([messages,idEvent,eventStart], eventPictureURL);


text:
Q: Conversion from char* to signed char* I saw a piece of valid C code I tried to compile as C++ and I got an error I can't understand.
char* t;
signed char* v = t;

error: invalid conversion from char* to signed char*

From what I learned, char and signed char are semantically identical, but are still considered as different by the compiler.
I know that the error is caused by the difference between these two type, my question is: Why does this difference exists ?
As far as I know char is implemented either as a signed char or as a unsigned char so it should be identical to either one or the other.

I consulted this question and it doesn't answer the point I want to know.

A: Actually I finally found the spec part talking about this:

3.9.1 Fundamental types

*

*Objects declared as characters (char) shall be large enough to store
  any member of the implementation's basic character set. If a character
  from this set is stored in a character object, the integral value of
  that character object is equal to the value of the single character
  literal form of that character. It is implementation-defined whether a
  char object can hold negative values. Characters can be explicitly
  declared unsigned or signed. Plain char, signed char, and unsigned
  char are three distinct types. A char, a signed char, and an unsigned
  char occupy the same amount of storage and have the same alignment
  requirements (3.11); that is, they have the same object
  representation. For character types, all bits of the object
  representation participate in the value representation. For unsigned
  character types, all possible bit patterns of the value representation
  represent numbers. These requirements do not hold for other types. In
  any particular implementation, a plain char object can take on either
  the same values as a signed char or an unsigned char; which one is
  implementation-defined.

A:
From what I learned, char and signed char are semantically identical, but are still >considered as different by the compiler.

NO. char is not semantically identical to signed char.
In contrast to the other integral types (integer, long, short etc) there is no guarantee that char without a signed or unsigned will be signed. This is implementation defined. Some architectures define it as signed, others as unsigned in the real world
So, with a char, if the signedness is important, you really do need to specify which you want.
My recommendation would be if you are doing character manipulation etc, or using an api call that uses char or char *, use char. If you just want an 8-bit integer value, make sure you specify signed char or unsigned char, so that in a couple of years time when you port to a different architecture you don't get bitten in the bum.
Or better yet, use uint8_t or int8_t for 8 bit integers.
EDIT: From your own answer:

These requirements do not hold for other types. In any particular implementation, a plain char object can take on either the same values as a signed char or an unsigned char; which one is implementation-defined.

A: I will say what i know...
For char type c++ has size '1' byte..
if it is signed char then the range is from -128 to 127
else if it is unsigned char range is from 0 to 256
we all know the 8 bits in a byte in case of signed char the MSB(ie , the left most bit) will be used for the sign the rest 7 bits for values making range 0-2^7(0-127) .negative sign(logical 1) and (logical 0) for positive sign on MSB. eg( 1 0000111=-7,0 0000111=+7)and 1 0000000-128. However if assign 129 for a signed char value it will be automatically changed to -127 (ie a value in range (-128,127).
on the other case of unsigned char type all the 8 bits are used for values ie range is 0-2^8(0-255). here 0-127 is same as the signed char and the ones belongs to -128 to 0 can be found in range 128-255 in the unsigned char set.
So we can say and spot the internal memory difference between the two types 'signed' and 'unsigned' which may be the problem.


text:
Q: When something good is being presented as bad When a person presents in his speech something that generally is good as being the absolute opposite, what do we call it?
I mean grammatically and in terms of terminology only.

*

*How do feel?

*Never been better (in a sad voice and manner when it actually should have been and stands for "Never been worse")

This example shows that "Never been better" is generally perceived as being something positive, however, is delivered as something negative.

A: "[I have] never been better." is not negative, either grammatically or linguistically.
Never is an adverb of frequency. Always, sometimes, ever, never.
Frequency can be positive, negative or neutral and the rest of the context is what will determine that.
I have never been better means: this is the best I have been.
"He has never been poor". [a positive situation for most people]
"She has never been hiking in good, walking shoes." [a negative situation for one's feet.
"They have never been good friends." [could be a neutral statement of fact]


text:
Q: ServletFileUpload#parseRequest(request) returns an empty list I have a client application in Android which uses HttpURLConnection to send files to the server. The server uses the Apache Commons FileUpload API to parse the form-data values.
The HttpURLConnection sends this request:
-----------------------------4912995119421
Content-Disposition: form-data; name="deviceid"

9428103
-----------------------------4912995119421
Content-Disposition: form-data; name="countryid"

598
-----------------------------4912995119421
Content-Disposition: form-data; name="number"

98621360
-----------------------------4912995119421
Content-Disposition: form-data; name="file"; filename="2012-12-08 17.42.18.jpg"
Content-Type: image/jpeg

ÿØÿá1 Exif  II*
      @      °      ª
   ²              ¼       Ä   (       1    Ì   2    Ø          i‡    ì   %ˆ    \  n  SAMSUNG GT-S5360L H      H      S5360LUHLB1 2012:12:08 17:42:18  š'    î  ?'    ö  "ˆ       'ˆ    È    ?    0220?    þ  ?      '     '    &  '
'    .        0100             @       °       >  £       ¤        ¤        ¤    6  ¤
   2012:12:08 17:42:18 2012:12:08 17:42:18
     d               R98      0100                         (           ¤      T.      ÿØÿà JFIF      ÿÛ C @@ÿÛ
-----------------------------4912995119421--

The server code:
    String contentType = request.getContentType();
    if ((contentType.indexOf("multipart/form-data") == -1)) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    long maxFileSize = (2 * 1024 * 1024);

    int maxMemSize = (2 * 1024 * 1024);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.

    upload.setSizeMax(maxFileSize);

    List fileItems = upload.parseRequest(request);
    Iterator i = fileItems.iterator();

    //leo primero todas las variables.

    int deviceID = 0;
    int countryID = 0;
    String phoneNumber = "";

    while (i.hasNext()) {
        FileItem fi = (FileItem) i.next();

        if (fi.isFormField()) {
            String variable = fi.getFieldName();
            if (variable.equals("deviceid")) {
                deviceID = Integer.parseInt(fi.getString());
            } else if (variable.equals("countryid")) {
                countryID = Integer.parseInt(fi.getString());
            } else if (variable.equals("number")) {
                phoneNumber = String.valueOf(Long.parseLong(fi.getString()));
            }

        }

    }

    if (deviceID == 0 || countryID == 0 || phoneNumber.equals("")) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

The problem is in the line List fileItems = upload.parseRequest(request);.
The returned list is empty and I can not get the form-data values.

A: If spring is used, check if there is a <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> in xml file. There is a function
protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
        if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
            if (request instanceof MultipartHttpServletRequest) {
                logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " +
                        "this typically results from an additional MultipartFilter in web.xml");
            }
            else {
                return this.multipartResolver.resolveMultipart(request);
            }
        }
        // If not returned before: return original request.
        return request;
    }

"eats" the multipart items. It causes a three hours pain.

A: It will be empty at that point if you have already (implicitly) parsed the request body beforehand. The HTTP request body can be read/parsed only once (as the client has sent it only once and won't send it multiple times).
The request body will be implicitly read/parsed when you have invoked any of the following methods before feeding the request to Commons FileUpload:
request.getParameter();
request.getParameterMap();
request.getParameterNames();
request.getParameterValues();
request.getReader();
request.getInputStream();

You need to make absolutely sure that you are not calling any of those methods beforehand (also check all servlet filters to be sure).
If you've already ensured that you aren't doing that, then the only other possible causes would be an incorrect boundary header and/or using incorrect newlines (it has really to be CR+LF and thus not alone LF). You can find a concrete and proper example at the bottom of Using java.net.URLConnection to fire and handle HTTP requests, under the section "Uploading files".

A: I was running into this problem as well, but I couldn't find anything that specifically related to reading the request object.  I finally got it to work by removing this block:
@MultipartConfig(
    location="/tmp",
    fileSizeThreshold=1024*1024,
    maxFileSize=1024*1024*5,
    maxRequestSize=1024*1024*5*5
)

Apparently when I had been trying to read the request by using getParts(), I forgot to remove this.  I'm a bit new to java, so I didn't know this conflicts with the ServletFileUpload#parseRequest.  Anyway, once I got rid of it, the parseRequest correctly returned the array.

A: I had this same problem after trying I find that it was incompatibility of libraries, library apache server with fileupload library, so I remove the library and imported from the library server Apache.
imports:
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

sorry my english

A: my problem is apache context.xml on my linux server contains Context
allowCasualMultipartParsing="true" and my HttpServlet contains
@MultipartConfig(fileSizeThreshold=1024*1024*2,maxFileSize=1024*1024*50,maxRequestSize=1024*1024*50)

I delete it then it's working correctly. Hope this will help you.


text:
Q: Can I have two spectral assassins at once? I got the power to summon a spectral assassin from the dark brotherhood quest-line, but can I use my spectral assassin once, wait 24 hours, then do it again and have 2 spectral assassins? Also, can I have a spectral assassin as well as my current (human) follower.
I have read the Elder Scrolls wiki and it says the following:

After being summoned, he will follow the Dragonborn around, no matter where they may be, until they summon another Familiar, Atronach, Raise Zombie, or when he is defeated.

Does this mean I can have 2 spectral assasins at once, since casting the power again is not summoning Familiars, Astronaches or raise zombies, or the assassin being defeated. Or does it fail due to too many followers.
Is it possible to get multiple spectral assassin this way, and can I get the assassins with a human follower?

A: 1) First of all you cannot use the 'summon Assassin' power within 24 hours of use.
2) Second of all if your assassin is alive after 24 hours and you use the power again it will simply disappear from the position it was standing and appear in another position close to you. Thats it.
I am sorry to crush your dream of having an assassin army, but that's how the game works. I know this because i myself have tried it multiple times.
However, you can get the assassin along with a human follower and a dog and  if you have anyone else following you which is related to a particular mission.Cheers.