text:
Q: Powershell .NET httpclient add header I want to upload a file using powershell to a RestAPI. Sadly the invoke-restmethod does not support MultipartForm Uploads and even with building my own body it does not work. Therefore, I have to get this working using another way :)
Luckily I found this excellent blog post: http://blog.majcica.com/2016/01/13/powershell-tips-and-tricks-multipartform-data-requests/ and now I'm trying to build me a request using the .NET Client within Powershell. But I do hit my borders right now. I need to edit the standard header to add an authorization token. And I have no clue how! Would somebody please so kind and point me in the right direction how to do this? Thank you very much!
function Invoke-MultipartFormDataUpload
{
    [CmdletBinding()]
    PARAM
    (
        [string][parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]$InFile,
        [string]$ContentType,
        [Uri][parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]$Uri,
        [System.Management.Automation.PSCredential]$Credential
    )
    BEGIN
    {
        if (-not (Test-Path $InFile))
        {
            $errorMessage = ("File {0} missing or unable to read." -f $InFile)
            $exception =  New-Object System.Exception $errorMessage
            $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, 'MultipartFormDataUpload', ([System.Management.Automation.ErrorCategory]::InvalidArgument), $InFile
            $PSCmdlet.ThrowTerminatingError($errorRecord)
        }

        if (-not $ContentType)
        {
            Add-Type -AssemblyName System.Web

            $mimeType = [System.Web.MimeMapping]::GetMimeMapping($InFile)

            if ($mimeType)
            {
                $ContentType = $mimeType
            }
            else
            {
                $ContentType = "application/octet-stream"
            }
        }
    }
    PROCESS
    {
        Add-Type -AssemblyName System.Net.Http

        $httpClientHandler = New-Object System.Net.Http.HttpClientHandler

        if ($Credential)
        {
            $networkCredential = New-Object System.Net.NetworkCredential @($Credential.UserName, $Credential.Password)
            $httpClientHandler.Credentials = $networkCredential
        }

        $httpClient = New-Object System.Net.Http.Httpclient $httpClientHandler

        $packageFileStream = New-Object System.IO.FileStream @($InFile, [System.IO.FileMode]::Open)

        $contentDispositionHeaderValue = New-Object System.Net.Http.Headers.ContentDispositionHeaderValue "form-data"
        $contentDispositionHeaderValue.Name = "fileData"
        $contentDispositionHeaderValue.FileName = (Split-Path $InFile -leaf)

        $streamContent = New-Object System.Net.Http.StreamContent $packageFileStream
        $streamContent.Headers.ContentDisposition = $contentDispositionHeaderValue
        $streamContent.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue $ContentType

        $content = New-Object System.Net.Http.MultipartFormDataContent
        $content.Add($streamContent)

        try
        {
            $response = $httpClient.PostAsync($Uri, $content).Result

            if (!$response.IsSuccessStatusCode)
            {
                $responseBody = $response.Content.ReadAsStringAsync().Result
                $errorMessage = "Status code {0}. Reason {1}. Server reported the following message: {2}." -f $response.StatusCode, $response.ReasonPhrase, $responseBody

                throw [System.Net.Http.HttpRequestException] $errorMessage
            }

            return $response.Content.ReadAsStringAsync().Result
        }
        catch [Exception]
        {
            $PSCmdlet.ThrowTerminatingError($_)
        }
        finally
        {
            if($null -ne $httpClient)
            {
                $httpClient.Dispose()
            }

            if($null -ne $response)
            {
                $response.Dispose()
            }
        }
    }
    END { }
}

A: Try this
#Authorization
$httpClient.DefaultRequestHeaders.Authorization = New-Object System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", $accesstoken);


text:
Q: Make
* elements expand to fill the parent container I have the following HTML:

Welcome to the Information Management Hub

<%= link_to "Customer Information", customer_information_path, :class => "btn btn-default btn-lg" %>

<%= link_to "Customer Information", customer_information_path, :class => "btn btn-default btn-lg" %>

<%= link_to "Customer Information", customer_information_path, :class => "btn btn-default btn-lg" %>

<%= link_to "Customer Information", customer_information_path, :class => "btn btn-default btn-lg" %>

And here is my customized CSS beyond Bootstrap:
.central-nav {
    list-style-type: none;
    width: 100%;
}

.central-nav li {
    display: inline-block;
}

I have tried numerous methods to have the list items expand to the width of the unordered list's parent container (div class="panel-body") and have been unsuccessful.
Is it possible to have the list items expand to the width of the unordered list's parent container?

A: You could try
.central-nav {
  list-style-type: none;
  width: 100%;
  display:table;
}

.central-nav li {
  display: table-cell;
}

A: As suggested by @Paulie_D, the tables is a good first method to try.  It is supported in older browsers and, overall, much easier to implement.
If your app will run on a modern browser and you want more control over how list items shrink or grow, their alignment, etc., then you can try flexbox: http://jsfiddle.net/J7meX/.
Markup:

Item 1

Item 2

Item 3

Styles:
* {
    margin: 0;
    padding: 0;
}

body {
    padding: 10px;
}

ul {
    list-style-type: none;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-direction: row;
    flex-direction: row;
}

ul > li {
    -webkit-flex: 1 1 33%;
    flex: 1 1 33%;
    outline: 1px dotted #000;
    white-space: nowrap;
}

A: You can try following.
.central-nav {
  list-style-type: none;
  width: 100%;
  display:block;
}

.central-nav li {
  display: block;
  width: 100%;
}

A: My apologies - a simple oversight - I forgot I wrapped the UL in a Div.
I created a new class as follows:
.fill-parent {
  width: 100%;
}

I applied that class to the div and the list items expanded to fill the div.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to rotate masked image? Right now my code displays a image like this

It would work if I could just rotate the image clockwise 90 degrees. How would I do this. Code is listed below. I took out some of the unnecessary lines of code for this.
import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var screenView: UIImageView!
    var image1 = UIImage(named: "w")

    func cropImageIntoQuarterSquare(image: UIImage) -> UIImage? {
        //shape of mask
        let image = photoDispaly.image
        let maskingImage = UIImage(named: "mask5")

        //where the masking code starts
        photoDispaly.image = maskImage(image: image!, mask: maskingImage!)
        photoDispaly.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin]
        photoDispaly.contentMode = .scaleAspectFit // OR .scaleAspectFill
        photoDispaly.clipsToBounds = true

        let originalImageSize: CGSize = image!.size
        let smallImageSize = CGSize(width: (originalImageSize.width + 40), height: (originalImageSize.height + 40))
        UIGraphicsBeginImageContext(smallImageSize)
        image?.draw(at: CGPoint.zero)
        let imageResult = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return imageResult
    }

    @IBOutlet var photoDispaly: UIImageView!

    func maskImage(image:UIImage, mask:(UIImage))->UIImage{
        let imageReference = image.cgImage
        let maskReference = mask.cgImage
        let imageMask = CGImage(maskWidth: maskReference!.width,
                                height: maskReference!.height,
                                bitsPerComponent: maskReference!.bitsPerComponent,
                                bitsPerPixel: maskReference!.bitsPerPixel,
                                bytesPerRow: maskReference!.bytesPerRow,
                                provider: maskReference!.dataProvider!, decode: nil, shouldInterpolate: true)
        let maskedReference = imageReference!.masking(imageMask!)
        let maskedImage = UIImage(cgImage:maskedReference!)
        return maskedImage
    }

    func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            return
        } else {
            return
        }
    }

A: you could run a transform on your UIImageView in your ViewDidLoad function
photoDispaly.transform = CGAffineTransform(rotationAngle: M_PI/4)

also you may want to rename Dispaly to Display ;)


text:
Q: Unable to Bind MVC Model on POST I'm writing a view that displays a list of managers. The managers have checkboxes next to their name to select them to be removed from the manager list. I am having problems binding the form submission back to my view model. Here's what the page looks like:

Here's the ViewModel for the page.
public class AddListManagersViewModel
{
    public List<DeleteableManagerViewModel> CurrentManagers;
}

And here's the sub-ViewModel for each of the DeleteableManagers:
public class DeleteableManagerViewModel
{
    public string ExtId { get; set; }
    public string DisplayName { get; set; }

    public bool ToBeDeleted { get; set; }
}

This is the code for the main View:
@model MyApp.UI.ViewModels.Admin.AddListManagersViewModel

        @using (Html.BeginForm("RemoveManagers","Admin"))
        {
            @Html.AntiForgeryToken()
            <fieldset>
                <legend>System Managers</legend>

                            Name
                            Remove

                        @Html.EditorFor(model => model.CurrentManagers)

            </fieldset>

                <button type="submit" class="btn btn-primary">Delete Selected</button>

        }

And this is the EditorTemplate I've created for DeleteableManagerViewModel:
@model MyApp.UI.ViewModels.Admin.DeleteableManagerViewModel

    @Html.DisplayFor(model => model.DisplayName)

        @Html.CheckBoxFor(model => model.ToBeDeleted)
        @Html.HiddenFor(model => model.ExtId)

But when I submit the form to the controller the model comes back null! this is what I want it to do:
[HttpPost]
public virtual RedirectToRouteResult RemoveManagers(AddListManagersViewModel model)
{
    foreach (var man in model.CurrentManagers)
    {
        if (man.ToBeDeleted)
        {
            db.Delete(man.ExtId);
        }
    }
    return RedirectToAction("AddListManagers");
}

I tried following along this post: CheckBoxList multiple selections: difficulty in model bind back but I must be missing something....
Thanks for your help!

A: Hmm. I think this is ultimately the problem; here's what you're posing:
CurrentManagers[0].ToBeDeleted=true&CurrentManagers[0].ToBeDeleted=false&CurrentManagers[0].ExtId=X00405982144

Your model is an AddListManagersViewModel that has a collection of CurrentManagers. So, you're posting an array of DeleteableManagerViewModel, which isn't getting bound to the "wrapper" model. You can try changing the model parameter to
params DeleteableManagerViewModel[] model
I don't ever use the EditorFor extensions, though, so I'm just guessing...


text:
Q: CH101 not correctly responding after firmware transfer I am currently in the process of interfacing with a CH101 ultrasonic sensor. I am using a nucleo STM32 board, with some level shifters for communication with the sensor. I am able to successfully perform the initial connectivity check (Reading from device address 0x45, memory address 0x00 - returns 0x0A 0x02) as per the documentation, and ch_group_start appears to write the firmware to the device. However after writing the firmware I cannot progress further.
The culprit seems to be the ch_common_get_locked_state. I can see that it's attempting to read from the assigned I2C address, but the communication seems to break every time. It should be reading a single byte from I2C address 0x29, register 0x14. I think the sensor might be holding the SDA line low for some reason.
I'm not sure if anyone has experience with this sensor and issues after writing the firmware.

A: This seemed to be an issue with the level shifting board I was using. Swapping it out fixed things luckily!


text:
Q: Standard normal RV probability Z is a standard normal random variable
I need to find $P(|Z|<.95)$, find c such that $P(|Z|<c)$, and given that X is a RV with mean 3 and standard deviation 16, find $P(X>3.84)$
I am just confused by the absolute value bars, what do I do with those?

