text:
Q: Describe or display the relationship between variables and the labels xgboost? I have a model:
model<-xgboost(data=as.matrix(data[,-1]),label=data$Ethnicity, num_class=8, nrounds=50,objective="multi:softmax",lambda=1, eval_metric="merror")

data is a matrix of 94 variables of random survey question and the label is Ethnicity which is a 0-7 variable coding race/ethnicity so that every number from 0 to 7 represents an ethnicity.
I found which variables are most important in the prediction:
xgb.importance(model=model)

##     Feature         Gain        Cover   Frequency
##  1:     q97 0.0924173556 0.0388402250 0.016981237
##  2:      q9 0.0603595554 0.0199381316 0.012749847
##  3:      q7 0.0456855077 0.0447756304 0.066922777
##  4:      q6 0.0436987577 0.0485072162 0.041311731
##  5:      q8 0.0319606309 0.0212999077 0.015199599
##  6:     q99 0.0276115402 0.0201090242 0.007961695
##  7:     q89 0.0245865711 0.0249913356 0.023829408
##  8:     q13 0.0197648132 0.0190748590 0.010912533
##  9:     q81 0.0194462208 0.0140010066 0.021880742
## 10:     q71 0.0192126872 0.0194684164 0.019709370

Now I am stuck, my question is how do I describe or display the relationship between these variables and the labels? TIA!
Here are some data from dput(head(data)):
structure(list(r = c(2, 6, 4, 4, 4, 4), q6 = c(1.73, 1.5, 1.9,
NA, 1.63, 1.7), q7 = c(54.43, 51.26, 66.68, NA, 68.49, 59.88),
    q8 = c(2, 2, 1, 2, 1, 2), q9 = c(5, 5, 5, 5, 4, 5), q10 = c(5,
    1, 1, 1, 3, 1), q11 = c(1, 1, 1, 2, 1, 1), q12 = c(1, 1,
    1, 4, 1, 1), q13 = c(1, 1, 1, 4, 1, 1), q14 = c(1, 1, 1,
    1, 1, 1), q15 = c(1, 1, 1, 1, 1, 1), q16 = c(1, 1, 3, 1,
    1, 1), q17 = c(2, 1, NA, 1, 1, 1), q18 = c(3, 1, NA, 2, 1,
    1), q19 = c(2, 1, NA, 1, 1, 1), q20 = c(2, 1, NA, 2, 1, 1
    ), q21 = c(2, 2, NA, 2, 1, 2), q22 = c(2, 1, 1, 1, 4, 2),
    q23 = c(2, 1, NA, 1, 5, 2), q24 = c(1, 2, 1, 2, 1, 1), q25 = c(1,
    2, 1, 2, 2, 1), q26 = c(2, 2, 1, 1, 1, 1), q27 = c(2, 2,
    1, 2, 1, 1), q28 = c(2, 2, 2, 2, 1, 1), q29 = c(1, 1, NA,
    1, 1, 3), q30 = c(1, 1, NA, 1, 1, 3), q31 = c(1, 2, NA, 1,
    1, 1), q32 = c(6, 1, NA, 6, 6, 1), q33 = c(NA, 1, NA, 2,
    5, 1), q34 = c(NA, 1, NA, 2, 4, 1), q35 = c(NA, 1, NA, 5,
    5, 1), q36 = c(2, 1, NA, 3, 3, 1), q37 = c(1, 1, NA, 1, 1,
    1), q38 = c(6, 1, NA, 4, 1, 1), q39 = c(1, 2, 2, 1, 1, 2),
    q40 = c(3, 1, NA, 2, 7, 1), q41 = c(6, 1, 2, 5, 6, 3), q42 = c(5,
    1, 5, 5, 5, 6), q43 = c(1, 1, 1, 2, 2, 2), q44 = c(1, 1,
    1, 2, 2, NA), q45 = c(1, 1, 1, 5, 7, 4), q46 = c(1, 1, 1,
    6, 5, 7), q47 = c(7, 1, NA, 7, 7, 6), q48 = c(6, 1, 7, 5,
    5, 6), q49 = c(4, 1, NA, 6, 1, 4), q50 = c(1, 1, 1, 2, 3,
    1), q51 = c(1, 1, 1, 1, 1, 1), q52 = c(1, 1, 1, 1, 1, 1),
    q53 = c(1, 1, 1, 2, 3, 1), q54 = c(1, 1, 1, 1, 2, 1), q55 = c(1,
    1, 1, 2, 1, 1), q56 = c(1, 1, 1, 1, 1, 1), q57 = c(1, 1,
    1, 4, 4, 2), q58 = c(1, 1, 1, 1, 1, 1), q59 = c(1, 2, 2,
    2, 1, 1), q60 = c(1, 2, 1, 1, 1, 1), q61 = c(7, 1, 2, 5,
    6, 6), q62 = c(3, 1, 3, 5, 7, 5), q63 = c(3, 1, 3, 2, 4,
    5), q64 = c(3, 1, 3, 3, 3, 2), q65 = c(2, 1, 2, 2, 2, 3),
    q66 = c(4, 1, NA, 4, 4, 2), q67 = c(2, 3, 3, 2, 3, 2), q68 = c(1,
    1, 2, 1, 1, 1), q69 = c(2, 3, 3, 2, 3, 3), q70 = c(2, 4,
    4, 2, 1, 1), q71 = c(3, 2, 3, 1, 3, 2), q72 = c(4, 4, 4,
    2, 3, 2), q73 = c(1, 2, 1, 1, 1, 2), q74 = c(2, 2, 3, 2,
    2, 2), q75 = c(2, 2, 2, 2, 2, 1), q76 = c(7, 2, 2, 2, 2,
    1), q77 = c(3, 3, 4, 4, 2, 7), q78 = c(1, 2, 4, 2, 1, 3),
    q79 = c(4, 8, 6, 3, 1, 2), q80 = c(6, 4, 4, 3, 1, 4), q81 = c(5,
    NA, 1, 4, 2, 1), q82 = c(7, 1, 6, 5, 2, 7), q83 = c(1, 1,
    1, 6, 1, 6), q84 = c(1, 1, 1, 2, 1, 2), q85 = c(2, 2, 1,
    2, 2, 2), q86 = c(1, 1, NA, 1, 1, 1), q87 = c(2, 2, NA, 2,
    2, 1), q88 = c(4, 5, 5, 3, 1, 2), q89 = c(4, 2, 2, 4, 2,
    4), q90 = c(2, 1, NA, NA, 1, 2), q91 = c(1, 1, 1, 3, 3, 1
    ), q92 = c(1, 1, 1, 2, 2, 5), q93 = c(4, 5, 7, 4, 7, 2),
    q94 = c(3, 3, 2, 2, 3, 2), q95 = c(1, 4, 1, 1, 1, 4), q96 = c(1,
    1, 1, 1, 1, 1), q97 = c(1, 1, 3, 1, 2, 3), q98 = c(1, 2,
    2, 1, 1, 1), q99 = c(1, 1, 1, 1, 1, 2)), row.names = c(NA,
6L), class = "data.frame")


text:
Q: Attached image is not getting to the mail Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.setType("image/jpg");
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]
        {"me@gmail.com"});
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
        "Test Subject");
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
        "go on read the emails");
        Log.v(getClass().getSimpleName(), "sPhotoUri=" + Uri.parse("file:///sdcard/2944154479.jpg"));
        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/2944154479.jpg"));
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));

I used the above code to send a image to the email,email page shows that file is attached
but I am getting only message,attachment is not getting to my mail.
please help
Thanks in advance

A: Please try below code it will work for you.
  Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
          emailIntent.setType("jpeg/image");
          emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                       new String[] { "" });
          emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
          Date cal = Calendar.getInstance().getTime();
          emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "body");

          Uri uri = Uri.fromFile(new File(Environment
                       .getExternalStorageDirectory(), "/HB.jpg"));

          emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
          emailIntent.setType("text/plain");

          startActivity(Intent.createChooser(emailIntent, "Send mail..."));

A: You first have to set the type to text/plain to add your message. Then you set the type to jpeg/image to add the image. Otherwise your information will be misinterpreted.
   Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,getResources().getString(R.string.emlSendToFriendSubject));
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[]{emailto});
    emailIntent.setType("text/plain");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,getResources().getString(R.string.emlSendToFriendBody));
    File file = getFileStreamPath(EMAIL_TEMP_FILE);
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    emailIntent.setType("image/jpeg");
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+file.getAbsolutePath()));
    startActivityForResult(Intent.createChooser(emailIntent, getResources().getString(R.string.btnSendToFriend)),ActMain.EMAIL_DONE);

A: Try this :)
String path = ...;

//Need to remove file:////, it has to be something like this storage/emulated/0/repertory/image.jpg
 if(path.startsWith("file")){
    path = path .replace("file:////", "");
 }

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path)));
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"test@test.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_TEXT   , "body");
startActivity(Intent.createChooser(i, "Sending email..."));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any way to easily draw a hollow donut shape in C# So like a graphics.FillEllipse, but with a hole in the middle. I need to highlight some circular icons by putting a ring around them, and due to the constraints of the larger program it's hard/impossible to simply FillEllipse under them to make it look like there's a hole.

A: You could create a Region that is based on what you would have drawn using the FillEllipse and the use the Exclude method of the Region to remove areas that you don't want by using another GraphicsPath returned from another call to FillEllipse.
Then you would just have to overlay the resulting Region on top of what you want it to surround.

A: // Create a brush
SolidBrush b = new SolidBrush(Color.Blue);

// Clear your Graphics object (defined externally)
gfx.Clear(Color.White);

// You need a path for the outer and inner circles
GraphicsPath path1 = new GraphicsPath();
GraphicsPath path2 = new GraphicsPath();

// Define the paths (where X, Y, and D are chosen externally)
path1.AddEllipse((float)(X - D / 2), (float)(Y - D / 2), (float)D, (float)D);
path2.AddEllipse((float)(X - D / 4), (float)(Y - D / 4), (float)(D / 2), (float)(D / 2));

// Create a region from the Outer circle.
Region region = new Region(path1);

// Exclude the Inner circle from the region
region.Exclude(path2);

// Draw the region to your Graphics object
gfx.FillRegion(b, region);

A: Using GDI+, you can draw a circle with a high value for the pen width, to make it look like a donut.  There will be nothing in the centre so you'll be able to see through it.