A: The notation $|x|$ means, "$x$ or $-x$, whichever is greater." For your purposes, what you really need to know is that $|Z| < c$ is the same as writing $-c < Z < c$.
It is perhaps also useful to know that if $Z$ is a standard normal random variable (expected value zero), then $P(Z<-c) = P(Z>c)$, and therefore $P(|Z|<c) = 1 - 2 P(Z > c)$.  In other words, if you cut off the tails of the distribution at equal distances from the middle, so that $5$% of the distribution is in each tail, you will have $10$% of the distribution in the two tails together.


text:
Q: Building Boost C++ Library with XCode 4 (Manual Not Working) First, I've tried http://www.boost.org/doc/libs/1_39_0/more/getting_started/unix-variants.html and Build Boost on Mac with Xcode and Using Boost with Xcode4 in painful detail, to no avail. I've spent about 5 hours on this thus far and have had no luck.
In painful detail, how do I install boost with my XCode C++ project.
What I've tried thus far:
Option 1. XCode -> File -> Add files to "Project Name"
Option 2. Building XCode as per http://www.boost.org/doc/libs/1_39_0/more/getting_started/unix-variants.html. The build works fine, but I cannot get XCode to recognize it.
Option 3. XCode -> Project -> Build Settings -> User Header Search Paths -> Add Build Setting... and adding in the path to the .hpp files
Option 4. XCode -> Targets -> Build Phases -> Link Binary With Libraries -> Add in all the compiled libraries
An interesting observation. The following is recognized by XCode:
#include "boost/asio.hpp"

The following is not recognized by XCode:
#include <boost/asio.hpp>

Please don't send me the same old links from the other articles. I have spent hours reading them.

A: Because the header file is recognised as #include "boost/asio.hpp" but not as #include <boost/asio.hpp>, you might have done the wrong setup in the Xcode code project.
There are two sections in Xcode where you can add a directory to the include path:

*

*"Header Search Paths"

*"User Header Search Paths"

You should use "Header Search Paths" for boost.

A: If you added the actual path to the .hpp files to your include path, then that is your problem.
You're not including asio.hpp, you're including boost/asio.hpp. So the include path should not be the directory that contains asio.hpp, but the directory that contains the boost subdirectory.


text:
Q: Install SQL Server 2000 from Install Shield 2009 Premier I have a basic MSI project in InstallShield 2009 Premier. I have some files(dlls, exes) to be copied, no problem. But what I need to install SQL Server 2000 in addition to this. What I did during development time was to install SQL Server 2000 before development(C#.net). I saw re-distributable "Microsoft SQL Server 2000 Desktop Engine (MSDE 2000) SP3a" (need to be downloaded). But would the installation of this re-distributable do the same job as SQL Server 2000?
Any information about installing "SQL Server 2000" from InstallShield... ?
Same question for installation of "Crystal Reports 2007".

A: If I am understanding your question correctly, adding SQL Server (or Crystal Reports) as a Redistributable should accomplish the same objective, as long as you choose the minimum-required version of SQL server that your application needs.


text:
Q: Type accepting any collection I have collection of Set and List so how can call a function who accept any type of collection ?
Set<X> myset = ...;
myfunction(myset);

List<X> mylist = ...;
myfunction(mylist);

myfunction(T collection){
}

So what would be the type of T ?

A: Collection. List and Set interfaces extends Collection.

A: Both Set and List extend Collection.

A: If you aren't using generics, T is simply a Collection:
void myfunction(Collection collection)

If you are, you could use T extends Collection
<T extends Collection> void myfunction(T collection)


text:
Q: Run a application after saving mail attachment Need to run an application after saving attachment with below script.
how do i call it After end sub?
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    saveFolder = "C:\New folder\tmp\"
    For Each objAtt In itm.Attachments
         objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
         Set objAtt = Nothing
    Next
End Sub

A: To open Application in VBA
Sub OpenApp()
    Dim x As Variant
    Dim Path As String

    '// Application Path
    Path = "C:\Program Files\blabla.exe"

    x = Shell(Path, vbNormalFocus)
End Sub


text:
Q: Publish/Subscribe simultaneously using MQTT I'm trying to make a code that can subscribe and publish operations simultaneously. I have this code below that I think should perform the functions simultaneously but it doesn't seem to be working:

#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Client.h>
#include <Adafruit_MQTT_FONA.h>
//#include <stackThunk.h>

#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

#include "DHT.h"
#define DHTPIN 13
#define DHTTYPE DHT11
#define Relay1            4
#define Relay2            0
#define Relay3            2
#define Relay4            14
//#define WLAN_SSID       "((DREAMNET03132490047))"             // Your SSID
//#define WLAN_PASS       "multan69"
DHT dht(DHTPIN, DHTTYPE);

char str_hum[16];
char str_temp[16];
#define WLAN_SSID       "Connect(ow)03002618017"             // Your SSID
#define WLAN_PASS       "XXXXXXX"        // Your password

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                   // use 8883 for SSL
#define AIO_USERNAME    "XXXXXXXXXXXXXX"            // Replace it with your username
#define AIO_KEY         "XXXXXXXXXXXXXXXXXXXXXXXXXXX"   // Replace with your Project Auth Key

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

/****************************** Feeds ***************************************/

// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay1"); // FeedName
Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay2");
Adafruit_MQTT_Subscribe Light3 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay3");
Adafruit_MQTT_Subscribe Light4 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay4");
Adafruit_MQTT_Publish temp = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Temperature");
Adafruit_MQTT_Publish hum = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Humidity");

void MQTT_connect();

void setup() {

 Serial.begin(115200);
  delay(10);
  dht.begin();
  pinMode(Relay1, OUTPUT);
  pinMode(Relay2, OUTPUT);
  pinMode(Relay3, OUTPUT);
  pinMode(Relay4, OUTPUT);

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Setup MQTT subscription for onoff feed.
  mqtt.subscribe(&Light1);
  mqtt.subscribe(&Light3);
  mqtt.subscribe(&Light2);
  mqtt.subscribe(&Light4);
}

void loop() {

  MQTT_connect();
   // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius (the default)
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit (isFahrenheit = true)
      float f = dht.readTemperature(true);

      // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
      }

      // Compute heat index in Fahrenheit (the default)
      float hif = dht.computeHeatIndex(f, h);
      // Compute heat index in Celsius (isFahreheit = false)
      float hic = dht.computeHeatIndex(t, h, false);
      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print(f);
      Serial.print(" *F\t");
      Serial.print("Heat index: ");
      Serial.print(hic);
      Serial.print(" *C ");
      Serial.print(hif);
      Serial.println(" *F");

      Serial.print("Temperature in Celsius:");
      Serial.println(String(t).c_str());

      Serial.print("Temperature in Fahrenheit:");
      Serial.println(String(f).c_str());

      Serial.print("Humidity:");
      Serial.println(String(h).c_str());

    //dtostrf(gps_latitude, 4, 2, str_temp);
    //dtostrf(gps_longitude, 4, 2, str_hum);

  // Now we can publish stuff!
  Serial.print(F("\nSending Humidity value: "));
  Serial.print(String(h).c_str());
  Serial.print("...");
  if (! hum.publish(String(h).c_str())) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }
delay(1000);
  Serial.print(F("\nSending Temperature value: "));
  Serial.print(String(t).c_str());
  Serial.print("...");
  if (! temp.publish(String(t).c_str())) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

//temperature_work();
  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(20000))) {
    if (subscription == &Light1) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light1.lastread);
      int Light1_State = atoi((char *)Light1.lastread);
    digitalWrite(Relay1, Light1_State);

    }
    if (subscription == &Light2) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light2.lastread);
      int Light2_State = atoi((char *)Light2.lastread);
      digitalWrite(Relay2, Light2_State);
    }
    if (subscription == &Light3) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light3.lastread);
      int Light3_State = atoi((char *)Light3.lastread);
      digitalWrite(Relay3, Light3_State);
    }
    if (subscription == &Light4) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light4.lastread);
      int Light4_State = atoi((char *)Light4.lastread);
      digitalWrite(Relay4, Light4_State);

    }
  }

}

void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;

  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying MQTT connection in 5 seconds...");
    mqtt.disconnect();
    delay(5000);  // wait 5 seconds
    retries--;
    if (retries == 0) {
      // basically die and wait for WDT to reset me
      while (1);
    }
  }
  Serial.println("MQTT Connected!");

}
void temperature_work(){
   delay(2000);

  }

However, when I upload the code of publish and subscription separately, it works fine. Can anyone please take a look at my code attempt and tell me what I'm doing wrong?


text:
Q: "rectifyStereoImages" in MATLAB not working I am working in the Stereo Vision for the first time. I am trying to rectify the stereoImages. The following is the result

I can't understand why the image is getting cropped
The following is my code
% Read in the stereo pair of images.
I1 = imread('sceneReconstructionLeft.jpg');
I2 = imread('sceneReconstructionRight.jpg');

% Rectify the images.
[J1, J2] = rectifyStereoImages(I1, I2, stereoParams);

% Display the images before rectification.
figure;
imshow(stereoAnaglyph(I1, I2), 'InitialMagnification', 50);
title('Before Rectification');

% Display the images after rectification.
figure;
imshow(stereoAnaglyph(J1, J2), 'InitialMagnification', 50);
title('After Rectification');

I am trying to follow this guide
http://www.mathworks.com/help/vision/examples/stereo-calibration-and-scene-reconstruction.html
The images I used

A: Try doing the following:
[J1, J2] = rectifyStereoImages(I1, I2, stereoParams, 'OutputView', 'Full');

This way you will see the entire images.

By default, rectifyStereoImages crops the output images to only contain the overlap between the two frames. In this case the overlap is very small compared to the disparity.
What is happening here is that the baseline (distance between the cameras) is too wide, and the distance to the objects is too short. This results in a very large disparity, which will be hard to compute reliably. I suggest that you either move the cameras closer together, or move the cameras further away from the objects of interest, or both.


text:
Q: Unable to add grid title to gridview using DevExpress vb.net I've tried the following code found on the DevExpress site but I get a NullReferenceException
at the view.Bands.Clear()
Dim view As BandedGridView = TryCast(gridControl1.MainView, BandedGridView)
view.Bands.Clear()

'Create the bands layout.
 Dim bandProdInf As GridBand = view.Bands.Add()
 bandProdInf.Caption = "Notification Details - Drilling"

This would be the look of the gridview that I would like:
https://www.devexpress.com/Support/Center/Attachment/GetAttachmentFile/e5cb046f-fb25-46a4-9ae8-25ba612daa01
"Notification Details - Drilling" would appear as the title of the gridview.

A: The support team from devexpress provided the following right answer:
The GridView offers a built-in mechanism for showing a title via the ViewCaption property. Additionally you will want to set the GridView's OptionsView.ShowViewCaption property to True.
So you would do the following:
gridview1.ViewCaption = "Grid view title"
gridview1.OptionsView.ShowViewCaption = True

A: Captions must be enabled, they're disabled by default.
Add:
  view.OptionsView.ShowViewCaption = true;


text:
Q: Rails validation on new form already done before it is submitted I am adding validation to my posts in my Rails project. Everything works well for edit but on the new form, the alert div already appears before the form is actually submited. How can I fix it in a way that the div only appears on submission of the form if validation returns false.
Thx ;)
posts_controller
def new
    @post = Post.new
end

def create
    post = Post.new(post_params)
    if post.valid?
      post.save
      redirect_to post_path(post.id), success: "..."
    else
      @post = post
      render 'new'
    end
 end

new.html.erb

Nouvel article

<% if @post.invalid? %>

    <% @post.errors.full_messages.each do |message| %>
      <%= message %>

    <% end %>

<% end %>

<%= form_for @post do |f| %>

    Titre de l'article
    <%= f.text_field :name, class: "form-control" %>

    Contenu de l'article
    <%= f.text_area :content, class: "form-control" %>

    <button type="submit" class="btn btn-success">...</button>

<% end %>

A: You may add changed? check to your template:
<% if @post.changed? && @post.invalid? %>

    <% @post.errors.full_messages.each do |message| %>
      <%= message %>

    <% end %>

<% end %>

A: If you use #invalid? this method invokes validation before you assing any attributes. You need to replace if @post.invalid@ with if @post.errors.any?


text:
Q: Undefined property of a typed Array (Typescript)? I've been struggling with a simple problem (but it's already givin' me a headache).
I have the code below:
interface IFoo{
   ReturnFirstBarObject1(): string;
   FillBarArray(array: Array<Bar>): void;
}

class Bar {
  object1: string;
  object2: string;
}

class Foo implements IFoo{
  array: Array<Bar>;

  constructor(){
    this.array = new Array<Bar>();
  }

  public ReturnFirstBarObject1(): string {
     return this.array[0].object1;
  }

  public FillBarArray(array: Array<Bar>): void {
     this.array = array;
  }
}

$(document).ready(function(){
  var foo = new Foo();

  $.get('url/getBars?FooID=1')
   .done(function(data: any){
       foo.FillBarArray(data);
   });

  var object1 = foo.ReturnFirstBarObject1();
});

I don't know why but object1 returns for me as 'undefined' and when I highlight 'this.array[0]' it returns a JSon like this
"{'object1' : 'someString', 'object2' : 'someString'}"

I want to access object1 but it returns undefined and I can't do a workaround on the Json because typescript recognize the array object as a Bar.
Anyone knows why this is happening and what can I do to access Bar property properly ?

A: It seems you are trying to get the first element before you have filled the array,
below code executes before your ajax calls fills the array, hence you are getting undefined error.
var object1 = foo.ReturnFirstBarObject1();

If you move this code inside ajax call it should work,
$.get('url/getBars?FooID=1')
  .done(function(data: Array<Bar>){
     foo.FillBarArray(data);
     var object1 = foo.ReturnFirstBarObject1();
});

A: The result here is a json string not a json object. Try $.getJSON.
Also @Madhu Ranjan's answer about jquery's callback possibly returning after the call to ReturnFirstBarObject1 is another thing to consider that could cause this problem.


text:
Q: Python: yahoo_fin.stock_info.get_quote_table() not returning table Goal:
The goal is to generate a robot in replit which will iteratively scrape yahoo pages like this amazon page, and track the dynamic 'Volume' datapoint for abnormally large changes. I'm currently trying to be able to reliably pull this exact datapoint down, and I have been using the yahoo_fin API to do so. I have also considered using bs4, but I'm not sure if it is possible to use BS4 to extract dynamic data. (I'd greatly appreciate it if you happen to know the answer to this: can bs4 extract dynamic data?)
Problem:
The script seems to work, but it does not stay online due to what appears to be an error in yahoo_fin. Usually within around 5 minutes of turning the bot on, it throws the following error:
  File "/home/runner/goofy/scrape.py", line 13, in fetchCurrentVolume
    table = si.get_quote_table(ticker)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/yahoo_fin/stock_info.py", line 293, in get_quote_table
    tables = pd.read_html(requests.get(site, headers=headers).text)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/util/_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/html.py", line 1098, in read_html
    return _parse(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/html.py", line 926, in _parse
    raise retained
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/html.py", line 906, in _parse
    tables = p.parse_tables()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/html.py", line 222, in parse_tables
    tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pandas/io/html.py", line 552, in _parse_tables
    raise ValueError("No tables found")
ValueError: No tables found

However, this usually happens after a number of tables have already been found.
Here is the fetchCurrentVolume function:
import yahoo_fin.stock_info as si

def fetchCurrentVolume(ticker):

  table = si.get_quote_table(ticker)
  currentVolume = table['Volume']

  return currentVolume

and the API documentation is found above under Goal. Whenever this error message is displayed, the bot exits a @tasks.loop , and the robot goes offline. If you know of a way to fix the current use of yahoo_fin, OR any other way to obtain the dynamic data found in this xpath: '//div[@id="quote-summary"]/div/table/tbody/tr'  , then you will have pulled me out of a 3 weeks long debacle with this issue! Thank you.

A: If you are able to retrieve some data then it cuts out, it is probably due to a rate limit. Try adding a sleep of a few seconds between each one.
see here for how to use sleep

A: Maybe the web server bonks out when the tables are being re-written every so often. Or something like that.
If you use a try/except waited a few seconds and then tried again before bailing out to a failure maybe that would work if it is just a hicup once in a while?
import yahoo_fin.stock_info as si
import time

def fetchCurrentVolume(ticker):
    try:
        table = si.get_quote_table(ticker)
        currentVolume = table['Volume']
    except:
        # hopefully this was just a hicup and it will be back up in 5 seconds
        time.sleep(5)
        table = si.get_quote_table(ticker)
        currentVolume = table['Volume']
    return currentVolume


text:
Q: Doctrine array type in Entity and MySQL (Symfony2) I want to work with Roles users in my Entity User Doctrine for backend engine. My authentification work correctly if I fixed static role in entity but if I want to retrieve that from my BDD MySQL I have a unserialize error.
My MySQL Field is in a Text (or Longtext) types and contain just one role like this : "ROLE_ADMIN" or "ROLE_USER". I have tried same think with field like this "ADMIN" or "USER" but nothing change.
Can you tell me why my retrieve Roles bug please ?
gist : Entity User Doctrine gist here

A: For solve lot of problems with serialize or deserialize the good way is work with fixtures data and encode those directly.
The deserialisation proceed run correctly without error because you encode your data with specific encodage php symfony code.
For first time, this is not very efficient to complete your database in SQL query directly.


text:
Q: HTML Table fit screen height So this is how my page look like right now (the colors is just to see the containers):
This is my PHP code:

Leaderboard uke

                                    Nr.

                                    Navn
                                    Salg

                                <?php
                                $currentRow = 0;
                                foreach($link->query('SELECT idn,COUNT(*) FROM usr') as $row) {
                                    echo "
";
                                    $currentRow++;
                                    if ($currentRow == 1) {
                                        echo "	";
                                    }
                                    if ($currentRow == 2) {
                                        echo "	";
                                    }
                                    if ($currentRow == 3) {
                                        echo "	";
                                    }
                                    if ($currentRow > 3) {
                                        echo "$currentRow	";
                                    }
                                    echo "	";
                                    $sql = "SELECT * FROM usr WHERE idn='{$row['idn']}'";
                                    $resultt = $link->query($sql);
                                    if ($resultt->num_rows > 0) {
                                         while($roww = $resultt->fetch_assoc()) {
                                             echo "" . $roww['fullname'] . "	";
                                         }
                                    }
                                    echo "" . $row['COUNT(*)'] . "	";
                                    echo "
";
                                }
                                ?>

CSS:
.containerrr {
    background-color: red;
    height: 900px;
    position: relative;
}

.containerrr > header {
    margin: 0 auto;
    padding: 1em;
    text-align: center;
}

.containerrr > header h1 {
    font-weight: 600;
    font-size: 3em;
    margin: 0;
}

.wrapperrr {
    line-height: 1.5em;
    margin: 0 auto;
    padding: 2em 0 3em;
    width: 90%;
    max-width: 2000px;

    background-color: blue;

    height: 100%;
}

table {
    border-collapse: collapse;
    width: 100%;
    background: #fff;
    table-layout: auto;
}

I want the table to fit the container(red color). But now I need to scroll down to see all the table data. How can I resize(in this case make it smaller), so all the rows fits the red area, so I don't have to scroll down? What am I missing here?

A: Add display: flex and flex-direction: column in containerrr class.

.containerrr {
    display: flex;
    flex-direction: column;
    background-color: red;
    height: 900px;
    position: relative;
}

.containerrr > header {
    margin: 0 auto;
    padding: 1em;
    text-align: center;
}

.containerrr > header h1 {
    font-weight: 600;
    font-size: 3em;
    margin: 0;
}

.wrapperrr {
    line-height: 1.5em;
    margin: 0 auto;
    padding: 2em 0 3em;
    width: 90%;
    max-width: 2000px;

    background-color: blue;

    height: 100%;
}

table {
    border-collapse: collapse;
    width: 100%;
    background: #fff;
    table-layout: auto;
}

Leaderboard uke

                                    Nr.

                                    Navn
                                    Salg

                                <?php
                                $currentRow = 0;
                                foreach($link->query('SELECT idn,COUNT(*) FROM usr') as $row) {
                                    echo "
";
                                    $currentRow++;
                                    if ($currentRow == 1) {
                                        echo "	";
                                    }
                                    if ($currentRow == 2) {
                                        echo "	";
                                    }
                                    if ($currentRow == 3) {
                                        echo "	";
                                    }
                                    if ($currentRow > 3) {
                                        echo "$currentRow	";
                                    }
                                    echo "	";
                                    $sql = "SELECT * FROM usr WHERE idn='{$row['idn']}'";
                                    $resultt = $link->query($sql);
                                    if ($resultt->num_rows > 0) {
                                         while($roww = $resultt->fetch_assoc()) {
                                             echo "" . $roww['fullname'] . "	";
                                         }
                                    }
                                    echo "" . $row['COUNT(*)'] . "	";
                                    echo "
";
                                }
                                ?>


text:
Q: Sonata admin stores a flash message after ajax call I have a dependent fields in my configureFormFields method.

I use Symfony form events for that. In my admin class I wrote the the following code:
$formModifierPet = function (FormInterface $form, User $user = null) {
        $pets = null === $user ? [] : $this
            ->getConfigurationPool()
            ->getContainer()
            ->get('doctrine')
            ->getRepository(Pet::class)
            ->findBy([ 'user' => $user ]);

        $form->add('pet', EntityType::class, [
            'class'       => Pet::class,
            'placeholder' => 'Select Pet',
            'attr'        => [
                'class' => 'js-set-pets-user'
            ],
            'choices'     => $pets,
            'multiple'    => true
        ]);
    };

    $formMapper->getFormBuilder()->addEventListener(
        FormEvents::PRE_SET_DATA,
        function (FormEvent $event) use ($formModifierPet) {
            $formModifierPet($event->getForm(), $this->getSubject()->getUser());
        }
    );

    $formMapper->getFormBuilder()->get('user')->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) use ($formModifierPet) {
            $formModifierPet($event->getForm()->getParent(), $event->getForm()->getData());
        }
    );