A: Based on user263134 answer:
    g.FillRegion(Brushes.Black, GetRingRegion(center, innerRadius, outherRadius));

    public static RectangleF GetRectangle(PointF center, float radius)
    {
        var rectangle = new RectangleF(center.X - radius, center.Y - radius,radius * 2, radius * 2);
        return rectangle;
    }

    public static Region GetRingRegion(PointF center, float innerRadius, float outherRadius)
    {
        // You need a path for the outer and inner circles
        var path1 = new GraphicsPath();
        var path2 = new GraphicsPath();

        // Define the paths (where X, Y, and D are chosen externally)
        path1.AddEllipse(GetRectangle(center,outherRadius));
        path2.AddEllipse(GetRectangle(center, innerRadius));

        // Create a region from the Outer circle.
        Region region = new Region(path1);

        // Exclude the Inner circle from the region
        region.Exclude(path2);

        return region;
    }

A: The answer of 'sth' is pretty much what you need, but dude you can easily just use:
(Graphics).DrawEllipse(new Pen(YOURCOLOR, RINGDIAMETER), center.x - radius, center.y - radius, radius * 2, radius * 2);
But i think you knew this before. :)

A: One important thing with the answer from sth, which is the most flexible answer, is that GraphicsPath and Brush need to be disposed so put their declaration in a using statement as follows:
// Clear your Graphics object (defined externally)
gfx.Clear(Color.White);

// You need a path for the outer and inner circles
using (GraphicsPath path1 = new GraphicsPath(), path2 = new GraphicsPath())
  {
  // Define the paths (where X, Y, and D are chosen externally)
  path1.AddEllipse((float)(X - D / 2), (float)(Y - D / 2), (float)D, (float)D);
  path2.AddEllipse((float)(X - D / 4), (float)(Y - D / 4), (float)(D / 2), (float)(D / 2));

  // Create a region from the Outer circle.
  Region region = new Region(path1);

  // Exclude the Inner circle from the region
  region.Exclude(path2);

  // Create a brush
  using (SolidBrush b = new SolidBrush(Color.Blue))
    {
    // Draw the region to your Graphics object
    gfx.FillRegion(b, region);
    }
  }

This will ensure that they are disposed when they are no longer needed.
The using is the best way to ensure that the Dispose method is called even when an exception occurs.


text:
Q: Extract average values of multiple columns via ActiveRecord I have a Grade model from which I need to pull the averages of two columns - accuracy and time. I'm using the following query to get both values together instead of querying the model twice.
Grade.where(student_id: 25).pluck('avg(accuracy), avg(time)')