And it's works fine, but when I click update button - sonata shows the following:

I've tried to dump the session and it seems that the flash message appears right after the ajax call. Can you please help me with that?
My service.yml:
admin.event:
  class: AdminBundle\Admin\EventAdmin
  arguments: [~, KKCBundle\Entity\Event, AdminBundle\Controller\Admin\EventAdminController]
  tags:
    - { name: sonata.admin, manager_type: orm, label: All Events }
  calls:
    - [ setTemplate, [ edit, SonataAdmin/AdminBundle/EventAdmin/edit.html.twig ]]

A: The problem is resolved. It was in the difference of sonataAdmin versions. E.g. my sonata version is:
"sonata-project/admin-bundle": "3.57.0" where I can see the following lines:
vendor/sonata-project/admin-bundle/src/Controller/CRUDController.php (editAction)

if (!$isFormValid) {
    if ($this->isXmlHttpRequest() && null !== ($response = $this->handleXmlHttpRequestErrorResponse($request, $form))) {
        return $response;
    }

    $this->addFlash(
        'sonata_flash_error',
            $this->trans(
                'flash_edit_error',
                    ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
                    'SonataAdminBundle'
                )
            );
} elseif ($this->isPreviewRequested()) {
            // enable the preview template if the form was valid and preview was requested
      $templateKey = 'preview';
            $this->admin->getShow();
        }
    }

but in another version of sonata 3.54.1 there is another code:
if (!$isFormValid) {
            if (!$this->isXmlHttpRequest()) {
                $this->addFlash(
                    'sonata_flash_error',
                    $this->trans(
                        'flash_edit_error',
                        ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
                        'SonataAdminBundle'
                    )
                );
            }
        } elseif ($this->isPreviewRequested()) {
            // enable the preview template if the form was valid and preview was requested
            $templateKey = 'preview';
            $this->admin->getShow();
        }

So, to avoid the unnecessary error message I overwrote the default edit action with the code from the version 3.54.1
I hope it saves someone a lot of time


text:
Q: R Regex / gsub : How to collapse spaces in a string I have a vector of sentences that were scanned from handwritten documents.  In the process there were some spacing problems like this:
 The d og is br own.

I was curious if there was a way to generically take any pattern with '_x_' or space-character-space and collapse the second space like this:
The d og is br own.  --> The dog is br own.

I'm only worried about a single character between the spaces  ('_x_' NOT '_xx_').
Any suggestions?

A: Maybe
> x<-"The d og is br own."
> gsub(" (.) "," \\1",x)
[1] "The dog is br own."

or
gsub(" ([[:alnum:]]) "," \\1",x)

(.) matches anything ([[:alnum:]]) matches alphanumeric characters only.


text:
Q: Tpt script issue to load Clob datatypes into teradata I am writing my first tpt script. My requirement is basic. I want to load a table in exadata ( which has clob and blob datatypes as well) into teradata.
I have come across few posts saying i can only use sql inserter operator to load clob and blob types. I have found below script:
SET TdpId=
SET UserName=
SET UserPassword=
DEFINE JOB LOADING_LOB_DATA
DESCRIPTION 'LOAD PRODUCT DEFINITION TABLE'
(

DEFINE SCHEMA SOURCE_SCHEMA
DESCRIPTION 'PRODUCT INFORMATION SCHEMA'
(
     COL1_ID VARCHAR(38),
     COL2_CLOB CLOB(50000) AS DEFERRED BY NAME,
     COL3_BLOB BLOB(100000) AS DEFERRED BY NAME
);

DEFINE OPERATOR DDL_OPERATOR()
DESCRIPTION 'DDL Operator'
TYPE DDL
ATTRIBUTES
(
    VARCHAR ARRAY ErrorList = ['3706','3803','3807'],
    VARCHAR DateForm,
    VARCHAR TraceLevel = 'None',
    VARCHAR PrivateLogName = 'ddllog',
    VARCHAR TdpId = @TdpId,
    VARCHAR UserName = @UserName,
    VARCHAR UserPassword = @UserPassword,
    VARCHAR AccountID,
    VARCHAR WorkingDatabase
);

DEFINE OPERATOR FILE_READER ()
DESCRIPTION 'DataConnector READER Operator'
TYPE DATACONNECTOR PRODUCER
SCHEMA SOURCE_SCHEMA
ATTRIBUTES
(
    VARCHAR TraceLevel = 'None',
    VARCHAR PrivateLogName = 'dtac_r_log',
    VARCHAR DirectoryPath = @SourceDirectoryPath,
    VARCHAR FileName = @SourceFileName,
    VARCHAR OpenMode = 'Read',
    VARCHAR IndicatorMode,
    VARCHAR Format = @SourceFileFormat
);

DEFINE OPERATOR SQL_INSERTER ()
DESCRIPTION 'TERADATA INSERTER UTILITY'
TYPE INSERTER
INPUT SCHEMA *
ATTRIBUTES
(
    VARCHAR TraceLevel = 'None',
    VARCHAR PrivateLogName = 'ins_log',
    VARCHAR Tdpid = @TdpId,
    VARCHAR UserName = @UserName,
    VARCHAR UserPassword = @UserPassword
);

STEP CREATE_SOURCE_TABLE
(
    APPLY
    ('drop table ' || @SourceTable || ' ;'),
    ('create table ' || @SourceTable || ' , FALLBACK ,
     NO BEFORE JOURNAL,
     NO AFTER JOURNAL
   (
        col1_id VARCHAR(38),
        col2_clob clob(50000),
        col3_blob blob(100000)
    ) primary index (col1_id);')

   TO OPERATOR ( DDL_OPERATOR () );
);

STEP LOADING_DATA_TO_SOURCE_TABLE
(
    APPLY

     ('INSERT INTO ' || @SourceTable || ' values (
        :COL1_ID, :COL2_CLOB, :COL3_BLOB);')

   TO OPERATOR (SQL_INSERTER [1])

   SELECT * FROM OPERATOR (FILE_READER ());
);

);

Can anyone tell me what's the use of file_reader() operator and ddl_operator here? Won't i require a ODBC_OPERATOR first here and then a sql opertaor?
Please help me with this.


text:
Q: How to run custom Python script on Jupyter Notebook launch (to boot Spark)? I found several tutorials on how to configure IPython Notebook to load Spark Context variable sc using PySpark (like this one: http://ramhiser.com/2015/02/01/configuring-ipython-notebook-support-for-pyspark/).
The problem is, since now we are using Jupyter Notebook instead of IPython Notebook, we can't create a setup script to load the Spark Context variable like we did with IPython (which should be located in ~/.ipython/profile_pyspark/startup/00-pyspark-setup.py).
The question is: What are the configurations on Jupyter Notebook that will execute the script 00-pyspark-setup.py on startup?

A: EDIT
The original answer should still work, but it is unwieldy and we use the following method nowadays that uses PySpark built in variables:
export PYSPARK_DRIVER_PYTHON=jupyter
export PYSPARK_DRIVER_PYTHON_OPTS="notebook"

Then just run PySpark directly like you would normally, but with the above variables set it starts jupyter notebook rather than a shell:
cd path/to/spark
bin/pyspark --master local[*]  # Change to use standalone/mesos/yarn master and add any spark config

If you start a new notebook you will find Spark set up for you. You can add other options to Juopyter if you want to match your environment, like:
export PYSPARK_DRIVER_PYTHON_OPTS="notebook --ip='*' --no-browser"

ORIGINAL ANSWER
You can still set up things with the same initial steps, ie create a profile using ipython profile create pyspark and place the startup script in $(ipython profile locate pyspark)/startup/.
Next, to make it available in Jupyter notebooks you have to specify a kernel that uses that profile, by creating a file $(ipython locate)/kernels/pyspark/kernel.json. This is what mine looks like:
{
  "display_name": "PySpark",
  "language": "python",
  "argv": [
    "python",
    "-m", "ipykernel",
    "--profile=pyspark",
    "-f", "{connection_file}"
  ],
  "env": {
    "PYSPARK_SUBMIT_ARGS": " --master spark://localhost:7077 --conf spark.driver.memory=20000m  --conf spark.executor.memory=20000m"
  }
}

The important bit is in the argv section. The information in the env section is picked up by the startup script I use:
import os
import sys

spark_home = '/opt/spark/'
os.environ["SPARK_HOME"] = spark_home
sys.path.insert(0, spark_home + "/python")
sys.path.insert(0, os.path.join(spark_home, 'python/lib/py4j-0.9-src.zip'))

pyspark_submit_args = os.environ.get("PYSPARK_SUBMIT_ARGS", "")
pyspark_submit_args += " pyspark-shell"
os.environ["PYSPARK_SUBMIT_ARGS"] = pyspark_submit_args

filename = os.path.join(spark_home, 'python/pyspark/shell.py')
exec(compile(open(filename, "rb").read(), filename, 'exec'))

As you can see it is quite similar to the one you linked, just plus the arguments that are defined in the kernel, and addition of pyspark-shell argument which is needed in latest version of PySpark.
Whit this, you can run jupyter notebook, open the main page in a browser and you can now create notebooks using this new kernel:


text:
Q: NodeJS - Promise.each error I couldn't debug Using Bluebird, I've been trying to make operations on an array by Promise.each sequentially but I couldn't. Indeed, it says the following :
ERROR_DESCRIPTION
Here is the code :

'use strict';

const express = require('express');
const router = express.Router();
const Promise = require('bluebird');

router.get('/', function(req, res, next) {

  let test = [1, 2, 3];
  Promise.each(test).then((values,index) => {
      console.log(values);

      res.setHeader('Content-Type', 'application/json');
      res.send(JSON.stringify("okok"));

    });
});

module.exports = router;

Thanks

A: This is how you need to use Promise.each and you should include res.send outside the promise.each as it execute more than once, you will be end up sending res multiple times.
'use strict';

const express = require('express');
const router = express.Router();
const Promise = require('bluebird');

router.get('/', function (req, res, next) {

  let test = [1, 2, 3];
  Promise.each(test,(values) => {
    console.log(values);
  });
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify("okok"));

});

module.exports = router;


text:
Q: docker images listed, but not able to delete i am trying to run container using image, but it doesn't detect image locally. whereas the images are listed as shown below. To recover i thought of deleting and re-running. But, i get error in deleting the listed image:
Also, I will like to highlight that i have uninstalled and re-installed docker between first time and 2nd time running the below cmd to start container.
Here is the sequence of steps i have done:

*

*Command to run container (which downloaded image when i ran it first)

docker container run --name jenkins-docker --rm --detach \
>   --privileged --network jenkins --network-alias docker \
>   --env DOCKER_TLS_CERTDIR=/certs \
>   --volume jenkins-docker-certs:/certs/client \
>   --volume jenkins-data:/var/jenkins_home \
>   --volume "$HOME":/home docker:dind

*Uninstalled and re-installed docker

*Re-run above cmd to start conatiner (got below error)

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers).
See 'docker run --help'.

*list image

REPOSITORY            TAG                 IMAGE ID            CREATED             SIZE
jenkinsci/blueocean   latest              b9a3e09d0e84        22 hours ago        549MB
docker                dind                8489eeb24a26        4 days ago          237MB

*Validate that no container is running

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

*Deleting images :

Error: No such image: b9a3e09d0e84

docker rmi 8489eeb24a26
Error: No such image: 8489eeb24a26

A: to force delete all containers, run:
docker rm -f $(docker ps -a -q)

to force delete all images, run:
docker rmi -f $(docker images -a -q)

to check containers have been deleted, run:
docker ps -a

to check images have been deleted, run
docker images -a

you can see errors like following at image deletion time, but you'll see by running docker images -a that there is nothing left
Error: No such image: 1203fc0eeda3

A: Had a similar issue where podman created an image duplicate listed as
REPOSITORY   TAG      IMAGE ID       CREATED         SIZE
<none>       <none>   b6513bbf3672   7 minutes ago   116 MB

Force deleting with
docker rmi -f $(docker images -a -q)

as suggested by fredericrous solved it!


text:
Q: Eslint unable to find errors on .ts files I generated SvelteKit project using npm create svelte@latest and added some .ts files for some library but running eslint . it cant find errors.
I have this default eslint config generate from svelte.
.eslintrc.cjs
module.exports = {
    root: true,
    parser: '@typescript-eslint/parser',
    extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'],
    plugins: ['svelte3', '@typescript-eslint'],
    ignorePatterns: ['*.cjs'],
    overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
    settings: {
        'svelte3/typescript': () => require('typescript')
    },
    parserOptions: {
        sourceType: 'module',
        ecmaVersion: 2020
    },
    env: {
        browser: true,
        es2017: true,
        node: true
    }
};

and tsconfig.json
{
    "extends": "./.svelte-kit/tsconfig.json",
    "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "checkJs": true,
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "resolveJsonModule": true,
        "skipLibCheck": true,
        "sourceMap": true,
        "strict": true
    }
}

I have this lint on package.json
"lint": "prettier --check --plugin-search-dir=. . && eslint .",

Running npm run lint it cant find any errors even there is clearly an error to a .ts file.
It only can detect errors from .svelte files.
Is there something wrong with my eslint or tsconfig or I miss something?

A: My bad, it is linting the .ts files but some rules is missing from what i used to be and not showing errors so I add some rules instead of using the default one and now it showing errors.
Here is my new config
module.exports = {
    root: true,
    parser: '@typescript-eslint/parser',
    extends: [
        'eslint:recommended',
        'plugin:node/recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:@typescript-eslint/recommended-requiring-type-checking',
        'prettier'
    ],
    plugins: ['node', 'prettier', 'svelte3', '@typescript-eslint'],
    ignorePatterns: ['*.cjs', 'svelte.config.js', 'vite.config.js'],
    overrides: [
        { files: ['*.svelte'], processor: 'svelte3/svelte3' },
        {
            files: ['*.ts', '*.js', '*.svelte'],
            parser: '@typescript-eslint/parser',
            extends: ['plugin:@typescript-eslint/recommended'],
            rules: {
                'node/no-missing-import': 'off',
                'node/no-unpublished-import': 'off'
            }
        }
    ],
    settings: {
        'svelte3/typescript': () => require('typescript')
    },
    parserOptions: {
        sourceType: 'module',
        ecmaVersion: 2020,
        project: ['./tsconfig.json']
    },
    env: {
        browser: true,
        es2017: true,
        node: true
    },
    rules: {
        'prettier/prettier': 'error',
        'block-scoped-var': 'error',
        eqeqeq: 'error',
        'no-var': 'error',
        'prefer-const': 'error',
        'eol-last': 'error',
        'prefer-arrow-callback': 'error',
        'no-trailing-spaces': 'error',
        quotes: ['warn', 'single', { avoidEscape: true }],
        'no-restricted-properties': [
            'error',
            {
                object: 'describe',
                property: 'only'
            },
            {
                object: 'it',
                property: 'only'
            }
        ]
    }
};


text:
Q: MOSS 2007 Attempted to read or write protected memory My production Sharepoint 2007 has been working well until the last weekend. Monday morning the users noticed http error 500 coming from the server. Looking into the application logs show hundreds of error event messages apparently related to corrupt memory. The following three error messages were repeated hundreds of times over the span of three days:

Event Source:     Windows SharePoint Services 3
  Event Category:   Timer
  Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Event Source:     Windows SharePoint Services 3
  Event Category:   General
  The description for Event ID ( 27745 ) in Source ( Windows SharePoint Services 3 ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event: #50071: Unable to connect to the database PMDG_SharePoint_Config on DBCL2K5P3\DB53.  Check the database connection information and make sure that the database server is running..
Event Source:     Office SharePoint Server
  Event Category:   Office Server Shared Services
  Message: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Techinal Support Details:
  System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
     at System.DirectoryServices.Interop.UnsafeNativeMethods.IntADsOpenObject(String path, String userName, String password, Int32 flags, Guid& iid, Object& ppObject)
     at System.DirectoryServices.Interop.UnsafeNativeMethods.ADsOpenObject(String path, String userName, String password, Int32 flags, Guid& iid, Object& ppObject)
     at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
     at System.DirectoryServices.DirectoryEntry.Bind()
     at System.DirectoryServices.DirectoryEntry.get_IsContainer()
     at System.DirectoryServices.DirectoryEntries.CheckIsContainer()
     at System.DirectoryServices.DirectoryEntries.Find(String name, String schemaClassName)
     at Microsoft.SharePoint.Metabase.MetabaseObjectCollection1.Find(String name)
     at Microsoft.SharePoint.Metabase.MetabaseObjectCollection1.get_Item(String name)
     at Microsoft.SharePoint.Administration.SPProvisioningAssistant.ProvisionIisApplicationPool(String name, ApplicationPoolIdentityType identityType, String userName, SecureString password, TimeSpan idleTimeout, TimeSpan periodicRestartTime)
     at Microsoft.SharePoint.Administration.SPMetabaseManager.ProvisionIisApplicationPool(String name, Int32 identityType, String userName, SecureString password, TimeSpan idleTimeout, TimeSpan periodicRestartTime)
     at Microsoft.Office.Server.Administration.SharedWebServiceInstance.CreateSharedWebServiceApplicationPool(SharedResourceProvider srp)
     at Microsoft.Office.Server.Administration.ApplicationServerJob.ProvisionLocalSharedServiceInstances(Boolean isAdministrationServiceJob)

I looked into the update history, and there were no changes in three months. This Sharpoint site collection has about six sites containing Silverlight 4.0 controls embedded in Web parts, which access a WCF service.
What is a likely cause of this?

A: I would start with the Timer Service (owstimer.exe).
I have heard of memory leaks with SharePoint Timer Jobs and also heard that it is a best practice to recycle the Timer Service on a scheduled interval.
The other possible problem is corruption with your IIS installation or Metabase.  I say that because the error is being thrown when Directory Services tries to read the Metabase.
You should be able to get more details from the ULS log files.  You may have to adjust the logging level for ULS.

A: Definitely try parsing ULS logs under %CommonProgramFiles%\Microsoft Shared\Web server extensions\12\LOGS.
The issue is apparently related to Application Pool provisioning process on your web server(s). Check the validity of application pool accounts and settings in IIS manager, review any changes to Group Policy Objects and Local Security Policy that could have taken place recently.
By the way, specifying your topology and configuration could be beneficial for the resolution of your issue.


text:
Q: Unable to automate Jmeter load testing in Bamboo

simple 14-Jan-2019 15:42:18 Build Global Digital - Application - App_Performance_Test - feature-Jmeter-Test-Feature - JMeter #3 (GDA-AP10-JOB1-3) started building on agent Elastic Agent on i-0375978d6d2732720
simple 14-Jan-2019 15:42:18 Elastic agent on instance i-0375978d6d2732720
simple 14-Jan-2019 15:42:18 Build working directory is /media/ephemeral0/build-dir/GDA-AP10-JOB1
simple 14-Jan-2019 15:42:18 Executing build Global Digital - Application - App_Performance_Test - feature-Jmeter-Test-Feature - JMeter #3 (GDA-AP10-JOB1-3)
simple 14-Jan-2019 15:42:18 Starting task 'Checkout jmeter scripts' of type 'com.atlassian.bamboo.plugins.vcs:task.vcs.checkout'
simple 14-Jan-2019 15:42:18 Checking out into /media/ephemeral0/build-dir/GDA-AP10-JOB1
simple 14-Jan-2019 15:42:18 Updating source code to revision: 06bbe6dbc1ab56007bf4b44e270b72d477e7fee6
simple 14-Jan-2019 15:42:18 Fetching 'refs/heads/feature/Jmeter-Test-Feature' from 'ssh://git@stash-QA.gd.com:7999/project/jmeter-scripts.git'. Will try to do a shallow fetch.
simple 14-Jan-2019 15:42:18 Warning: Permanently added '[127.0.0.1]:36663' (RSA) to the list of known hosts.
simple 14-Jan-2019 15:42:19 Checking out revision 06bbe6dbc1ab56007bf4b44e270b72d477e7fee6.
simple 14-Jan-2019 15:42:19 Already on 'feature/Jmeter-Test-Feature'
simple 14-Jan-2019 15:42:19 Updated source code to revision: 06bbe6dbc1ab56007bf4b44e270b72d477e7fee6
simple 14-Jan-2019 15:42:19 Finished task 'Checkout jmeter scripts' with result: Success
simple 14-Jan-2019 15:42:19 Running pre-build action: VCS Version Collector
simple 14-Jan-2019 15:42:19 Running pre-build action: Sauce OnDemand Build Configurator
simple 14-Jan-2019 15:42:19 Running pre-build action: Hung Build Killer PreBuildAction
simple 14-Jan-2019 15:42:19 Skipping execution of task 'Run jmeter scripts' as it is disabled
command 14-Jan-2019 15:42:19 Substituting variable: ${bamboo.capability.system.builder.command.JMeter 3} with /opt/apache-jmeter-3/bin/jmeter
command 14-Jan-2019 15:42:19 Substituting variable: ${bamboo.build.working.directory} with /media/ephemeral0/build-dir/GDA-AP10-JOB1
simple 14-Jan-2019 15:42:19 Starting task 'Test script' of type 'com.atlassian.bamboo.plugins.scripttask:task.builder.script'
command 14-Jan-2019 15:42:19 Beginning to execute external process for build 'Global - Application - App_Performance_Test - feature-Jmeter-Test-Feature - JMeter #3 (GDA-AP10-JOB1-3)'\n ... running command line: \n/bin/sh /home/bamboo/bamboo-agent-home/temp/GDA-AP10-JOB1-3-ScriptBuildTask-5020464262256623767.sh\n ... in: /media/ephemeral0/build-dir/GDA-AP10-JOB1\n ... using extra environment variables: \nbamboo_planRepository_1_branch=feature/Jmeter-Test-Feature\nbamboo_duration=5\nbamboo_repository_247496707_revision_number=06bbe6dbc1ab56007bf4b44e270b72d477e7fee6\nbamboo_planRepository_1_branchDisplayName=feature/Jmeter-Test-Feature\nbamboo_repository_revision_number=06bbe6dbc1ab56007bf4b44e270b72d477e7fee6\nbamboo_repository_247496707_name=Global - jmeter-scripts\nbamboo_repository_247496707_git_repositoryUrl=ssh://git@stash-QA.gd.com:7999/project/jmeter-scripts.git\nbamboo_buildKey=GDA-AP10-JOB1\nbamboo_capability_remote=true\nbamboo_capability_system_builder_command_Python_2_7=/usr/bin/python\nbamboo_shortJobName=JMeter\nbamboo_buildResultsUrl=https://bamboo-staging.qa.com/browse/GDA-AP10-JOB1-3\nbamboo_repository_247496707_git_branch=feature/Jmeter-Test-Feature\nbamboo_planRepository_repositoryUrl=ssh://git@stash-QA.gd.com:7999/project/jmeter-scripts.git\nbamboo_agentId=247824395\nbamboo_location=publish\nbamboo_ramp_time=1\nbamboo_planRepository_revision=06bbe6dbc1ab56007bf4b44e270b72d477e7fee6\nbamboo_planRepository_previousRevision=06bbe6dbc1ab56007bf4b44e270b72d477e7fee6\nbamboo_repository_branch_name=feature/Jmeter-Test-Feature\nbamboo_repository_247496707_branch_name=feature/Jmeter-Test-Feature\nbamboo_ci_password=********\nbamboo_capability_system_builder_command_Python_3=/usr/bin/python3\nbamboo_password=********\nbamboo_capability_ci=true\nbamboo_capability_system_builder_command_foodcritic=/opt/chefdk/bin/foodcritic\nbamboo_dependenciesDisabled=false\nbamboo_locale=en_us\nbamboo_threads=1\nbamboo_planRepository_branch=feature/Jmeter-Test-Feature\nbamboo_planRepository_1_type=bbserver\nbamboo_planRepository_branchName=feature/Jmeter-Test-Feature\nbamboo_environment=lt-000\nbamboo_gdminorversion=6313\nbamboo_capability_release=true\nbamboo_planRepository_1_username=\nbamboo_planRepository_type=bbserver\nbamboo_ManualBuildTriggerReason_userName=bv49406\nbamboo_capability_system_builder_command_rubocop=/opt/chefdk/bin/rubocop\nbamboo_capability_system_builder_node_Node_js=/opt/node/bin/node\nbamboo_capability_system_builder_ant_Ant=/opt/ant\nbamboo_capability_system_builder_mvn3_Maven_3=/opt/maven/current\nbamboo_planKey=GDA-AP10\nbamboo_planRepository_username=\nbamboo_planRepository_1_branchName=feature/Jmeter-Test-Feature\nbamboo_capability_system_agent_environment_ec2_instance_type=c3.xlarge\nbamboo_resultsUrl=https://bamboo-staging.qa.com/browse/GDA-AP10-JOB1-3\nbamboo_capability_system_agent_environment_ebs_optimised=false\nbamboo_build_working_directory=/media/ephemeral0/build-dir/GDA-AP10-JOB1\nbamboo_planRepository_1_name=Global - jmeter-scripts\nbamboo_shortPlanName=feature-Jmeter-Test-Feature\nbamboo_capability_system_builder_command_ansible=/usr/local/bin/ansible\nbamboo_hybris_version=6.3.0.8\nbamboo_capability_system_builder_command_packer=/usr/local/bin/packer\nbamboo_planRepository_name=Global - jmeter-scripts\nbamboo_gdmajorversion=1\nbamboo_capability_system_builder_command_terraform=/usr/local/bin/terraform\nbamboo_buildNumber=3\nbamboo_username=admin\nbamboo_planName=Global - Application - App_Performance_Test - feature-Jmeter-Test-Feature\nbamboo_capability_system_builder_command_git=/usr/bin/git\nbamboo_shortPlanKey=AP10\nbamboo_shortJobKey=JOB1\nbamboo_capability_system_builder_node_npm=/opt/node-7/bin/npm\nbamboo_capability_system_builder_command_JMeter_3=/opt/apache-jmeter-3/bin/jmeter\nbamboo_capability_system_builder_command_berkshelf=/opt/chefdk/bin/berks\nbamboo_buildTimeStamp=2019-01-14T15:42:18.663Z\nbamboo_repository_previous_revision_number=06bbe6dbc1ab56007bf4b44e270b72d477e7fee6\nbamboo_repository_git_branch=feature/Jmeter-Test-Feature\nbamboo_buildResultKey=GDA-AP10-JOB1-3\nbamboo_buildPlanName=Global - Application - App_Performance_Test - feature-Jmeter-Test-Feature - JMeter\nbamboo_capability_system_agent_environment_iam_instance_profile=gd-mantl-agent\nbamboo_planRepository_1_revision=06bbe6dbc1ab56007bf4b44e270b72d477e7fee6\nbamboo_repository_name=Global - jmeter-scripts\nbamboo_domain=www-bose-com\nbamboo_repository_247496707_previous_revision_number=06bbe6dbc1ab56007bf4b44e270b72d477e7fee6\nbamboo_ci_user=gc8281256\nbamboo_buildFailed=false\nbamboo_capability_system_docker_executable=/usr/bin/docker\nbamboo_agentWorkingDirectory=/media/ephemeral0/build-dir\nbamboo_gdtempversion=17216\nbamboo_capability_system_git_executable=/usr/bin/git\nbamboo_repository_git_username=\nbamboo_planRepository_1_previousRevision=06bbe6dbc1ab56007bf4b44e270b72d477e7fee6\nbamboo_planRepository_branchDisplayName=feature/Jmeter-Test-Feature\nbamboo_capability_system_builder_mvn3_Maven_3_x=/opt/maven/current\nbamboo_capability_system_builder_command_awscli=/usr/local/bin/aws\nbamboo_plan_storageTag=plan-247365637\nbamboo_repository_git_repositoryUrl=ssh://git@stash-QA.gd.com:7999/project/jmeter-scripts.git\nbamboo_repository_247496707_git_username=\nbamboo_capability_system_builder_command_knife=/opt/chefdk/bin/knife\nbamboo_working_directory=/media/ephemeral0/build-dir/GDA-AP10-JOB1\nbamboo_planRepository_1_repositoryUrl=ssh://git@stash-QA.gd.com:7999/project/jmeter-scripts.git\nbamboo_capability_system_jdk_JDK_1_8=/opt/jdk-8\nbamboo_capability_system_jdk_JDK_1_9=/opt/jdk-9\nbamboo_capability_system_builder_command_chrome=/usr/bin/google-chrome\n
simple 14-Jan-2019 16:02:25  _   _  ____  _  _
simple 14-Jan-2019 16:02:25 ( )_( )(  _ \( )/ )
simple 14-Jan-2019 16:02:25  ) _ (  ) _ < )  (
simple 14-Jan-2019 16:02:25 (_) (_)(____/(_)\_)
simple 14-Jan-2019 16:02:25 This build has been killed by the HBK (Hung Build Killer). Either Bamboo has detected the build has hung or it has been manually stopped.
simple 14-Jan-2019 16:02:25 Attempting to generate stack trace and terminate spawned sub-processes of process id: 2282
simple 14-Jan-2019 16:02:25 Found related process: pid: 2659 ppid: 2282 pgid: 2174 %cpu: 0.0 %mem: 0.0 cmd: /bin/sh /home/bamboo/bamboo-agent-home/temp/GDA-AP10-JOB1-3-ScriptBuildTask-5020464262256623767.sh
simple 14-Jan-2019 16:02:25 Found related process: pid: 2660 ppid: 2659 pgid: 2174 %cpu: 0.0 %mem: 0.0 cmd: /bin/bash
simple 14-Jan-2019 16:02:25 getStackTraceAndKillRelatedProcesses for 2 processes
simple 14-Jan-2019 16:02:25 Executing kill -3 2660
simple 14-Jan-2019 16:02:25 Executing kill -3 2659
simple 14-Jan-2019 16:02:30 Killing: 2660
simple 14-Jan-2019 16:02:30 Executing kill 2660
simple 14-Jan-2019 16:02:30 Killing: 2659
simple 14-Jan-2019 16:02:30 Executing kill 2659
error 14-Jan-2019 16:02:30 Terminated
error 14-Jan-2019 16:02:30 /home/bamboo/bamboo-agent-home/temp/GDA-AP10-JOB1-3-ScriptBuildTask-5020464262256623767.sh: 2: cd: can't cd to /opt/apache-jmeter-3/bin/jmeter
simple 14-Jan-2019 16:02:30 Failing task since return code of [/bin/sh /home/bamboo/bamboo-agent-home/temp/GDA-AP10-JOB1-3-ScriptBuildTask-5020464262256623767.sh] was 2 while expected 0
simple 14-Jan-2019 16:02:30 Finished task 'Test script' with result: Failed
simple 14-Jan-2019 16:02:30 Running post build plugin 'Docker Container Cleanup'
simple 14-Jan-2019 16:02:30 Running post build plugin 'NCover Results Collector'
simple 14-Jan-2019 16:02:30 Running post build plugin 'Clover Results Collector'
simple 14-Jan-2019 16:02:30 Running post build plugin 'Sauce OnDemand Post Runner'
simple 14-Jan-2019 16:02:30 Running post build plugin 'npm Cache Cleanup'
simple 14-Jan-2019 16:02:30 Running post build plugin 'Artifact Copier'
simple 14-Jan-2019 16:02:30 Publishing an artifact: jmeter_jtl
error 14-Jan-2019 16:02:30 Unable to publish artifact [jmeter_jtl]: the source directory /media/ephemeral0/build-dir/GDA-AP10-JOB1/output does not exist.
simple 14-Jan-2019 16:02:30 The artifact hasn't been successfully published after 456.8 μs
simple 14-Jan-2019 16:02:30 Finalising the build...
simple 14-Jan-2019 16:02:30 Stopping timer.
simple 14-Jan-2019 16:02:30 Build GDA-AP10-JOB1-3 completed.
simple 14-Jan-2019 16:02:30 Running on server: post build plugin 'NCover Results Collector'
simple 14-Jan-2019 16:02:30 Running on server: post build plugin 'Build Hanging Detection Configuration'
simple 14-Jan-2019 16:02:30 Running on server: post build plugin 'Clover Delta Calculator'
simple 14-Jan-2019 16:02:30 Running on server: post build plugin 'Maven Dependencies Postprocessor'
simple 14-Jan-2019 16:02:30 All post build plugins have finished
simple 14-Jan-2019 16:02:30 Generating build results summary...
simple 14-Jan-2019 16:02:30 Saving build results to disk...
simple 14-Jan-2019 16:02:30 Logging substituted variables...
simple 14-Jan-2019 16:02:31 Indexing build results...
simple 14-Jan-2019 16:02:31 Finished building GDA-AP10-JOB1-3.
simple 14-Jan-2019 16:02:35  _   _  ____  _  _
simple 14-Jan-2019 16:02:35 ( )_( )(  _ \( )/ )
simple 14-Jan-2019 16:02:35  ) _ (  ) _ < )  (
simple 14-Jan-2019 16:02:35 (_) (_)(____/(_)\_)
simple 14-Jan-2019 16:02:35 This build has been killed by the HBK (Hung Build Killer). Either Bamboo has detected the build has hung or it has been manually stopped.
simple 14-Jan-2019 16:02:35 Has finished generating stack trace and terminating spawned sub-processes of process id: 2282

I am planning to automate performance testing through Bamboo. Currently, I am running performance tests using jmeter 3.1 installed on a Windows machine (AWS-EC2 instance).
I am following the below approach to automate my tests:

*

*Create a repository in stash, upload the jmx file

*Create a bamboo plan, with  a stage(jmeter)->task 1(Source Code Checkout configuration- configured the above repository) and task 2 (Script configuration).

*In the second task, I choose /bin/sh or cmd.exe then I have written the code in the script body section:
/bin/bash
cd ${bamboo.capability.system.builder.command.JMeter 3} -n -t \
jmeterscript.jmx -l ${bamboo.build.working.directory}/example.jtl
#runtime the value will be
#${bamboo.capability.system.builder.command.JMeter 3}
# (which is interpolated to `/opt/apache-jmeter-3/bin/jmeter`)

When I run the above plan, it runs for more than 30 mins and fails.
Here's the error I receive (logs are in-line, above):
can't cd to /opt/apache-jmeter-3/bin/jmeter
   Unable to publish artifact [jmeter_jtl]: the source directory
   /media/ephemeral0/build-dir/GDA-AP10-JOB1/output does not exist.

A: cd ${bamboo.capability.system.builder.command.JMeter 3} -n -t \jmeterscript.jmx -l ${bamboo.build.working.directory}/example.jtl
By this command you are trying to change dir. But there is no such dir actually.
You have to run JMeter instead:
${bamboo.capability.system.builder.command.JMeter 3} -n -t \jmeterscript.jmx -l ${bamboo.build.working.directory}/example.jtl


text:
Q: Why wont my options list get populated when using a for loop When trying to dynamically create a select box with values using php my data will not populate. All of the research I've done shows I've done this right. Can anyone point me to the right direction please.
<select name="month">
<?php
    $months = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

    for ($x=0; $x<=11; $x++) {
        echo '<option value="' . $x+1 . '">' . $months[$x] . '</option>';
    }
?>
</select>

A: you should add parentheses around the $x+1
like so:
<select name="month">
<?php
    $months = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

    for ($x=0; $x<=11; $x++) {

        echo '<option value="' . ($x+1) . '">' . $months[$x] . '</option>';
    }
?>
</select>


text:
Q: Javascript - revealing object and variable scope http://jsfiddle.net/ZLH7J/1/
What the jsFiddle and code below shows are two examples that essentially do the same thing. When trying to call first(); or this.first(); in either example, an undefined error is thrown. I can call the functions later through the instance, but not when trying to instantiate the object using init(){...}() like a constructor. I put init() at the bottom thinking it was an order of operations thing, but that is not the case. This does not work the way I thought it would work.
I am curious to understand how this is supposed to be done, and why this cannot be done.
//create and return an obj
var fishSticks = function(){
    return {
        first: function(){
            document.getElementById('output').innerHTML="Success";
        },
        init: function(){
            try{
                first(); //err
                this.first(); // also err
             }catch(e){
                document.getElementById('output').innerHTML=e.toString();
            }
        }()
    }
}

//do function stuff and then return 'this'
var fishFillet = function(){
    var first = function(){
            document.getElementById('output2').innerHTML="Success";
    }
    var init = function(){
            try{
                first(); //err
                this.first(); // also err
             }catch(e){
                 document.getElementById('output2').innerHTML=e.toString();
            }
    }()
return this;
}

 var test = new fishSticks();
 var test2 = new fishFillet();

A: In your second example, if you comment out the call in "init" to this.first() then you get the "Success" message.
The first version doesn't work because JavaScript simply does not allow for references to be made within an under-construction object to the object itself.  There's just no way to do it.
The second one works (well the simple reference to "first" works) because "first" is declared as a local variable. Local variables are not properties of any object, and in particular they're not properties of the object allocated when the function is called with new.  That's why this.first() doesn't work.
In the second one, you could make this.first() work by declaring things differently:
var fishFillet = function(){
    this.first = function(){
            document.getElementById('output2').innerHTML="Success";
    }
    var init = function(){
            try{
                this.first(); //will work
             }catch(e){
                 document.getElementById('output2').innerHTML=e.toString();
            }
    }()
    return this;
}

Also, for what it's worth, the weird anti-pattern of
var something = function() { ... }

is not as useful as
function something() { ... }

There's no reason to use the var declaration instead of the function declaration.

A: You need to understand two things:
1) JavaScript does not automatically insert this like Java does, so the first() call will only look through the lexical scope for a definition of first, it will nok look at the this object. Therefore the call to first() should work but this will be bound to something else than what you might expect inside first.
2) Local variables in a constructor do not become members of the constructed object.