I get two values alright, but they are in the following format which I do not understand:
[[#<BigDecimal:7f9c5a890410,'8.0',9(18)>, #<BigDecimal:7f9c5a8903c0,'10.0',9(18)>]]

How do I extract only the values that I need from this? i.e. avg_accuracy = 8.0 and avg_time = 10.0
I'm new to Ruby, Rails, ActiveRecord. I appreciate the help.

A: grades = Grade.where(student_id: 25, class_id: 123).pluck('avg(accuracy), avg(time)').first

Should get
[#<BigDecimal:7f9c5a890410,'8.0',9(18)>, #<BigDecimal:7f9c5a8903c0,'10.0',9(18)>]

and now convert them to simple floats.
grades.map!(&:to_f)

should get
[8.0, 10.0]


text:
Q: OpenCV: A straighforward method of colorizing a grayscale image What is a straight forward method of "colorizing" a grayscale image. By colorizing, I mean porting the grayscale intensity values to one of the three R, G, B channels in a new image.
For example a 8UC1 grayscale pixel with intensity of I = 50 should become a 8UC3 color pixel of intensity BGR = (50, 0, 0) when the picture is colorized to "blue".
In Matlab for example, what I'm asking for can be simply created with two lines of code:
color_im = zeros([size(gray_im) 3], class(gray_im));
color_im(:, :, 3) = gray_im;

But amazingly I cannot find anything similar in OpenCV.

A: Well, the same thing requires a bit more work in C++ and OpenCV:
// Load a single-channel grayscale image
cv::Mat gray = cv::imread("filename.ext", CV_LOAD_IMAGE_GRAYSCALE);

// Create an empty matrix of the same size (for the two empty channels)
cv::Mat empty = cv::Mat::zeros(gray.size(), CV_8UC1);

// Create a vector containing the channels of the new colored image
std::vector<cv::Mat> channels;

channels.push_back(gray);   // 1st channel
channels.push_back(empty);  // 2nd channel
channels.push_back(empty);  // 3rd channel

// Construct a new 3-channel image of the same size and depth
cv::Mat color;
cv::merge(channels, color);

or as a function (compacted):
cv::Mat colorize(cv::Mat gray, unsigned int channel = 0)
{
    CV_Assert(gray.channels() == 1 && channel <= 2);

    cv::Mat empty = cv::Mat::zeros(gray.size(), gray.depth());
    std::vector<cv::Mat> channels(3, empty);
    channels.at(channel) = gray;

    cv::Mat color;
    cv::merge(channels, color);
    return color;
}

A: There are special function to do this - applyColorMap in OpenCV from v2.4.5 in contrib module. There are different color maps available:


text:
Q: Why does my BitArray split? I have the following code:
bittrans = '0b' + str(bitnumber)
strnumber = bitstring.BitArray(bittrans)
print bittrans
print strnumber

Which outputs:
0b1001010100000010111110001111111111
0x9502f8ff, 0b11

How do I stop the bitstring form splitting itself?

A: This is just the string representation that BitArray uses to make your bitarray simpler to look at if you print it out. It has nothing to do with the internal representation.
It splits because BitArray.__str__ wants to represent your bitarray as a bunch of bytes, like so:
0x95 02 f8 ff ?

You can't represent your bitstring as bytes unambiguously because the number of bits in your bitstring isn't a multiple of 8:
In [60]: len('1001010100000010111110001111111111') % 8
Out[60]: 2

Notice that's how many bits are left over in the string representation you have in your question. You will have to pad your number with 6 more bits to make it representable as a "single" hex number.
You can instead print out strnumber.bin:
In [75]: print strnumber.bin
1001010100000010111110001111111111


text:
Q: While Loop encrypted data I'm trying to pass encrypted data through a while loop, in order to decrypt the data from a database. I'm able to get some what of a result. Though, since the decryption relies on if the string matches the key. If it the key doesn't match, it won't display anything because all of the strings combine, instead of breaking on each table line.
What I'm seeing happen:
If encrypted data line 1 is: 1234
If encrypted data line 2 is: 5678
+-------------------+
| client_name       |
+-------------------+
| 1234              |
| 5678              |
+-------------------+

The result with the while loop is: 12345678. What I'm trying to achieve is having the while loop go line to line and output for decryption.
Here is what I have for the while loop output:
<?php
  $data = mysql_query("SELECT * FROM invoices WHERE username = '$username'") or die(mysql_error());
    while($info = mysql_fetch_array( $data ))
    {
    $security = new Security();
    echo "".$security->decrypt($info['client_name'])." Invoice 20";
  }
?>

Here is what I have for the decryption: (Based on - http://wpy.me/blog/15-encrypt-and-decrypt-data-in-php-using-aes-256)
<?php class Security {

            # Private key
            public static $salt = 'ZfTfbipGsZ4yz34jFrGHagahptzLN7ROigy';

            # Encrypt a value using AES-256.
            public static function encrypt($plain, $key = null, $hmacSalt = null) {
                if(empty($key)) {
                    $key = self::$salt;
                }

                self::_checkKey($key, 'encrypt()');

                if ($hmacSalt === null) {
                    $hmacSalt = self::$salt;
                }

                $key = substr(hash('sha256', $key . $hmacSalt), 0, 32); # Generate the encryption and hmac key

                $algorithm = MCRYPT_RIJNDAEL_128; # encryption algorithm
                $mode = MCRYPT_MODE_CBC; # encryption mode

                $ivSize = mcrypt_get_iv_size($algorithm, $mode); # Returns the size of the IV belonging to a specific cipher/mode combination
                $iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM); # Creates an initialization vector (IV) from a random source
                $ciphertext = $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv); # Encrypts plaintext with given parameters
                $hmac = hash_hmac('sha256', $ciphertext, $key); # Generate a keyed hash value using the HMAC method
                return $hmac . $ciphertext;
            }

            # Check key
            protected static function _checkKey($key, $method) {
                if (strlen($key) < 32) {
                    echo "Invalid key $key, key must be at least 256 bits (32 bytes) long."; die();
                }
            }

            # Decrypt a value using AES-256.
            public static function decrypt($cipher, $key = null, $hmacSalt = null) {
                if(empty($key)) {
                    $key = self::$salt;
                }

                self::_checkKey($key, 'decrypt()');

                if (empty($cipher)) {
                    echo 'The data to decrypt cannot be empty.'; die();
                }
                if ($hmacSalt === null) {
                    $hmacSalt = self::$salt;
                }

                $key = substr(hash('sha256', $key . $hmacSalt), 0, 32); # Generate the encryption and hmac key.

                # Split out hmac for comparison
                $macSize = 64;
                $hmac = substr($cipher, 0, $macSize);
                $cipher = substr($cipher, $macSize);

                $compareHmac = hash_hmac('sha256', $cipher, $key);
                if ($hmac !== $compareHmac) {
                    return false;
                }

                $algorithm = MCRYPT_RIJNDAEL_128; # encryption algorithm
                $mode = MCRYPT_MODE_CBC; # encryption mode
                $ivSize = mcrypt_get_iv_size($algorithm, $mode); # Returns the size of the IV belonging to a specific cipher/mode combination

                $iv = substr($cipher, 0, $ivSize);
                $cipher = substr($cipher, $ivSize);
                $plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
                return rtrim($plain, "\0");
            }

        }
?>

What would you suggest I do within my while loop, to output each data point separately?

A: Just do like this:
if($data->num_rows() > 0){
   // create her security object not inside loop.
   $security = new Security();

   foreach($data->result() as $row){
       echo "".$security->decrypt($row->client_name)." Invoice 20
";
   }
}


text:
Q: Linux bashrc messed up I think I messed up my bashrc file adding Java to the path.
None of my commands will work, I cant cd,ls,gedit or sudo.
I tried to manually find my bashrc and change it back but I cant access it because it says I dont have permissions.
How can I reset my bashrc in this state?

A: Try this:
PATH="/usr/sbin:/usr/bin:/sbin:/bin"

Most things should work now to fix your ~/.bashrc


text:
Q: Changing collection object values en masse Is it possible to make changes to all objects in a collection at once?
e.g. (this is impossible):
thisCollection.getAll().setTested(true);

There is no getAll and so I wondered if there was another way to make this change while avoiding iteration.

A: Well you can use Iterable.forEach:
thisCollection.forEach(x -> x.setTested(true));

That's still going to iterate, of course - there's nothing you can do about that. You've got lots of objects to modify... how would you expect them to all be modified without any iteration?
It's up to you whether you view the above as simpler or more complicated than just doing it the "old fashioned" way with an enhanced for loop:
for (Item item : thisCollection) {
    item.setTested(true);
}


text:
Q: Why this php code not work when tried to remove script tag? Normally i use this code for remove all data inner img tag. It's work good.
<?PHP
$string = "test";
$string = preg_replace("/]+>/", "", $string);
echo $string;
?>

Then i apply code for remove all data inner script tag. this is my code.
<?PHP
$string = "test";
$string = preg_replace("/<scrip[^>]+script>/", "", $string);
echo $string;
?>

When test code it's not remove data inner script tag. Why ?

A: Your code doesn't work because you're parsing <scrip, followed by zero or more characters other than >, followed by script>.
There is no such substring in your content. In your $string, after <scrip you have a t (which matches [^>]+) and then you have a > instead of script>. So, no match.
Here's what you need to do instead:
$string = preg_replace("/ other content
Without lazy evaluation, it would remove everything from the first
• Followed by </script> to mark the end of the script section
Note I'm escaping the slash (\/ instead of /) because / is the regex delimiter character here. We could also have used a different character at the beginnen and end of the regex, like #, and then the / didn't have to be escaped.
• Finally, I added the s and i modifiers. s to make it parse multiline content. Javascript code can of course contain linebreaks, and we want .*? to match those as well. And i to make it case insensitive, because I assume you want to replace


text:
Q: Map marker title does not show full text on Google map V2 I have multiple markers with its information on the map. By tapping on a particular marker it shows information.
Below is the code for adding multiple markers:
for (int i = 0; i < list.size(); i++) {
    MarkerOptions markerOptions = new MarkerOptions();
    HashMap<String, String> hmPlace = list.get(i);
    double lat = Double.parseDouble(hmPlace.get("lat"));
    double lng = Double.parseDouble(hmPlace.get("lng"));
    String name = hmPlace.get("place_name");
    String vicinity = hmPlace.get("vicinity");
    LatLng latLng = new LatLng(lat, lng);
    markerOptions.position(latLng);
    markerOptions.title(name + ":" + vicinity);
    googleMap.addMarker(markerOptions);
}

My output is seen like this:

When I tap on a marker it is not displaying the full text. Instead of that it shows me some text and after some dots display.
Is there any method in Google Map V2 to show the full text? I already use the title() method of the "MarkerOptions" class.

A: Thanks for helping.But I solved my issue.
Just create one class which extends InfoWindowAdapter.
class MyInfoWindowAdapter implements InfoWindowAdapter {

    private final View myContentsView;
    private String name, vicinity;

    public MyInfoWindowAdapter(String name, String vicinity) {
        myContentsView = getLayoutInflater().inflate(
                R.layout.custom_info_contents, null);
        this.name = name;
        this.vicinity = vicinity;
    }

    @Override
    public View getInfoContents(Marker marker) {

        TextView tvTitle = ((TextView) myContentsView
                .findViewById(R.id.title));
        tvTitle.setText(name);
        TextView tvSnippet = ((TextView) myContentsView
                .findViewById(R.id.snippet));
        tvSnippet.setText(vicinity);

        return myContentsView;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        // TODO Auto-generated method stub
        return null;
    }

}

And use setInfoWindowAdapter() method of GoogleMap.
googleMap.setInfoWindowAdapter(new MyInfoWindowAdapter(name,
                    vicinity));

A: Try following code
MarkerOptions options = new MarkerOptions();
    options.position(origin);
    options.title("Current Location");
    options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
    mMap.addMarker(options);

Hope this will help you


text:
Q: How to configure mouse actions on a linux system? If the question sounded simple, let me specify: I'm using Chrome OS, which is a heavily modified Gentoo distribution, but I have dev mode enabled so i am able to do most things, and in theory everything in commandline that linux should be capable of.
Now the second specificity is that i am addicted to thinkpad trackpoint mouses (or nipples, as you may know them), so i got a lenovo bluetooth keyboard with one (and without a trackpad https://linkgear.jp/uploads/IMG_1361.jpg ).
But: out of the three mouse buttons, chrome os doesn't seem to support the middle mouse triggering the scrolling action to scroll by holding that+moving the trackpoint, therefore i am simply left without scrolling ability.
This limits my performance by like 50%, as opposed to the 25% that my annoyance with trackpads take away in comparison.
Now I haven't been convinved that Chrome OS is incapable of receiving this scrolling mouse action, nor would i easily believe it because it's literally just yetanother linux at core.
I am open to any hacking idea someone might have, but i couldn't find much so far about the mouse interfaces of chrome os or it's certain "Ash" window manager.
Thanks!

A: First use evemu-record to verify what raw physical events arrive (or maybe libinput debug-events to see similar, but libinput-processed events).
Assuming they do, you should be able to build something out of interception-tools to alter those events in-flight – something very similar to the "x2y" example in the project's README, but changing the event code from REL_Y to REL_WHEEL if the button is currently pressed.
bool held = false;
while (..) {
  if (event.type == EV_KEY && event.code == BTN_MIDDLE) {
    held = (bool) event.value;
  } else if (held && event.type == EV_REL && event.code == REL_X) {
    event.code = REL_WHEEL;
  }
  ..
}


text:
Q: I'm trying to make a string accept only letters and space BUT NO NUMBERS This is what I theorized it should be but it seemed like it doesn't work.
HELP PLEAZEE
    int main()
    {
       char input[50];
       int i;

    do{
      printf("ENTER A CHARACTER:");
      scanf("%s",&input);

    if(isalpha(input)!=0){
       printf("YOU INPUTTED A CHARACTER");
       i++;
    }else{
       printf("INVALID INPUT\n");
    }

    }while(i!=1);

    }

A: isalpha takes an integer as an argument.
You are giving a char array.
You should loop for the number of characters given in input[], if you want more than one character (hard to tell from this code).
This exits if you give exactly one character but keeps going if you give more than one:
#include <stdio.h>
#include <string.h>

int main()
{
    char input[50];
    int i = 0, j;
    size_t len = 0;

    do
    {
        printf("ENTER A CHARACTER:");
        scanf("%s",&input);

        len = strlen(input);

        for(j = 0; j < len; j++) {
            if(isalpha(input[j]))
            {
                i++;
                printf("YOU INPUTTED A CHARACTER %d\n", i);
            }
            else
            {
                printf("INVALID INPUT\n");
                break;
            }
        }
    } while(i!=1);
}


text:
Q: Java: Style-Correcting Code: finding comment I'm writing these algorithms for a style-correcting program which makes adjustments to a java source file, that can compile without error. It is currently set to read the file line-by-line.
Right now, I'm having trouble writing 2 methods/algorithms which

*

*Determine if the current line (string) has comments, and

*finds where the comment starts

I currently have:
 public static int FindComment (String TextLine) {
              int EndOfCode = TextLine.lastIndexOf(";  ");
              return TextLine.indexOf("//", EndOfCode);

           }

        public static boolean HasComment (String TextLine) {
           if (TextLine.contains("//"))
           {
              return true;
           }

           else
           {
              return false;
           }
        }

I know this is incorrect because I can have code, and comments, which contain " ; // ; //" as well as comments. I tried other conditional statements without success.

A: Hello you don't explain what problem do you have but I think you should escape with backslash characters when working with indexOf function.


text:
Q: vue.js with Laravel pagination and filtering for list I'm still debating the approach but this is what I have so far. The filters work great but the data list is over 2k items, so some sort of limit is going to need to be applied. The issue is that any limit to the view would have to require a new API pull with any filter being set by any methods I've tried.
My question is should I somehow paginate from the API call or pull all data and paginate with vue? Should I perhaps filter in the backend and apply different API calls or should I use what I have below? The filtering works nicely but I am not clear how I could limit whats displayed yet filter through the entire list then return.
My Vue app and components:
Vue.component('filter', {

props: ['list', 'name'],

template: '#filter-template',

watch: {

    selected: function(currentValue) {

        this.$dispatch('filter-update', [this.name, currentValue]);

    }

}

 });

Vue.component('products', {

template: '#product-template',

created() {

    this.fetchProducts();

},

data:function(){
    return {
        products:[],
        category: 'All',
        collection: 'All',
        design: 'All'
    }
},

events: {

    'push-category': function(id) {

        this.category = id;
        this.filterProducts();

    },

    'push-collection': function(id) {

        this.collection = id;
        this.filterProducts();

    },

    'push-design': function(id) {

        this.design = id;
        this.filterProducts();

    }

},

computed: {

    total: function () {
        return this.products.length;
    }

},

methods: {

    fetchProducts: function() {

        this.$http.get('api/internal/products', function(products) {

            this.$set('products', products);

        });

    },

    filterProducts: function() {

        var parent = this;
        var catFilter = [];
        var collFilter = [];
        var designFilter = [];

        // Collect all the bad guys
        if(this.category == 'All') {
            catFilter = [];
        } else {

            var key = 'Item_Disc_Group';

            filter(key, this.category, catFilter);

        }

        if(this.collection == 'All') {
            collFilter = [];
        } else {

            var key = 'Collection';

            filter(key, this.collection, collFilter);

        }

        if(this.design == 'All') {
            designFilter = [];
        } else {

            var key = 'Fancy_Color_Intensity';

            filter(key, this.design, designFilter);

        }

        // Hide all the bad guys, show any good guys
        for (var i = this.products.length - 1; i >= 0; i--) {
            var product = this.products[i];

            if(catFilter.indexOf(product) > -1) {
                product.On_The_Web = "0";
            } else if(collFilter.indexOf(product) > -1) {
                product.On_The_Web = "0";
            } else if(designFilter.indexOf(product) > -1) {
                product.On_The_Web = "0";
            } else {
                product.On_The_Web = "1";
            }

        };

        function filter(key, active, array) {

            for (var i = parent.products.length - 1; i >= 0; i--) {
                var product = parent.products[i];

                if(product[key] != active) {
                    array.push(product);
                }

            };

        }

    }

}

});

new Vue({

el: '#product-filter',

created() {

    this.fetchCategories();
    this.fetchCollections();
    this.fetchDesigns();

},

methods: {

    fetchCategories: function() {

        this.$http.get('api/categories', function(categories) {

            this.$set('categories', categories);

        });

    },

    fetchCollections: function() {

        this.$http.get('api/collections', function(collections) {

            this.$set('collections', collections);

        });

    },

    fetchDesigns: function() {

        this.$http.get('api/designs', function(designs) {

            this.$set('designs', designs);

        });

    }

},

events: {

    'filter-update': function(data) {

        if(data[0] == "categories") {
            this.$broadcast('push-category', data[1]);
        } else if (data[0] == "collections") {
            this.$broadcast('push-collection', data[1]);
        } else {
            this.$broadcast('push-design', data[1]);
        }

    }

}

});

My markup:

<filter :list="categories" name="categories"></filter>

<filter :list="collections" name="collections"></filter>

<filter :list="designs" name="designs"></filter>

<products></products>

<template id="filter-template">

        @{{ name }}
        <select v-model="selected" class="form-control input-small">
            <option selected>All</option>
            <option value="@{{ option.navision_id }}" v-for="option in list">@{{ option.name }}</option>
        </select>
        Selected: @{{ selected }}

</template>

<template id="product-template">

@{{ total }}

@{{ product.No }}

</template>

A: If the query takes more than a few seconds I would implement the server side filtering, but really thats preference for you.  If you go with client-side filters, you can use the built in filterBy filter:

Just make the default value '' instead of All so that if no filter is selected then the list won't be filtered at all.
<option value="" selected>All</option>

Then you can also use a pagination filter to further page the results (borrowed from this fiddle):
data:function(){
    return {
        currentPage: 0,
        itemsPerPage: 1,
        resultCount: 0
    }
},
computed: {
    totalPages: function() {
      return Math.ceil(this.resultCount / this.itemsPerPage)
    }
},
methods: {
    setPage: function(pageNumber) {
      this.currentPage = pageNumber
    }
},
filters: {
    paginate: function(list) {
        this.resultCount = list.length
        if (this.currentPage >= this.totalPages) {
          this.currentPage = this.totalPages - 1
        }
        var index = this.currentPage * this.itemsPerPage
        return list.slice(index, index + this.itemsPerPage)
    }
}

That would be added last after the filtering:

You'd also want to add buttons to support pagination, ie:

    {{ pageNumber+1 }}


text:
Q: Whats the difference between calling a URL using XMLHttpRequest and a Form? I'm using static html/javascript pages (no php, etc.)
I have a static HTML web page.  When the page loads, it makes an XMLHttpRequest to a target server on another domain, waits for the response, and parses the response JSON.
  function executeRequest() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        var response = JSON.decode(xhttp.responseText);
        alert(response.access_token)
        alert(response.expires_in)
      }
    };
    var tmpURL = "https://target.url.com/oauth2/access_token"
    xhttp.open("POST", tmpURL, true);
    xhttp.send();
  }

XMLHttpRequest cannot load [target.url.com] No 'Access-Control-Allow-Origin'
  header is present on the requested resource.
  Origin 'https://local.url.com' is therefore not allowed access.

To rule out a problem with CORS, I can request the URL with a form. When the user clicks the Submit button, it brings a successful response.
<form method="POST" action="https://target.url.com/oauth2/access_token">
  ... form inputs here
  <input type="submit" value="Submit form">
</form>

Why is the target server responding differently to the xmlHttpRequest than the Form?

A: You have a CORS issue.
XMLHttpRequests are subject to CORS rules.
<form method="POST" action="http://xxx"> posts done purely with HTML are not subject to CORS rules.
It's as simple as that.
Part of the reason this cross origin form post is allowed is that the browser will change the browser window to display the response from the form post so the cross origin site controls what happens next.  That is not the case with XMLHttpRequest where the requesting page controls what happens next as no page is automatically loaded or displayed after an XMLHttpRequest.  So, it's easier to cause mischief with XMLHttpRequest than it is with a form post.
See Cross Domain Form POSTing for some further explanation.


text:
Q: Rails 4 - How to display and play a video file? In rails 4.2.4, I have uploaded one video file using paperclip. How can I display and play it? I have tried to display using <video src="<%= video.document.url %>" controls></video> but it is showing route error.
File url is http://localhost:3000/public/videos/user_1/3/sample_HD.mp4?1461059434
File which is saves under /public/videos/user_1/3/ folder.
How can I display and play a saved video? Do I need to use other method?

A: You can use the video_tag helper which builds an HTML 5 tag. Video files are loaded from 'public/videos' by default.
<%= video_tag "truffle1.mp4", :size => "320x240", :controls => true %>

A: Changing <video src="<%= video.document.url %>" controls></video> to <video src=<%= video.document.url %> controls></video> should fix your problem.


text:
Q: Quick ls command I've got to get a directory listing that contains about 2 million files, but when I do an ls command on it nothing comes back. I've waited 3 hours. I've tried ls | tee directory.txt, but that seems to hang forever.
I assume the server is doing a lot of inode sorting. Is there any way to speed up the ls command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time.

A: This question seems to be interesting and I was going through multiple answers that were posted. To understand the efficiency of the answers posted, I have executed them on 2 million files and found the results as below.
$ time tar cvf /dev/null . &> /tmp/file-count

real    37m16.553s
user    0m11.525s
sys     0m41.291s

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

$ time echo ./* &> /tmp/file-count

real    0m50.808s
user    0m49.291s
sys     0m1.404s

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

$ time ls &> /tmp/file-count

real    0m42.167s
user    0m40.323s
sys     0m1.648s

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

$ time find . &> /tmp/file-count

real    0m2.738s
user    0m1.044s
sys     0m1.684s

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

$ time ls -U &> /tmp/file-count

real    0m2.494s
user    0m0.848s
sys     0m1.452s

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

$ time ls -f &> /tmp/file-count

real    0m2.313s
user    0m0.856s
sys     0m1.448s

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

To summarize the results

*

*ls -f command ran a bit faster than ls -U. Disabling color might have caused this improvement.

*find command ran third with an average speed of 2.738 seconds.

*Running just ls took 42.16 seconds. Here in my system ls is an alias for ls --color=auto

*Using shell expansion feature with echo ./* ran for 50.80 seconds.

*And the tar based solution took about 37 miuntes.

All tests were done seperately when system was in idle condition.
One important thing to note here is that the file lists are not printed in the terminal rather
they were redirected to a file and the file count was calculated later with wc command.
Commands ran too slow if the outputs where printed on the screen.
Any ideas why this happens ?

A: This would be the fastest option AFAIK: ls -1 -f.

*

*-1 (No columns)

*-f (No sorting)

A: Using
ls -1 -f

is about 10 times faster and it is easy to do (I tested with 1 million files, but my original problem had 6 800 000 000 files)
But in my case I needed to check if some specific directory contains more than 10 000 files. If there were more than 10 000 files, I am not anymore interested that how many files there is. I just quit the program so that it will run faster and wont try to read the rest one-by-one. If there are less than 10 000, I will print the exact amount. Speed of my program is quite similar to ls -1 -f if you specify bigger value for parameter than amount of files.
You can use my program find_if_more.pl in current directory by typing:
find_if_more.pl 999999999

If you are just interested if there are more than n files, script will finish faster than ls -1 -f with very large amount of files.
#!/usr/bin/perl
    use warnings;
    my ($maxcount) = @ARGV;
    my $dir = '.';
    $filecount = 0;
    if (not defined $maxcount) {
      die "Need maxcount\n";
    }
    opendir(DIR, $dir) or die $!;
    while (my $file = readdir(DIR)) {
        $filecount = $filecount + 1;
        last if $filecount> $maxcount
    }
    print $filecount;
    closedir(DIR);
    exit 0;

A: You can redirect output and run the ls process in the background.
ls > myls.txt &

This would allow you to go on about your business while its running.  It wouldn't lock up your shell.
Not sure about what options are for running ls and getting less data back.  You could always run man ls to check.

A: ls -U

will do the ls without sorting.
Another source of slowness is --color. On some linux machines, there is a convenience alias which adds --color=auto' to the ls call, making it look up file attributes for each file found (slow), to color the display. This can be avoided by ls -U --color=never or \ls -U.

A: This is probably not a helpful answer, but if you don't have find you may be able to make do with tar
$ tar cvf /dev/null .

I am told by people older than me that, "back in the day", single-user and recovery environments were a lot more limited than they are nowadays.  That's where this trick comes from.

A: I'm assuming you are using GNU ls?
try
\ls

It will unalias the usual ls (ls --color=auto).

A: I have a directory with 4 million files in it and the only way I got ls to spit out files immediately without a lot of churning first was
ls -1U

A: If a process "doesn't come back", I recommend strace to analyze how a process is interacting with the operating system.
In case of ls:
$strace ls

you would have seen that it reads all directory entries (getdents(2)) before it actually outputs anything. (sorting… as it was already mentioned here)

A: Try using:
find . -type f -maxdepth 1

This will only list the files in the directory, leave out the -type f argument if you want to list files and directories.

A: How about find ./ -type f (which will find all files in the currently directory)?  Take off the -type f to find everything.

A: Things to try:
Check ls isn't aliased?
alias ls

Perhaps try find instead?
find . \( -type d -name . -prune \) -o \( -type f -print \)

Hope this helps.

A: What partition type are you using?
Having millions of small files in one directory it might be a good idea to use JFS or ReiserFS which have better performance with many small sized files.

A: Some followup:
You don't mention what OS you're running on, which would help indicate which version of ls you're using.  This probably isn't a 'bash' question as much as an ls question.  My guess is that you're using GNU ls, which has some features that are useful in some contexts, but kill you on big directories.
GNU ls Trying to have prettier arranging of columns.  GNU ls tries to do a smart arrange of all the filenames.  In a huge directory, this will take some time, and memory.
To 'fix' this, you can try:
ls -1 # no columns at all
find BSD ls someplace, http://www.freebsd.org/cgi/cvsweb.cgi/src/bin/ls/ and use that on your big directories.
Use other tools, such as find

A: There are several ways to get a list of files:
Use this command to get a list without sorting:
ls -U

or send the list of files to a file by using:
ls /Folder/path > ~/Desktop/List.txt

A: You should provide information about what operating system and the type of filesystem you are using. On certain flavours of UNIX and certain filesystems you might be able to use the commands ff and ncheck as alternatives.

A: I had a directory with timestamps in the file names. I wanted to check the date of the latest file and found find . -type f -maxdepth 1 | sort | tail -n 1 to be about twice as fast as ls -alh.

A: You can also make use of xargs.  Just pipe the output of ls through xargs.
ls | xargs

If that doesn't work and the find examples above aren't working, try piping them to xargs as it can help the memory usage that might be causing your problems.

A: Lots of other good solutions here, but in the interest of completeness:
echo *


text:
Q: How to overlap images in Xamarin forms I want to design as attached screenshot

I tried using RelativeLayount and AbsoluteLayout but Still not successful to have the required result. Can you help
<RelativeLayout HorizontalOptions="Center">

            <Image Source="XX.png"  />
            <Image Source="YY.png"/>
            <Image Source="WW.png"/>
</RelativeLayout>

These are the three images

A: You can use AbsoluteLayout and specify image positions to make them overlap:
<AbsoluteLayout>
        <Image Source="aa.png" Aspect="Fill" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds=".5,.5,1,1"/>
        <Image Source="bb.png" Aspect="Fill" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds=".5,.5,1,1"/>
</AbsoluteLayout>

But in your case, it will be difficult to adjust the positions since your images are of different scale, and are not symmetrical, it's recommended that you make some adjustment on your images first so that it will be easier for you to put them into the screen.
For more information about AbsoluteLayout, see Xamarin.Forms AbsoluteLayout

A: Option 1 - Use grid with same Row and Column
Option 2 - Use AbsoluteLayout


text:
Q: How to deal with invalid UTF-8 characters in a Perl webapp? How to deal with invalid UTF-8 sequences in data from external file / external command, which data is used to generate HTML (in a Perl web app)?
Currently I am running to_utf8() on each piece of data; said subroutine detects if data is invalid UTF-8, and falls back to 'latin1' encoding:
use utf8;
use Encoding;
binmode STDOUT, ':utf8';

sub to_utf8 {
    my $str = shift;
    return undef unless defined $str;
    if (utf8::valid($str)) {
        utf8::decode($str);
        return $str;
    } else {
        return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
    }
}

Please correct me if this code is incorrect.
The (fragment of) recommended setup in Perl Unicode Essentials from Tom Christiansen's Materials for OSCON 2011 is
use utf8;
use open qw( :encoding(UTF-8) :std );

How to get something similar to what I have using something like above?  I'd prefer automatic handling of Unicode, rather than having to remember to mark all output strings from external commands and files with to_utf8().
The data is from external files, or output from external commands, and it should be in UTF-8, but because of user errors it sometimes it isn't.

A: You can write a custom IO layer that does the "magical" decoding.
Usualy IO layers (like :utf8) are written in XS, but the core module PerlIO::via (see http://search.cpan.org/perldoc?PerlIO::via) allows you to use perl code for that.


text:
Q: How to call this color range in Autodesk Forge Data visualization? How do I use the color range like the following image ? I've looked for it several times in the source code

A: This gradient bar is made with the React component HeatmapOptions and in the Hyperion Reference App, it's called from the BaseApp.
Here's the link to the documentation HeatmapOptions.


text:
Q: I need a good, easy to use open source TTS I'm trying to find a relatively easy to use non-robotic sounding TTS since im not really familiar with python or TTS engine's in general so it's hard for me to just yoink one of those neural network TTS thingies from github and make it work on my machine.
So far i've installed coqui TTS(formerly Mozilla TTS as i understand) and its exactly what i need, however it doesnt work properly for some reason.
When im trying to feed it a sentence that is longer than half of a dozen words it might skip some words or might just stop mid sentence and while its running it has this error:
> Decoder stopped with `max_decoder_steps` 500

So its either:
a). What am i doing wrong with coqui and how do i make it read at least a paragraph of text or how do i fix this error?
or
b). Is there any other easy to use TTS programs that are similar in quality to coqui?


text:
Q: Voice Over is reading ListTile component main section with title and subtitle as a group instead of one element with text

        Title a
        Subtitle lorem Ipsum is nice

        Title b
        Subtitle lorem Ipsum is nice

        Title c
        Subtitle lorem Ipsum is nice

What I want is that when voice over / screen reader is on, is to be able to navigate between ListTiles, inside the ListTileGroup so the screen reader will read each ListTile title and subtitle without adding the word "group", For example Voice Over reads the first ListTile :  "Title a Subtitle lorem Ipsum is nice, group, 1 of 3".

And then:

I tried to remove the roles and change the listtileGroup to ul tag, And listtile's to li tags , but this didn't help.


text:
Q: Describing data of different classes in JSON What are ways to encode a value in JSON which is one of a set of predefined classes, along with class-specific attributes? I also have a requirement that the format can be fully validated with a json-schema (including non-presence of unneeded attributes).
An example would be: it is either a sphere with a specific radius, or a cube with specific dimensions.
A possible encoding for this example is:
{"class": "sphere", "sphereRadius": 1.6}
{"class": "cube", "cubeSizeX": 1, "cubeSizeY": 2, "cubeSizeZ": 3}

But I don't know if it's possible to define a json-schema describing the above format. I would need to specify that sphereRadius must be present if and only if class is equal to "sphere".
I am planning to use this in combination json-editor[1], which will build a user interface based on the schema. The result should be something like a drop-down menu where you select the class, and a set of fields where you enter the class-specific information.
[1] https://github.com/jdorn/json-editor

A: You probably want oneOf, where each option has e.g.:
"properties": {
    "class": {"enum": ["sphere"]}
}

along with any sphere-specific constraints.  The drop-down interface you describe sounds like it would be a good representation for "oneOf" clauses, so that fits.


text:
Q: Google Docs Apps Script сохранение определенных страниц в PDF Всем привет, подскажите пожалуйста мне необходимо,чтобы посредством GAS выполнялось конвертирование doc в pdf и сохранялось в папке на Google Drive в какой-нибудь папке "Work", НО самое важное у меня получилось сделать определенный doc  с определенным ID сконвертировать полностью(весь документ), а мне необходимо чтобы он по очереди все .doc файлы из папки сохранял в pdf со страницами 18-21(например), т.е. не весь документ

A: Средствами Google Apps Script этого сделать невозможно. Документ на печать поставляется целиком в формате pdf, далее уже средствами печати на стороне клиента назначаются параметры печати.
Т.о. чтобы использовать этот процесс в облаке вам необходимо иметь сервер, который будет принимать Документ и параметры для печати. Этот же сервер, после того как он разобьет на нужные страницы, должен будет обратно сохранить файл на ваш Диск.
На первый взгляд кажется, что Google Cloud Functions или Google Cloud Run могут решить эту проблему.


text:
Q: Combining SimpleOneWayItinerary items, from BFM in OTA_AirBookRQ I am having issues, combining some fares, from Bargain Finder Max's SimpleOneWayItineraries (SOAP), when sending to OTA_AirBookRQ. The issue happens simply because some of these one-way fares are not combinable. When sending those itineraries together, the response is the famous NO COMBINABLE FARES FOR CLASS USED.
I suspect, in order to avoid sending these faulty requests, BFM would supply me with a piece of information, that signifies which fares can be priced together.
Despite searching the docs, over and over, I have not found an indicator on each PricedItinerary that signals such information.
Please let me know if the indicator exist, or better yet, how I can avoid displaying these faulty combination of fares, from Bargain Finder Max.

A: The only alternative is to enable Multi-Ticket, which will produce a different ticket for each fare component.
In cases where carriers do not have an agreement, this allows you to combine searches.
It will also retrieve compatible fares if that criteria is met.
I hope this information was useful.


text:
Q: Add properties to a constructor class after loading I have a class Model that gets extended by many other definition models, in this example we'll use HorseModel. These are being used in Vue3, in which webpack is bundling them up as part of the build.
class HorseModel extends Model {
    constructor(record, config = {}){
        super(record, config);
    }

    static getProperties = () => {
        return {
            'rider': {type: RiderModel, nullable: true}
        }
    }
}

class RiderModel extends Model {
    constructor(record, config = {}){
        super(record, config);
    }

    static getProperties = () => {
        return {
            'horse': {type: HorseModel, nullable: true}
        }
    }
}

Originally, I had a properties object as a static property on the definition model class, however these objects may reference other definition models, which in turn may circular reference back to the original definition model, which upsets webpack. To overcome this issue, I wrapped the properties object in a function. This works.
My concern now is that because the properties object isn't something I can just access on the base constructor, I see two not-ideal options:

*

*Call the getProperties function each time I need a value (what I'm doing currently)

*Add the properties when constructing each instance of the definition models, which replicates the otherwise static values in memory for each instance.

I also tried defining the properties object outside of the class, then having getProperties return a reference to that object, so at least all instances would point to the same object. This revealed an immediate issue with self-referencing definition models, Cannot access 'HorseModel' before initialization
Is there some way to add these properties as a static property at some point later, maybe on DOM ready, to avoid the webpack circular reference issue and be able to access these in one place in memory?

Circular ref problem example:
class HorseModel extends Model {
    constructor(record, config = {}){
        super(record, config);
    }

    static properties = {
        'rider': {type: RiderModel, nullable: true}
    }
}

class RiderModel extends Model {
    constructor(record, config = {}){
        super(record, config);
    }

    static properties = {
        'horse': {type: HorseModel, nullable: true}
    }
}

The type property of whichever one is bundled second will be undefined.

A: For circular references and references to classes that have not yet been initialised, creating the object lazily (on access, not with the class definition) is unavoidable. I would recommend a getter for this, not a method.
To make it more efficient and not create a new object on every access, the getter can be memoised. I often do that by making the getter overwrite itself with a normal data property:
class HorseModel extends Model {
    static get properties() {
        const value = {'rider': {type: RiderModel, nullable: true}};
        Object.defineProperty(this, 'properties', {value});
        return value;
    }
}

class RiderModel extends Model {
    static get properties() {
        const value = {'horse': {type: HorseModel, nullable: true}};
        Object.defineProperty(this, 'properties', {value});
        return value;
    }
}

A: This does not work
Upon not being dumb further testing it becomes obvious that the circular reference issue does in fact persist with this implementation. Leaving this up for posterity.

While this doesn't quite go as far as adding the property after load, it does overcome circular- and self-referencing issues while pointing back to a singular instance of the properties object in question:
class HorseModel extends Model {
    constructor(record, config = {}){
        super(record, config);
    }

    static getProperties = () => {
        return _properties;
    }
}

const _properties = {
    'name': {type: String, nullable: true, ...}
    ...
}

Declare the properties object after the class, as the class is not accessing it until the getProperties function is actually called.


text:
Q: Java Web application Displaying data from SQL join I have two db tables.  One table contains Forecast data.  The second table contains Actual data.  I have two javabeans that represent each of these tables.
I want a jsp view (JSTL/EL) that lists the forcasted data, the actual data and then delta between the two in groups of weekly dates, such as this:
                              1/1/11                    1/8/11
 CONTRACT   LineCode     Forecast Actual Delta    Forecast Actual Delta
   B&M       E12-C         12       11    1           25       10    15
   B&M       E11-D         10       15   -5           20       20     0
   Smig      XX2-12        Null     10   -10          20       20     0
   Cartri    WW0-E         etc...

Should I create a 3rd javabean that represents the view above from a SQL JOIN and do all the math in servlets (Or possibly in the SQL itself)?
Or do I pass the two beans and do the math in the jsp view?  If I do the latter, I'm not sure how to do the looping efficiently with jstl.  The two db tables may not have the exact same order or number of rows (as seen with the Null value in the SMIG contract above)

A: In order of preference:
1) Do it in the database,
2) Do it in a POD (JavaBean)
3) (A distant third) Do it in the JSP.


text:
Q: How can I create a custom assignment using a replacement function? I have defined a function called once as follows:
once <- function(x, value) {
    xname <- deparse(substitute(x))
    if(!exists(xname)) {
        assign(xname, value, env=parent.frame())
    }
    invisible()
}

The idea is that value is time-consuming to evaluate, and I only want to assign it to x the first time I run a script.
> z
Error: object 'z' not found
> once(z, 3)
> z
[1] 3

I'd really like the usage to be once(x) <- value rather than once(x, value), but if I write a function once<- it gets upset that the variable doesn't exist:
> once(z) <- 3
Error in once(z) <- 3 : object 'z' not found

Does anyone have a way around this?
ps: is there a name to describe functions like once<- or in general f<-?

A: If you are willing to modify your requirements slightly to use square brackets rather than parentheses then you could do this:
once <- structure(NA, class = "once")
"[<-.once" <- function(once, x, value) {
    xname <- deparse(substitute(x))
    pf <- parent.frame()
    if (!exists(xname, pf)) assign(xname, value, pf)
    once
}

# assigns 3 to x (assuming x does not currently exist)
once[x] <- 3
x # 3

# skips assignment (since x now exists)
once[x] <- 4
x # 3

A: As per item 3.4.4 in the R Language Reference, something like a names replacement is evaluated like this:
 `*tmp*` <- x
 x <- "names<-"(`*tmp*`, value=c("a","b"))
 rm(`*tmp*`)

This is bad news for your requirement, because the assignment will fail on the first line (as x is not found), and even if it would work, your deparse(substitute) call will never evaluate to what you want it to.
Sorry to disappoint you


text:
Q: pytorch не компилируется     [Running] python -u "c:\Users\IGOR\Desktop\py\project.py"
Traceback (most recent call last):
  File "c:\Users\IGOR\Desktop\py\project.py", line 2, in <module>
    import torch
  File "C:\Users\IGOR\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\__init__.py", line 81, in <module>
    from torch._C import *
ImportError: DLL load failed: �� ������� ��������� ���������.

[Done] exited with code=1 in 2.164 seconds

не могу понять почему не компилируется код

A: Была аналогичная проблема, оказалось, версия cuda на компьютере не соответствовала заданной при инсталляции pytorch. Решилось перестановкой последнего, с аккуратным подбором параметра cudatoolkit.


text:
Q: How to prove Θ(g(n)) = O(g(n)) ∩ Ω(g(n)) I came across this statement, as per my understanding  Theta lies between Big O and Omega but I am unable to understand why intersection comes here. Can I get a mathematical as well as analytical understanding for  Θ(g(n)) = O(g(n)) ∩ Ω(g(n))

A: Θ(g(n)) means that the function is bound both above and below by g(n).
Mathematically, if a function f(n) is Θ(g(n)), then

0   ≤   c1.g(n)  ≤  f(n)  ≤  c2.g(n) for all n greater than some constant k

Now,

*

*O(g(n)) is upper bound on g(n), so a function that is O(g(n)) is upper bounded by g(n).

*Ω(g(n)) is lower bound on g(n), so a function that's Ω(g(n)) is lower bound by g(n).
O(g(n)) ∩ Ω(g(n)) is representative of a function sandwiched between g(n) from both above and below, as shown in the image below, which by definition would be Θ(g(n)).

Mathematically, that means the function is 0 ≤ c1.g(n) ≤ f(n) ≤ c2.g(n).


text:
Q: How to split a variable in Perl on tab character? I have a variable $results generated by the following foreachloop
my $result = "";
foreach $c1(sort {$a<=>$b} keys %info ) {
    $result .= $c1 . "\t" .
      join(',',@{$info{$c1}->{var1}}) . "\t" .
      join(',',@{$info{$c1}->{var2}}) . "\n";
}

If I print the results it looks like this
a    b    c
c    d    e
f    g    h

So there are three columns seperated by \t and the lines are separated by \n.
I now want to split this $results variable by tab, to end up with 3 columns. I tried to do this with a while loop, but it's not working
while($result){
    my @columns = split("\t");
}

What am I doing wrong?

A: Without an argument, split splits the value of $_. You want split(/\t/, $result);
Also, the while looks wrong. Perhaps you want
for my $r (split (/\n/, $result)) {
    @columns = split (/\t/, $r);
    :

A: What you have written will produce an endless loop, since while ($result) { ... } will continue as long as $result is a true value, which yours is. Furthermore, if you did split it as you wanted you would get
("a", "b", "c\nd", "e", "f\ng", "h", "i")

which I presume isn't what you want.
You shouldn't join all your data together with tabs and then split it again. Keep it as separate items. Something like
my @results;

foreach my $c1 (sort { $a <=> $b } keys %info ) {
  push @results, [
    $c1,
    join ',', @{ $info{$c1}{var1} },
    join ',', @{ $info{$c1}{var2} }
  ];
}

Then you will have an array of arrays corresponding to the originally printed data. You can print it out for diagnostic purposes using Data::Dump if you wish.

Update
Since you want to retain the values of the first column, which are the sorted keys of the has, you may as well save those separately before looping over them. Perhaps this code suits you better?
my @keys = sort { $a <=> $b } keys %info;
my @results;

foreach my $c1 ( @keys ) {
  push @results, [
    $c1,
    join ',', @{ $info{$c1}{var1} },
    join ',', @{ $info{$c1}{var2} }
  ];
}

Now @keys is the list of values that you wanted.


text:
Q: How to Iterate trough Indeed reviews and find the correspondent job offer, printing the employee review? Having established already a dynamic search for the offers based on companies generating a link where you use it to search it´s available job reviews done by the previous employees, I´m now faced with the question about coding the part that would let me after having assign job offers and job reviews to a list as well as description to iterate through them and print the correspondent.
It all seems easy to do until you notice that job offers list have a different size than job reviews so I´m on a standstill regarding the following situation.
I´m trying the following code which obviously gives me an error since cargo_revisto_list is longer in length than nome_emprego_list because once you have more reviews than job offers this tends to happen, as well as the opposite.
Lists would be per example, the following:
cargo_revisto_list = ["Business Leader","Sales Manager"]
nome_emprego_list = ["Business Leader","Sales Manager","Front-end Developer"]
opiniao_list = ["Excellent Job","Wonderful managing"]

It would be a question of luck to get them to be exactly the same size.
url = "https://www.indeed.pt/cmp/Novabase/reviews?fcountry=PT&floc=Lisboa"
comprimento_cargo_revisto = len(cargo_revisto_list) #19
comprimento_nome_emprego = len(nome_emprego_list) #10
descricoes_para_cargos_existentes = []

if comprimento_cargo_revisto > comprimento_nome_emprego:
    for i in range(len(cargo_revisto_list)):
        s = cargo_revisto_list[i]
        for z in range(len(nome_emprego_list)):
            a = nome_emprego_list[z]
            if(s == a): #A Stopping here needs new way of comparing strings
                c=opiniao_list[i]
                descricoes_para_cargos_existentes.append(c)
elif comprimento_nome_emprego > comprimento_cargo_revisto:
    for i in range(len(comprimento_nome_emprego)):
        s = nome_emprego_list[i]
        for z in range(len(cargo_revisto_list)):
            a = cargo_revisto_list[z]
            if(s == a) and a!=None:
                c = opiniao_list[z]
                descricoes_para_cargos_existentes.append(c)
else:
    for i in range(len(cargo_revisto_list)):
        s = cargo_revisto_list[i]
        for z in range(len(nome_emprego_list)):
            a = nome_emprego_list[z]
            if(s == a):
                c = (opiniao_list[i])
                descricoes_para_cargos_existentes.append(c)

After solving this issue I would need to get the exact review description about the job reviewed that corresponds to the job offer, so to solve this I would get the index of cargo_revisto_list and use that index to print opiniao_list (job description) that matches the job reviewed since it was added to the list at the same time and order by Beautiful Soup at the scraping moment.


text:
Q: java.lang.ArrayIndexOutOfBoundsException: 4 Error I'm new to coding and I've been writing this code and trying to make it work but every time I run it it crashes. I've looked things up and will writing this code I've followed java's website on how to properly write down code as well as this site.
Anyways, it would be greatly appreciated if someone can explain to me why this is not working because it seems to me like the logic is there but I don't get why it crashes.
My code:
    import java.util.Scanner;
    import java.lang.String;
    import java.util.*;
    public class Question1
    {
      public static void main(String[] args)
          {
             Scanner keyboard= new Scanner(System.in);
             System.out.println("Enter either letters or numbers and I'll magically tell you if they are consecutive :D");
             String inputedString= keyboard.nextLine();
             boolean consecutiveOrNot=isConsecutive(inputedString);
             System.out.println("Drum rolls...... Is it consecutive: "+ consecutiveOrNot);  //Problem with this line?
          }

      public static boolean isConsecutive(String inputedString)
          {
            //Storing string's units into an array and converting to UpperCase if necessary
            //and storing string's numerical value into the variable 'arrayCharToInt'
              char[] charIntoArray= new char[inputedString.length()];
              int[] arrayCharToInt= new int[inputedString.length()];
              for (int i=0;i<inputedString.length();i++ )
                {
                   charIntoArray[i]=inputedString.charAt(i);
                    if (Character.isLetter(charIntoArray[i]) && Character.isLowerCase(charIntoArray[i]))
                     {
                        charIntoArray[i]= Character.toUpperCase(charIntoArray[i]);
                      }
                    arrayCharToInt[i]=(int) charIntoArray[i];
                }

           // The next if statements and the methods that they call are used to verify
           //that the content of the initial string is either letters or numbers, but not both together
              boolean[] continuous= new boolean[arrayCharToInt.length];
              boolean[] testContNumbersDecreasing= new boolean[arrayCharToInt.length];
              boolean[] testContNumbersIncreasing= new boolean[arrayCharToInt.length];
              boolean[] testContLettersDecreasing= new boolean[arrayCharToInt.length];
              boolean[] testContLettersIncreasing= new boolean[arrayCharToInt.length];
              Arrays.fill(continuous, true);
               if (lowestValue(arrayCharToInt)>=65 && highestValue(arrayCharToInt)<= 90)
                {
                    for (int x=0;x<arrayCharToInt.length ;x++ )
                    {
                       testContLettersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -25));
                       testContLettersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -25));
                    }
                    return (Arrays.equals(continuous,testContLettersIncreasing) || Arrays.equals(continuous,testContLettersDecreasing));
                }

               else if ((lowestValue(arrayCharToInt) >= 48) && (highestValue(arrayCharToInt)<= 57))
                {
                    for (int x=0;x<arrayCharToInt.length ;x++ )
                    {
                       testContNumbersIncreasing[x]=((arrayCharToInt[x+1]-arrayCharToInt[x]== 1) || (arrayCharToInt[x+1]-arrayCharToInt[x]== -9));
                       testContNumbersDecreasing[x]=((arrayCharToInt[x]-arrayCharToInt[x+1]== 1) || (arrayCharToInt[x]-arrayCharToInt[x+1]== -9));
                    }
                    return (Arrays.equals(continuous,testContNumbersIncreasing) || Arrays.equals(continuous,testContNumbersDecreasing));

                }
              else
                {
                    return false;
                }

          }

      public static int lowestValue(int[] array)
          {
                int lowest=array[0];
                  for (int counter=0; counter< array.length; counter++)
                    {
                      if( lowest>array[counter])
                            lowest= array[counter];
                    }
                    return lowest;
          }

      public static int highestValue(int[] array)
          {
               int highest=array[0];
                for (int counter=0; counter< array.length; counter++)
                    {
                      if( highest<array[counter])
                        highest= array[counter];
                    }
                return highest;
          }

    }

The main method seems to be fine because it put everything in the isConsecutive method as a comment except for 'return true;' and indeed the program ran and printed true. So I know the problem lies somewhere in the second method.
If there's anything that I did not do right please tell me and that would be greatly appreciated. After all I'm still learning.
Thanks

A: All of your calls to arrayCharToInt[x+1] are going to go out of bounds on the last iteration of the loop they're in (for example, if arrayCharToInt.length equals 5, the highest that x is going to go is 4. But then x+1 equals 5, which is out of bounds for an array with five cells). You'll need to put in some sort of if( x == arrayCharToInt.length - 1) check.

A: in the method isConsecutive inside the for loop:   for (int x=0;x<arrayCharToInt.length ;x++ ) , you have used arrayCharToInt[x+1]
if the arrayCharToInt lenth is 4 , then you have arrayCharToInt [0] to arrayCharToInt [3].
now consider this statement:arrayCharToInt[x+1]
when x is 3 this statement will evalueate to arrayCharToInt[4] resulting in array index out of bounds exception

A: This error throw when something went wrong in the Array calling function.
You got the length and make it print.
for eg:
int a[] = {1,2,3,4}

Length of this array is,
int length = a.length

So length = 4 but highest index is 3, not 4. That means index of the array started with 0. So you have to print:
arr[length-1];

In your program,
x == arrayCharToInt.length - 1


text:
Q: What is the Linux process kernel stack state at process creation? I can't find this information anywhere. Everywhere I look, I find things referring to how the stack looks once you hit "main" (whatever your entry point is), which would be the program arguments, and environment, but what I'm looking for is how the system sets up the stack to cooperate with the switch_to macro. The first time the task gets switched to, it would need to have EFLAGS, EBP, the registers that GCC saves, and the return address from the schedule() function on the stack pointed to by "tsk->thread->esp", but what I can't figure out is how the kernel sets up this stack, since it lets GCC save the general purpose registers (using the output parameters for inline assembly).
I am referring to x86 PCs only. I am researching the Linux scheduler/process system for my own small kernel I am (attempting) to write, and I can't get my head around what I'm missing. I know I'm missing something since the fact that Slackware is running on my computer is a testament to the fact that the scheduler works :P
EDIT: I seem to have worded this badly. I am looking for information on how the tasks kernel stack is setup not how the tasks user task is setup. More specifically, the stack which tsk->thread->esp points to, and that "switch_to" switches to.

A: The initial kernel stack for a new process is set in copy_thread(), which is an arch-specific function.  The x86 version, for example, starts out like this:
int copy_thread(unsigned long clone_flags, unsigned long sp,
unsigned long unused,
struct task_struct *p, struct pt_regs *regs)
{
    struct pt_regs *childregs;
    struct task_struct *tsk;
    int err;

    childregs = task_pt_regs(p);
    *childregs = *regs;
    childregs->ax = 0;
    childregs->sp = sp;

    p->thread.sp = (unsigned long) childregs;
    p->thread.sp0 = (unsigned long) (childregs+1);

    p->thread.ip = (unsigned long) ret_from_fork;

p->thread.sp and p->thread.ip are the new thread's kernel stack pointer and instruction pointer respectively.
Note that it does not place a saved %eflags, %ebp etc there, because when a newly-created thread of execution is first switched to, it starts out executing at ret_from_fork (this is where __switch_to() returns to for a new thread), which means that it doesn't execute the second-half of the switch_to() routine.

A: The state of the stack at process creation is described in the X86-64 SVR4 ABI supplement (for AMD64, ie x86-64 64 bits machines). The equivalent for 32 bits Intel processor is probably ABI i386. I strongly recommend reading also Assembly HOWTO. And of course, you should perhaps read the relevant Linux kernel file.

A: Google for "linux stack layout process startup" gives this link: "Startup state of a Linux/i386 ELF binary", which describes the set up that the kernel performs just before transferring control to the libc startup code.


text:
Q: If integral of vector field along closed path is zero, must it be conservative? I know that for any conservative vector field the following is true
$$\oint_C \nabla f \  \mathrm \cdot \ d\vec r = 0$$
However, my question is: if the integral on a closed loop of a vector field evaluates to $0$, then must it be conservative?
Or algebraically put:

Suppose that $\vec F$ is a vector field (we don't know if it's conservative) and $C:\vec r(t)$ is a closed path.
Are the following statements equivalent?
$$\vec F=\nabla f\quad \Longleftrightarrow\quad \oint_C \vec F \  \mathrm \cdot \ d\vec r = 0$$
or should it be $$\vec F=\nabla f\quad \implies\quad \oint_C \vec F \  \mathrm \cdot \ d\vec r = 0$$ instead?

I would like to add the following comment to my question:

For any vector field not of the form $\vec F = \nabla f$, is it the case that $$\oint_C \vec F \  \mathrm \cdot \ d\vec r \neq 0\quad \forall C$$ Or it possible that a vector field of that same form has $$\oint_C \vec F \  \mathrm \cdot \ d\vec r = 0$$ over some $C$.

A: The statements are indeed equivalent as long as the domain $U \subset \Bbb R^n$ of $\vec F$ is path connected (but not necessarily simply connected!). As the proof here explains: if $\vec F: U \to \Bbb R^n$ satisfies $\oint_C \vec F\cdot d \vec r = 0$ for all closed loops in the domain, then an associated potential function $f:U \to \Bbb R$ can be constructed as follows.
Select a fixed element $\vec a \in U$. For every $\vec x \in U$, there exists a path $\gamma[\vec a, \vec x]$ connecting $\vec a$ and $\vec x$. Define
$$
f(\vec x) = \int_{\gamma[\vec a, \vec x]} \vec F(\vec r) \cdot d \vec r.
$$
Because $\vec F$ is conservative (i.e. because of the integral condition), this function is well defined (i.e. we get the same result no matter which path we choose). With this $f$, we indeed find that $\nabla f = \vec F$.


text:
Q: How do I get forms inline with each other? This probably seems like a really dumb question, but i am building a website for my school project and i need to get these two forms next to each other rather then having a line break inbetween them:

  <form action="edexcel_maths.php" method="post">
    <input style="display:inline;" type="submit" name="edmathsbutt" class="button" value="Edexcel Maths">
  </form>

  <form action="aqa_physics.php" method="post">
    <input style="display:inline;" type="submit" name="aqaphybutt" class="button" value="AQA Physics">
  </form>

A: Use display: inline style on the forms.

form {
  display: inline;
}

  <form action="edexcel_maths.php" method="post">
    <input style="display:inline;" type="submit" name="edmathsbutt" class="button" value="Edexcel Maths">
  </form>

  <form action="aqa_physics.php" method="post">
    <input style="display:inline;" type="submit" name="aqaphybutt" class="button" value="AQA Physics">
  </form>


text:
Q: Java HttpClient unit testing with Mockito I am trying to create some unit tests for a service that I created in Java 11 using the java.net.http.HttpClient API.
The code works fine but I am getting java.lang.reflect.InaccessibleObjectException error when running the unit tests.
The Service class:
@Stateless
public class MyWebService {

    @Inject
    private HttpClient httpClient;

    public void makeHttpCall(){

        final HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://someurl.com"))
            .headers(CONTENT_TYPE, "application/json")
            .GET()
            .build();

        final HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

      // business logic
    }
}

The test class is as follows:
@RunWith(MockitoJUnitRunner.class)
public class MyWebServiceTest {

    @InjectMocks
    private MyWebService service;

    @Mock
    private HttpClient httpClient;

    @Test
    public void shouldMakeHttpCallTest(){

        service.makeHttpCall();

        //asserts
    }
}

Am I doing something wrong? I've seen that many people instantiate a new instance of the httpClient within the method itself, however, I am not sure if it is testable that way.
What I was trying to achieve is something like
@RunWith(MockitoJUnitRunner.class)
public class JdkHttpClientServiceShould {

@InjectMocks
private JdkHttpClientService victim;
@Mock
private HttpClient httpClient;

@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void executeRequest() throws Exception {
    HttpResponse httpResponse = mock(HttpResponse.class);
    when(httpClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenReturn(httpResponse);
    when(httpResponse.statusCode()).thenReturn(200);
    when(httpResponse.body()).thenReturn("Hello");

    ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor.forClass(HttpRequest.class);
    ArgumentCaptor<HttpResponse.BodyHandler<String>> bodyHandlerArgumentCaptor = ArgumentCaptor.forClass(HttpResponse.BodyHandler.class);

    ClientResponse clientResponse = victim.executeRequest(HTTP_URL);

    assertThat(clientResponse.getStatusCode()).isEqualTo(200);
    assertThat(clientResponse.getResponseBody()).isEqualTo("Hello");

    verify(httpClient, times(1)).send(httpRequestArgumentCaptor.capture(), bodyHandlerArgumentCaptor.capture());
    assertThat(httpRequestArgumentCaptor.getValue().uri().toString()).isEqualTo(HTTP_URL);
    assertThat(httpRequestArgumentCaptor.getValue().method()).isEqualTo(GET_METHOD);
    assertThat(httpRequestArgumentCaptor.getValue().headers().map()).containsExactly(Assertions.entry(HEADER_KEY_CLIENT_TYPE, Collections.singletonList(JDK_HTTP_CLIENT.getValue())));
    assertThat(bodyHandlerArgumentCaptor.getValue()).isEqualTo(HttpResponse.BodyHandlers.ofString());
}

}
Any help would be great. Thank you
The full stack trace is:
java.lang.reflect.InaccessibleObjectException: Unable to make protected java.net.http.HttpClient() accessible: module java.net.http does not "opens java.net.http" to unnamed module @595b007d

    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:340)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:280)
    at java.base/java.lang.reflect.Constructor.checkCanSetAccessible(Constructor.java:189)
    at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:182)
    at org.mockito.internal.creation.cglib.ClassImposterizer.setConstructorsAccessible(ClassImposterizer.java:86)
    at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:56)
    at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
    at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
    at org.mockito.Mockito.mock(Mockito.java:1285)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:33)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
    at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:43)
    at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:66)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:71)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:55)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:319)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

A: use mockito @Spy
@ExtendWith(MockitoExtension.class) // using junit5

@Mock
HttpResponse<InputStream> mockResponse;

@Spy
HttpClient httpClient;

void test() throws Exception {
  when(httpClient.send(any(), any(HttpResponse.BodyHandlers.ofInputStream().getClass())))
    .thenReturn(mockResponse);

A: This happens because HttpClient is an abstract class. You should Mock the abstract class with CALLS_REAL_METHODS marker or mock implementation.
Here is an example.
Or you can use WireMock to imitate the endpoint you call. Here example


text:
Q: Background image not showing up on my github.io So if you run my code in your editor in default browser the background image appears, but ever since i made it an .io on github, no image is showing up in the background.
Does anyone understand why?! Thanks for any feedback!
How it should be
Whats happening on my .io!
Help!!!!!
Thanks!
https://github.com/Joeyryanbridges/lindseyStyle (github code)

A: Welcome Stack Overflow, Looks like the image path and css background shorthand is wrong.
.centerImg{background: url('../images/succ2.png') no-repeat center fixed ghostwhite;
background-size: 56%;}

Let me know it works for you.


text:
Q: Check My Database Design / PHP/MySQL I'm currently working on improving my database to make room for growth.  As it stands, different users have different 'permissions' to areas of the website.  Some users have permissions to multiple areas of the website.
I'd like some feedback if I'm doing this in the most efficient way:
 tblUsers:
    usrID       usrFirst       usrLast       phone    //etc....
      1            John          Doe
      2            Jane          Smith
      3            Bill          Jones

 tblAreas:
    id      name
     1       Marketing
     2       Support
     3       Human Resources
     4       Media Relations

 tblPermissions:

    id       usrID       areaID
    1          1           2
    2          1           4
    3          2           1
    4          3           3

Right now, for each "area", I have separate directories.  However, I'd like to minimize all of these directories down to one main directory, and then redirect users on logging in to their appropriate 'area' based upon their permissions.
Does it sound like I'm doing this correctly?  I've never created a multi-layered site with different permissions and different groups of people, thus, I'm certainly open to learning more on how to do this correctly.
Thanks very much!

A: The general design is ok.  The issues that pop out on me relate to naming.

*

*SQL doesn't need hungarian notation -- generally considered unnecessary / bad (tblUsers -> users).

*I wouldn't prefix table-names to column-names ...

*... except for column "id" which should always include your table name (i.e. areaId)

*Your "first" and "last" column don't make sense (hint: firstName)

*I'd rename tblPermissions -> userAreas

Depending on your programming language and database, I'd also recommend using underscore instead of capitalization for your table/column-names.
As for using separate directories for different groups, I'd advise against it.  Have the security-checks in your code instead of your directory layout.
Reasoning:
What happens when somebody decides that support is also allowed to do some marketing stuff?  Should you change your code, or add a record into your database?
Or what if you have overlapping actions?
@brianpeiris:  A couple of things come to mind:

*

*No need for column aliases in JOINs

*Makes it easier to search through code ("foo_id" gives less results than "id")

*JOIN USING (foo_id) instead of JOIN ON (foo.id=bar.id).

A: The schema looks fine.
I would suggest that you put access control in the controller and base it of of URL path, so that you are not coding it into every section.

A: Yes, this seems like it is addressing your need perfectly from the database side.
The challenge will be using the data as simply and declaratively as possible. Where is the right place to declare what "area" you are in? Does each page do this, or is there a function that calculates it, or can your controllers do it? as someone suggests. The second part is evaluating the current user against this. Ideally you end up with a single function like "security_check_for_area(4)" that does it all.


text:
Q: I have attempted to create a trivia game. I am having problems with the output I am looking for Trying to understand what I am doing wrong here. The output I get when I type in "ohio" or "amsterdam" (or any other variable) is
Votes:
Robert: 0
Yukio: 0
Andrew: 1

I want the location chosen by the user to give the specified contestant (votesA, votesY, votesR) a point.
favorite_places = {

    'Andrew': {
        'place1': 'Tokyo',
        'place2': 'Amsterdam',
        },

    'Yukio': {
        'place1': 'Osaka',
        'place2': 'Kyoto',
        },

    'Robert': {
        'place1': 'Ohio',
        'place2': 'Queensland',
        'place3': 'Auckland',
        }
}

print("Welcome to location quiz poller.\nThese are the contestants choice of favorite places."
 "Please choose which place is the best, whoever has the most votes will win.")

votesA = 0
votesY = 0
votesR = 0

votinglist = []

for name, place in favorite_places.items():
    #one way to label, access and print nested dictionary values
    places = f"{place['place1']}\n{place['place2']}\n{place.get('place3', '')}\n"
    print(f"{name}'s favorite places are: ")
    print(f"{places}")

print("Which place is the best place?")
inp = input('Enter here: ')
inp = inp.lower()

if inp == 'tokyo' or 'amsterdam':
    votesA += 1

elif inp == 'osaka' or 'kyoto':
    votesY += 1

elif inp == 'ohio' or 'queensland' or 'auckland':
    votesR += 1
else:
    print('That is not a valid selection.  -closing program-')

print(f"Votes:\n\tRobert: {votesR}\n\tYukio: {votesY}\n\tAndrew: {votesA}\n\t")

A: You're having problems due to your conditions.
When you say if inp == 'tokyo' or 'amsterdam':, you're actually saying in simplified English "if input is Tokyo, or there's a string Amsterdam." That is, you're not actually comparing inp to Amsterdam. "Amsterdam" will always evaluate to True, as will any string except empty ones.
What you want is something along the lines of:
if inp == 'tokyo' or inp == 'amsterdam':

or, even better:
if inp in ('tokyo', 'amsterdam'):


text:
Q: How to do this task without creating so many lists? import pandas as pd

#import data
data = pd.read_excel(r"C:\Users\alek racicot\Downloads\TP4-Qualité (excel).xlsx")

titles = list(data.columns)
titles_value = []
echantillions = {}

#return sample mean of each column and add it to titles_value
for column in data:
    sample_mean = sum(data[column])/len(data[column])
    titles_value.append(sample_mean)

#take each element in titles as key and give it corresponding value
for i in range(len(titles)):
    echantillions[(titles[i])]= titles_value[i]

print(echantillions)

A: I'm not sure what your dataset looks like, but it sounds like you're looking for pandas mean. Meaybe try this:
import pandas as pd

#import data
data = pd.read_excel(r"C:\Users\alek racicot\Downloads\TP4-Qualité (excel).xlsx")
data = data.mean(axis=1)
print(data)


text:
Q: Detect handleChange of grouped questions - Reactjs I have a form that contains several questions. Some of the questions contains a group of subquestions.
{
  (this.props.moduleDetails.questions[questionInfo].question_group && this.props.moduleDetails.questions[questionInfo].has_grouped_questions === 1) ?

      {
        (this.props.moduleDetails.questions[questionInfo].question_group )  ?

            { this.renderQuestionGroup(questionInfo) }
            <input type="button" onClick={(e) => { this.addQuestionGroup(questionInfo) }} value="Add" className="btn"/>

          : null
      }

    : null
}

As you can see, renderQuestionGroup is the method that displays the sub-questions.
renderQuestionGroup(questionInfo) {
    let input = [];

    input = this.display(questionInfo)
    return input;
  }

  display(questionInfo) {
      let input = [];
      this.state && this.state.groupedQuestions && this.state.groupedQuestions[questionInfo] && this.state.groupedQuestions[questionInfo].map(
        (qInfo, qIndex) => {
                  if(qInfo !== undefined) {

                    Object.keys(qInfo).map(
                      (questionInfo, index) => {
                        input.push(<QuestionAnswers
                                     questionInfo={qInfo[questionInfo]}
                                     generateStepData={this.props.generateStepData}
                                     userEnteredValues={this.props.formValues}
                                     key={qInfo[questionInfo].module_question_id+qIndex}
                                     groupIndex={qIndex}
                                />)
                  });
                }
      });
     return input;
  }

Subquestions (a group of questions) are placed in state during the componentDidUpdate.
componentDidUpdate = (prevProps, prevState, snapshot) => {
    console.log('prevProps----------->', prevProps);
    console.log('this.props----------->', this.props)
    if (prevProps !== this.props) {
      let questions = this.props.moduleDetails.questions,
          sgq       = {};

      Object.keys(questions).map((qId) => {
        sgq[qId] = (this.state.groupedQuestions[qId]) ? this.state.groupedQuestions[qId] : [];
        let answerId = this.props.formValues[qId],
            questionObj = questions[qId],
            groupedQuestions = [];
        if(questionObj.has_grouped_questions == 1 && answerId != null && (this.state.groupedQuestions != null)) {
          groupedQuestions = questions[qId].question_group[answerId];

          let loopCount = this.getLoopCount(groupedQuestions);

            for(let i=0; i<loopCount; i++) {
              sgq[qId].push(groupedQuestions);
            }
        }
      });
      this.setState({groupedQuestions: sgq});
    }
  }

This works well and the questions get loaded correctly initially. The problem is that during every handleChange event, the method componentDidUpdate is getting triggered which eventually leads to rendering questions again.
I dont want the componentDidUpdate method to invoke during the handlechange event. Any idea on how to fix this?
PS: My idea was to compare  prevProps and this.props. If both are not same, it will be handle change event. But the issue is that  if i remove the condition
if (prevProps !== this.props) {
  ...
}

I am getting an infinite loop during initial load. So what i need is as follows.

*

*Detect handleChange inside componentDidUpdate method.

*Questions to render correctly initially. Currently i am getting an infinite loop if i remove the if (prevProps !== this.props) { ...} condition.

Any help would be appreciated.

A: componentDidUpdate is triggered on each change of the state, this is why you can get infinite loops when you set the state there.
If your new data is coming from  from props then move this logic to getderivedstatefromprops (or componentWillReceiveProps if you are using lower version of react below v16.3).
getderivedstatefromprops
componentWillReceiveProps
As for handle change just set the state inside the handler, no need to listen for changes in componentDidUpdate.