A: How about...
var fishFillet = function () {
    var first = function () {
        document.write( 'Success' );
    };

    var init = function () {
        first();
    };

    init();

    return {
        first: first
    };
};

And then:
var ff = fishFillet(); // calls init() which calls first()
ff.first(); // call first() manually

Live demo: http://jsfiddle.net/uaCnv/
So, first you define all your functions, next you manually invoke init, and last you return an object containing those functions which should be available through the resulting object (as methods).

A: Since you are using both as a constructor, format them as such:
function fishFillet(){
    this.first = function(){
        document.getElementById('output2').innerHTML="Success";
    }
    this.init = function(){
        try{
            this.first();
        }catch(e){
            document.getElementById('output2').innerHTML=e.toString();
        }
    }
}
var food = new fishFillet();
food.init();

The reason it wasn't working for you is b/c "first" is created as a local varaible, and is deleted after execultion. Init isn't being called until after the execution of the constructor has finished


text:
Q: Post processing of uploaded file When a file with the .xml extension has been uploaded on my blog (via the Add Media uploader) I would like to automatically replace some attributes.
For example, if I upload a file with this content:
<content creator="foo"></content>

I would like that Wordpress modifies it automatically in:
<content creator="bar"></content>

What hook should I use and how?

A: You can do this using the wp_handle_upload hook:
http://adambrown.info/p/wp_hooks/hook/wp_handle_upload?version=3.4&file=wp-admin/includes/file.php
Create a function and add it to this hook so it runs last, it will be passed an array. The array contains the location of the newly uploaded file:
add_filter('wp_handle_upload','wpse_66775_handle_upload',1000,1);
function wpse_66775_handle_upload($args){
    $filename = $args['file'];
    $type = $args['type'];
    // test if it's an XML file and do some work on it
    if(the file is an xml file){
        super_magic_xml_file_modifier($filename);
    }
    return $args;
}

function super_magic_xml_file_modifier($filename){
    // General PHP/XML stuff that doesn't belong on WPSE
}

Modifying the XML file etc, is another task that is not within the scope of this site.


text:
Q: What do drivers have to do with modules? I need to research and find out "which drivers are loaded on my system" using /proc.
In /proc there is a dir called "driver" so I thought that was it, but reading about it online, I saw I should also take look at my modules file.
Why? what do these have to do with each other?

A: Linux kernel modules are extensions of the kernel that implement functionality including that of drivers. /proc contains information about your devices and modules. There's your connection.


text:
Q: Skipped 172 frames! The application may be doing too much work on its main thread In my Java project, only user login and register, there are activities with only buttons in it. When I run the emulator for the second time, I get such a warning. When I want to go to the register page, it sends to the page with the button. Or the user login page does not open when it first opens. The alert looks like this: Skipped 172 frames! The application may be doing too much work on its main thread. I'm new to Android programming, I would appreciate it if you could help.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.geziproject">
   <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Geziproject">
        <activity android:name=".bos"/>
        <activity android:name=".kayitol" />
        <activity android:name=".kullanicigiris">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

kayitol.java
public class kayitol extends AppCompatActivity {
    private EditText txtAd, txtEmail, txtŞifre;
    private Button btnkayit;
    FirebaseAuth mFirebaseAuth;
    //DatabaseReference yol;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kayitol);
        mFirebaseAuth = FirebaseAuth.getInstance();
        txtAd = findViewById(R.id.txtad);
        txtEmail = findViewById(R.id.txtEmail);
        txtŞifre = findViewById(R.id.txtŞifre);
        btnkayit = findViewById(R.id.kayit);

        btnkayit.setOnClickListener(v -> {
            String email = txtEmail.getText().toString();
            String pwd = txtŞifre.getText().toString();
            if (email.isEmpty()) {
                txtEmail.setError("Lütfen email giriniz");
                txtEmail.requestFocus();
            } else if (pwd.isEmpty()) {
                txtŞifre.setError("Lütfen şifre giriniz");
                txtŞifre.requestFocus();
            } else if (email.isEmpty() && pwd.isEmpty()) {
                Toast.makeText(kayitol.this, "Bu alanlar boş bırakılamaz", Toast.LENGTH_LONG).show();
            } else if (!(email.isEmpty() && pwd.isEmpty())) {
                mFirebaseAuth.createUserWithEmailAndPassword(email, pwd).addOnCompleteListener(kayitol.this, task -> {
                    if (!task.isSuccessful()) {
                        Toast.makeText(kayitol.this, "Kayıt başarısız,tekrar deneyiniz", Toast.LENGTH_LONG).show();
                    } else {
                        Intent intent = new Intent(kayitol.this, bos.class);
                        startActivity(intent);
                    }
                });
            } else {
                Toast.makeText(kayitol.this, "Hata oluştu", Toast.LENGTH_LONG).show();
            }
        });
    }
}

kullanicigiris.java
public class kullanicigiris extends AppCompatActivity {
    Button btngiris;
    Button btnkayit;
    FirebaseAuth mFirebaseAuth;
    private EditText txtad;
    private EditText txtemail;
    private EditText txtsifre;
    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kullanicigiris);
        mFirebaseAuth = FirebaseAuth.getInstance();
        Button btngiris = findViewById(R.id.giris);
        Button btnkayit = findViewById(R.id.kayit);

        txtad = findViewById(R.id.txtad);
        txtemail = findViewById(R.id.txtemaili);
        txtsifre = findViewById(R.id.txtŞifre);

        mAuthListener = firebaseAuth -> {
            FirebaseUser mFirebaseUser = mFirebaseAuth.getCurrentUser();
            if (mFirebaseUser != null) {
                Toast.makeText(kullanicigiris.this, "giriş yaptın", Toast.LENGTH_LONG).show();
                Intent i = new Intent(kullanicigiris.this, bos.class);
                startActivity(i);
            } else {
                Toast.makeText(kullanicigiris.this, "lütfen giriş yapın", Toast.LENGTH_LONG).show();
            }
        };

        btngiris.setOnClickListener(v -> {
            String email = txtemail.getText().toString();
            String pwd = txtsifre.getText().toString();
            if (email.isEmpty()) {
                txtemail.setError("Lütfen email giriniz");
                txtemail.requestFocus();
            } else if (pwd.isEmpty()) {
                txtsifre.setError("Lütfen şifre giriniz");
                txtsifre.requestFocus();
            } else if (email.isEmpty() && pwd.isEmpty()) {
                Toast.makeText(kullanicigiris.this, "Bu alanlar boş bırakılamaz", Toast.LENGTH_LONG).show();
            } else if (!(email.isEmpty() && pwd.isEmpty())) {
                mFirebaseAuth.signInWithEmailAndPassword(email, pwd).addOnCompleteListener(kullanicigiris.this, task -> {
                    if (!task.isSuccessful()) {
                        Toast.makeText(kullanicigiris.this, "Giriş  başarısız ,tekrar deneyiniz", Toast.LENGTH_LONG).show();
                    } else {
                        txtad.setText("");
                        txtemail.setText("");
                        txtsifre.setText("");
                        startActivity(new Intent(kullanicigiris.this, bos.class));
                    }
                });
            } else {
                Toast.makeText(kullanicigiris.this, "Hata oluştu", Toast.LENGTH_LONG).show();
            }
        });

        btnkayit.setOnClickListener(v -> {
            Intent i = new Intent(kullanicigiris.this, kayitol.class);
            startActivity(i);
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        mFirebaseAuth.addAuthStateListener(mAuthListener);

    }
}

bos.java
public class bos extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bos);
    }
}

run:
12/07 16:40:12: Launching 'app' on Pixel.
Install successfully finished in 2 s 552 ms.
$ adb shell am start -n "com.example.geziproject/com.example.geziproject.kullanicigiris" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 7342 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/ple.geziprojec: Not late-enabling -Xcheck:jni (already on)
I/ple.geziprojec: Unquickening 12 vdex files!
W/ple.geziprojec: Unexpected CPU variant for X86 using defaults: x86
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
W/ple.geziprojec: Verification of boolean com.google.android.gms.common.GoogleApiAvailabilityLight.isPlayServicesPossiblyUpdating(android.content.Context, int) took 251.962ms (19.84 bytecodes/s) (776B approximate peak alloc)
W/ple.geziprojec: Verification of com.google.android.gms.tasks.Task com.google.android.gms.common.GoogleApiAvailability.makeGooglePlayServicesAvailable(android.app.Activity) took 120.192ms (316.16 bytecodes/s) (1400B approximate peak alloc)
I/FirebaseInitProvider: FirebaseApp initialization successful
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/ple.geziprojec: Verification of void com.google.android.gms.common.api.internal.GoogleApiManager$zaa.<init>(com.google.android.gms.common.api.internal.GoogleApiManager, com.google.android.gms.common.api.GoogleApi) took 115.333ms (945.09 bytecodes/s) (3688B approximate peak alloc)
W/ple.geziprojec: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/ple.geziprojec: Verification of void com.google.android.gms.common.api.internal.GoogleApiManager$zaa.onConnected(android.os.Bundle) took 141.826ms (246.78 bytecodes/s) (1264B approximate peak alloc)
W/ple.geziprojec: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10153; state: ENABLED
D/HostConnection: HostConnection::get() New Host Connection established 0xeaedfd50, tid 7393
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xeaeded90: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xeaeded90: ver 2 0 (tinfo 0xeb222df0) (first time)
I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to fallback implementation
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xeaedfb20, tid 7393
D/goldfish-address-space: allocate: Ask for block of size 0x100
    allocate: ioctl allocate returned offset 0x3fcf6d000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2
I/OpenGLRenderer: Davey! duration=976ms; Flags=1, IntendedVsync=1293927629619, Vsync=1293977629617, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=1293986896900, AnimationStart=1293986963100, PerformTraversalsStart=1293987049900, DrawStart=1294410491800, SyncQueued=1294418169100, SyncStart=1294436241500, IssueDrawCommandsStart=1294436512100, SwapBuffers=1294778679200, FrameCompleted=1294922281100, DequeueBufferDuration=187900, QueueBufferDuration=733800, GpuCompleted=0,
I/Choreographer: Skipped 61 frames!  The application may be doing too much work on its main thread.

A: In general, frames being skipped at an amount under 200 or so tends to simply be lag on your emulator. This is expected; emulators are quite slow. In your current state, this is probably a problem you can safely ignore.
You could close other unnecessary programs on your computer to see if it gets better. You probably will skip a few frames no matter what, but it's generally fine.
This problem is only a serious issue if the number of skipped frames becomes large enough that it seriously affects user experiences on actual hardware. That would be in the range of 300+ frames
For detailed information, look at Android UI : Fixing skipped frames


text:
Q: Is it possible to remove shadow on a specific image via css It is possible to remove a shadow on a specific image that appears on many pages many time on a site.
This is the image that should not have a shadow.
http://www.101calendartemplates.com/wp-content/uploads/2015/12/print.png
The image appears on this site on pages such as this one:
http://www.101calendartemplates.com/august-calendar-2/
This is the code that was used to add a shadow to all other images on the site:

.alignnone {
    border: #b9b9b9 solid 1px;

  -webkit-box-shadow: 3px 3px 5px 6px #ccc;  /* Safari 3-4, iOS 4.0.2 - 4.2, Android 2.3+ */
  -moz-box-shadow:    3px 3px 5px 6px #ccc;  /* Firefox 3.5 - 3.6 */
  box-shadow:         3px 3px 5px 6px #ccc;  /* Opera 10.5, IE 9, Firefox 4+, Chrome 6+, iOS 5 */
}

A: You can target the img by src attribute:
img[src$="print.png"] {
  -webkit-box-shadow: none;
  -moz-box-shadow:    none;
  box-shadow:         none;
}

The "$=" matches on any value that ends in the specified value.


text:
Q: Parsing equations in Python using regex I have the following expressions that I need to be able to parse into separate tokens:
"a=b+c"     ->  a b + c
"a=5+c"     ->  a 5 + c
"a=c*50"    ->  a c * 50
"a=50%50"   ->  a 50 % 50
"a=c-x[20]" ->  a c - x[20]
"a=x[3]+50" ->  a x[3] + 50
"a=b--c"    ->  a b - -c

I used this regex help but I can only apply the regex on one example, not all of them. For example, the following code would work only on "a=b+c","a=c-50" but not if I swap them into "a=c-50, "a=b+c":
#!/usr/bin/python
# URL that generated this code:
# http://txt2re.com/index-python.php3?s=%22a=b%2bc%22,%20%22a=c-50%22&-32&-34&25&-35&-33&36&27&5

import re

txt='"a=b+c", "a=c-50"'

re1='.*?'   # Non-greedy match on filler
re2='(a)'   # Any Single Character 1
re3='.*?'   # Non-greedy match on filler
re4='(b)'   # Any Single Character 2
re5='(.)'   # Any Single Character 3
re6='(c)'   # Any Single Character 4
re7='.*?'   # Non-greedy match on filler
re8='(a)'   # Any Single Character 5
re9='.*?'   # Non-greedy match on filler
re10='.'    # Uninteresting: c
re11='.*?'  # Non-greedy match on filler
re12='(.)'  # Any Single Character 6
re13='(.)'  # Any Single Character 7
re14='(\\d+)'   # Integer Number 1

rg = re.compile(re1+re2+re3+re4+re5+re6+re7+re8+re9+re10+re11+re12+re13+re14,re.IGNORECASE|re.DOTALL)
m = rg.search(txt)
if m:
   c1=m.group(1)
   c2=m.group(2)
   c3=m.group(3)
   c4=m.group(4)
   c5=m.group(5)
   c6=m.group(6)
   c7=m.group(7)
   int1=m.group(8)
   print("("+c1+")"+"("+c2+")"+"("+c3+")"+"("+c4+")"+"("+c5+")"+"("+c6+")"+"("+c7+")"+"("+int1+")"+"\n")

A: Try using re.split()
It will split your equation on the basis of operators.
For example:
text = 'a=x[3]+50'
pattern = r'([\=\+\-\%\*])'
result = re.split(pattern, text)

Output:
['a', '=', 'x[3]', '+', '50']


text:
Q: How to specify multiple columns with gather() function to tidy data I want to tidy my data with the gather function but how do I specify multiple columns at once?
Say this is my data:
    Country Country.Code Year X0tot4 X5tot9 X10tot14 X15tot19 X20tot24
1  Viet Nam          704 1955   4606   2924     2389     2340     2502
2  Viet Nam          704 1960   5842   4410     2860     2356     2318
3  Viet Nam          704 1965   6571   5646     4328     2823     2335
4  Viet Nam          704 1970   7065   6391     5548     4271     2797
5  Viet Nam          704 1975   7658   6862     6237     5437     4208
6  Viet Nam          704 1980   7991   7473     6754     6113     5266
7  Viet Nam          704 1985   8630   7855     7375     6657     6027
8  Viet Nam          704 1990   9212   8513     7770     7277     6571
9  Viet Nam          704 1995   9200   9099     8447     7702     7140
10 Viet Nam          704 2000   7245   9119     9053     8402     7610
11 Viet Nam          704 2005   6760   7140     8997     8951     8257
12 Viet Nam          704 2010   7277   6657     7015     8891     8775
13 Viet Nam          704 2015   7753   7233     6623     6982     8817

Now I want to create one new column Age.groups with the variables from X0tot4 to X20tot24.
Something like df %>% gather(key = "Age.group", value = c(4:8)). Console says this is not the right column specification. But what is?

A: Nice answer by Psidom. Alternatively, you can exclude columns using "-".
df %>% gather(key = "Age.group", value = value, -Country, -Country.Code, -Year)

A: In the gather function, value specifies the name of value column in the result; To specify which columns to gather, you can use start_column:end_column syntax, this will gather all columns from the start_column to end_column; In your case, it would be X0tot4:X20tot24:
df %>% gather(key = 'Age.group', value = 'Value.name', X0tot4:X20tot24)
#                        V                     V
#                              V               V
#                                    V         V
#      Country Country.Code Year Age.group Value.name
#1   Viet Nam           704 1955    X0tot4       4606
#2   Viet Nam           704 1960    X0tot4       5842
#3   Viet Nam           704 1965    X0tot4       6571
#4   Viet Nam           704 1970    X0tot4       7065
#5   Viet Nam           704 1975    X0tot4       7658
#6   Viet Nam           704 1980    X0tot4       7991
#7   Viet Nam           704 1985    X0tot4       8630

A: We can also specify the columns to gather by matching a string. The following will all work.
library(tidyverse)

# Match by the beginning of a string with a pattern
df %>% gather(Age.group, Value.name, starts_with("X"))

# Match by if a string containing a pattern
df %>% gather(Age.group, Value.name, contains("X"))

# Match by a regular expression pattern
df %>% gather(Age.group, Value.name, matches("X"))