text:
Q: Add a badge to a C# winforms control When writing in CSS I can add a class of "badge" and get what I want. A small number near a button or tab with some styling to it, to show that this control has pending info that needs review.
There is even a post here of somebody trying to do what I want on iOS
I want to do this on WinForms on either a button or a tab. If an easier solution is available in WPF, then I might consider using that instead.
Here is an image showing an example of what I want to achieve:

A: And here is a way with a static Adorner class, very quick and rather dirty..
It can add a Label to many controls and it includes a click action, dynamic text and has code to remove the Label.

Adding a Badge to a Button takes one line:
    public Form1()
    {
        InitializeComponent();
        // adorn one Button with a Badge Label:
        Adorner.AddBadgeTo(button1, "123");
        // if you want to you can add a click action:
        Adorner.SetClickAction(button1, dobidoo);
    }

    // a test action
    void dobidoo(Control ctl)
    {
        Console.WriteLine("You have clicked on :" + ctl.Text);
    }

Here is the Adorner class:
static class Adorner
{
    private static List<Control> controls = new List<Control>();

    static public bool AddBadgeTo(Control ctl, string Text)
    {
        if (controls.Contains(ctl)) return false;

        Badge badge = new Badge();
        badge.AutoSize = true;
        badge.Text = Text;
        badge.BackColor = Color.Transparent;
        controls.Add(ctl);
        ctl.Controls.Add(badge);
        SetPosition(badge, ctl);

        return true;
    }

    static public bool RemoveBadgeFrom(Control ctl)
    {
        Badge badge = GetBadge(ctl);
        if (badge != null)
        {
            ctl.Controls.Remove(badge);
            controls.Remove(ctl);
            return true;
        }
        else return false;
    }

    static public void SetBadgeText(Control ctl, string newText)
    {
        Badge badge = GetBadge(ctl);
        if (badge != null)
        {
                badge.Text = newText;
                SetPosition(badge, ctl);
        }
    }

    static public string GetBadgeText(Control ctl)
    {
        Badge badge = GetBadge(ctl);
        if (badge != null) return badge.Text;
        return "";
    }

    static private void SetPosition(Badge badge, Control ctl)
    {
       badge.Location = new Point(ctl.Width  - badge.Width - 5,
                                  ctl.Height - badge.Height - 5);
    }

    static public void SetClickAction(Control ctl, Action<Control> action)
    {
        Badge badge = GetBadge(ctl);
        if (badge != null)  badge.ClickEvent = action;
    }

    static Badge GetBadge(Control ctl)
    {
        for (int c = 0; c < ctl.Controls.Count; c++)
            if (ctl.Controls[c] is Badge) return ctl.Controls[c] as Badge;
        return null;
    }

    class Badge : Label
    {
        Color BackColor = Color.SkyBlue;
        Color ForeColor = Color.White;
        Font font = new Font("Sans Serif", 8f);

        public Action<Control> ClickEvent;

        public Badge()   {}

        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.FillEllipse(new SolidBrush(BackColor), this.ClientRectangle);
            e.Graphics.DrawString(Text, font, new SolidBrush(ForeColor), 3, 1);
        }

        protected override void OnClick(EventArgs e)
        {
            ClickEvent(this);
        }

    }
}

Note that while you can add it to most controls, not all work as well as a Button. A TabControl is rather hard to adorn as its Tabs really are not Controls but just painted areas, so just like adding a 'close X' to it you would have to user draw the badges of all TabPages..

A: Really the easiest and best way to achieve this is to create a new customized UserControl. Just add a button and insert a label over it on the right. Then add getters and setters for the controls inside you new UserControl. Here's an example of get/set to configure the button's notification:
public String ButtonNotification {
   get { return yourUserControlLabel.Text; }
   set {
         if (value == null || value == "") { yourUserControlLabel.Visibility = Hidden; }
         else { yourUserControlLabel.Visibility = Visible; }

         yourUserControlLabel.Text = value;
   }
}

Then you can customize the label's visibility and other properties with the getters/setters.

A: Here is a rough way to do it with a UserControl:
public partial class btnControl : UserControl
    {
        public Label label = new Label();
        public TextBox box = new TextBox();

        public btnControl()
        {
            this.label = new System.Windows.Forms.Label();
            this.box = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // label
            //
            this.label.AutoSize = true;
            this.label.ForeColor = System.Drawing.Color.White;
            this.label.Location = new System.Drawing.Point(4, 7);
            this.label.Name = "label";
            this.label.Size = new System.Drawing.Size(35, 13);
            this.label.TabIndex = 0;
            this.label.Text = "label";
            //
            // box
            //
            this.box.Location = new System.Drawing.Point(110, 3);
            this.box.Name = "box";
            this.box.Size = new System.Drawing.Size(31, 20);
            this.box.TabIndex = 1;
            this.box.Enabled = false;
            //
            // btnControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.Blue;
            this.Controls.Add(this.box);
            this.Controls.Add(this.label);
            this.Name = "btnControl";
            this.Size = new System.Drawing.Size(144, 26);
            this.ResumeLayout(false);
            this.PerformLayout();
        }
    }

Then put it in your form:
private void Form1_Load(object sender, EventArgs e)
        {
            btnControl Control = new btnControl();
            this.Controls.Add(Control);
            Control.label.Text = "Home";
            Control.box.Text = "42";
        }

Gives you:


text:
Q: Location of Google Drive Service Account Uploads I'm trying to upload a file to my Google Drive using a service account. When I deploy this code, I don't want the user to give authorization, I want them to upload to my account. I'm using this via PHP, and below is where I am so far.
This code is based on the examples given by the official documentation. When I run the php script, I get no errors, and I print_r the result variable. It has multiple URLs, when I go to it with the same account I created all this with, it says I need to request permission. When I look in my Google Developers console, it says it got the request and successfully ran it.
However, the file doesn't show anywhere in my Google Drive. I'm not really sure where to see these files on the service account, and how to get this file into my Google Drive. Below is my code.
Am I missing a permission somewhere, or am I supposed to somehow connect the service account to a normal account?
DEFINE("TESTFILE", 'testfile-small.txt');
    if (!file_exists(TESTFILE)) {
      $fh = fopen(TESTFILE, 'w');
      fseek($fh, 1024 * 1024);
      fwrite($fh, "!", 1);
      fclose($fh);
    }

// The setup

// Authentication Credentials
$client_id = '<my client id>'; //Client ID
$service_account_name = '<my client email'; //Email Address
$key_file_location = '<path to key>'; //key.p12

// Create the client
$client = new Google_Client();
$client->setApplicationName("IEEE_File_Upload");
$service = new Google_Service_Drive($client);

// Check for token
if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

// Get the key
$key = file_get_contents($key_file_location);

// Create the credentials
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/drive'),
    $key
);

// Set the credentials
$client->setAssertionCredentials($cred);

// Something with tokens
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

// Actual file stuff

  // Now lets try and send the metadata as well using multipart!
  $file = new Google_Service_Drive_DriveFile();
  $file->setTitle("Hello World!");
  $result = $service->files->insert(
      $file,
      array(
        'data' => file_get_contents(TESTFILE),
        'mimeType' => 'application/octet-stream',
        'uploadType' => 'multipart'
      )
  );

echo "
Results Of Call:
";
foreach ($result as $item) {
  echo $item['volumeInfo']['title'], "
 \n";

A: A service account is NOT YOU, a service account is its own sudo user entity type of thing.  A service account has its own drive account, its own Google calendar ..  when you preform an upload to a service account files are uploaded to its Google drive account not yours.
I suggest you use the same script and do a file list to see if the file was uploaded to the service accounts drive account.
There is no web interface for a service account so you cant log in and check it via the web it will all have to be done though your service account code.

A: "I'm trying to upload a file to my Google Drive using a service account."
As DaImTo said, a Service Account is not the same as your own Drive Account. The clue is in the word "Account", ie. it's a separate Account.
If you want to upload to your own account, you simply need to acquire a refresh token for that account, then use it to generate an access token each time you want to do an upload. The steps required are documented here How do I authorise an app (web or installed) without user intervention? (canonical ?)

redpajama_set_name: RedPajamaStackExchange


text:
Q: заполнение EditText по курсору через баттон интересует возможность заполнение EditText'а по расположению курсора через button.
То есть понятно что editText.append или .setText не подойдут. проще говоря надо что бы кастомные кнопки работали как обычная клавиатура андроидовская.

A:     EditText editText = findViewById(R.id.editText);
    ......
public void someButton(View view){
        int position = editText.getSelectionStart();
        String tmpString = editText.getText().toString();
        editText.setText(tmpString.substring(0, position));
        editText.append((Button)view).getText().toString());
        editText.append(tmpString.substring(position, tmpString.length());
}


text:
Q: Saving loop results in new dataframe columns in R I try to save results of a for loop in new columns but despite message() returns proper information, the data is not saved.
Background:
I have a data frame which in column 1 carries XPaths and in column 2 CSS Selectors of website elements and wish to save results of getComputedStyle (JS function evaluated with the help of RSelenium) for several styles like 'color', 'width' etc.
#Function filling one row with CSS's
get_computed_styles_loop <- function(some_web_element){
  for (style in 1:length(css_styles)) {
    js_function_styles <- paste("return window.getComputedStyle(",some_web_element,").getPropertyValue('",css_styles[style],"')",sep="")
    my_df_col <- columns_number + as.integer(style)
    my_df[selector, my_df_col] <- as.character(remDr$executeScript(js_function_styles)) # <- THIS ONE DOESN'T SAVE DATA TO THE DATAFRAME
    message(paste(js_function_styles, " ", my_df_col , " ", remDr$executeScript(js_function_styles)))
  }
}

#Filling the whole dataframe
for (selector in 1:nrow(my_df){
  js_function_xpath <- paste("document.getElementByXPath('",my_df[selector,1],"')",sep="");
  js_function_selector <- paste("document.querySelector('",my_df[selector,2],"')",sep="");
      tryCatch({
        get_computed_styles_loop(js_function_xpath)
      },
      error=function(cond){
        message(paste("XPath not working here: ", selector))
        tryCatch({
          get_computed_styles_loop(js_function_selector)
        },
        error=function(cond1){
          message(paste("Neither does CSS Selector: ", selector))
          return(NA)
        }
        )
      }
      )
}

Exemplary message() results. It seems ok but it's not shown in new columns:
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('color')   22   rgb(17, 17, 17)
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('background-color')   23   rgba(0, 0, 0, 0)
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('background')   24
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('margin')   25
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('padding')   26
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('width')   27   400px
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('height')   28   32px
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('font-weight')   29   400
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('font-family')   30   "Open Sans", sans-serif
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('font-size')   31   13px
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('border')   32
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('border-radius')   33
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('position')   34   static
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('text-align')   35   start
return window.getComputedStyle(document.getElementByXPath('html/body/div[1]/div[1]/table')).getPropertyValue('pointer')   36


text:
Q: Python 3.9+ Bluetooth on Windows 10 I've found already very similar questions for this problem but I can't figure it out.
I'm trying to connect a TimeBox evo with bluetooth to windows 10 using python with this code:
import socket

serverMACAddress = "11:75:58:ce:c7:52"
port = 4
print("Start")
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.connect((serverMACAddress,port))
while 1:
    text = input()
    if text == "quit":
        break
    s.send(bytes(text, 'UTF-8'))
s.close()

and I get this error:
OSError: [WinError 10064]
Altough getting the error, the device connects to the PC but I can't send and receive data using Python.

A: I had the same issue and it worked with a port value of 1...


text:
Q: How to deal with Pylint unused import message on submodule? I have this code:
import pyqtgraph as pg  # Short name cause pyqtgraph is looong
import pyqtgraph.exporters

# ... some code

pg.foo()
pg.exporters.ExportItem(blah)

Now pylint complains about the import pyqtgraph.exporters saying it is unused import. What is the Pythonic or elegant solution to fix this warning?
Note that without having import pyqtgraph.exporters, the methods in that submodule cannot be called.

A: You can do something like that:
import pyqtgraph as pg  # Short name cause pyqtgraph is looong
import pyqtgraph.exporters  # pylint: disable=unused-import

# ... some code

pg.foo()
pg.exporters.ExportItem(blah)

To prevent pylint warnings.

A: This should work
import pyqtgraph as pg  # Short name cause pyqtgraph is looong
from pyqtgraph import exporters

# ... some code

pg.foo()
exporters.ExportItem(blah)


text:
Q: Parallelogram inside of a quadrilateral.
Prove: If $ABCD$ is a quadrilateral with respective side midpoints $X$; $Y$; $Z$; $W$, as pictured, then $XYZW$ is a parallelogram.

I'm not sure where to start. All I know is $\overline{DZ}=\overline{XC}$, $\overline{DW}=\overline{WA}$. $\overline{AX}=\overline{XB}$ and $\overline{BY}=\overline{YC}$. From here I don't see where I can go.

A: Hint: Find parallel lines. In particular, show that $WZ$ is parallel to some other line. Show that $XY$ is also parallel to that other line.
Hint: What do you know about mid points of 2 line segments which a common end point?

A: Hint:

*

*For any $\triangle ABC$, let $M$ and $N$ be the midpoints of $AB$ and $AC$, then $\triangle ABC \sim \triangle AMN$, moreover, all the sides of the first triangle are parallel respectively to the sides of the second triangle (see also this).

Good luck ;-)


text:
Q: How to use json in register class and log in class I have a registration page and I want to upload data from my registration page to the server and after Login, I want to get the data which I submit at the time of registration.
This is my Register class :
public void requestData() {

 if (generalUtilities.isConnected()) {

                StringRequest requestRegister = new StringRequest(Request.Method.POST, GlobalData.SIGNUP,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {

                                try {
                                    final JSONObject jObject = new JSONObject(response);
                                    if (jObject.getString("status").equals("1")) {
                                        Log.e("baba", "baba22");
                                        JSONObject jsonObject = jObject.getJSONObject("data");

                                        edtMailId.setText(jsonObject.getString("Email"));

                                        String email = jsonObject.getString("Email");
                                        String password = jsonObject.getString("Password");

                                        Log.e("email", email);
                                        Log.e("password", password);

                                        b = new Bundle();
                                        b.putString("EMAIL", email);
                                        b.putString("PASSWORD", password);

                                    } else {

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {

                                Log.e("error", "" + volleyError.getMessage());
                            }
                        }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("FirstName", edtFirstName.getText().toString().trim());
                        params.put("LastName", edtLastName.getText().toString().trim());
                        params.put("Email", edtMailId.getText().toString().trim());
                        params.put("Password", edtPassword.getText().toString().trim());
                        params.put("DOB", edtDob.getText().toString().trim());
                        params.put("Gender", "" + RadioButtonMale.isChecked());
                        params.put("HomePhone", edtHomePhone.getText().toString().trim());
                        params.put("WorkPhone", edtWorkPhone.getText().toString().trim());

                        return params;
                    }
                };

                RequestQueue registerqueue = Volley.newRequestQueue(getContext());

                registerqueue.add(requestRegister);

            } else {

                generalUtilities.showAlertDialog("Hey User", "Please Connect To The Internet", getContext());
            }
        }

This is My login class :
 public void requestData() {

    if (generalUtilities.isNetworkAvailable()) {

        // mProgressDialog.show();
        StringRequest requestLogin = new StringRequest(Request.Method.POST, GlobalData.LOGIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            Log.e("login", response);
                            final JSONObject jObject = new JSONObject(response);
                            if (jObject.getString("status").equals("1")) {

                                // mProgressDialog.dismiss();

                                JSONObject jsonObject = jObject.getJSONObject("data");
                                Email = jsonObject.getString("Email");
                                Password = jsonObject.getString("Password");
                                Log.e("email", Email);
                                Log.e("password", Password);

                            } else {
                                Toast.makeText(getContext(), "data not getting from the server", Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("error", "" + volleyError.getMessage());
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Email","aman");
                params.put("Password","123345");

                return params;
            }
        };

        RequestQueue loginqueue = Volley.newRequestQueue(getContext());

        loginqueue.add(requestLogin);
    } else {
        generalUtilities.showAlertDialog("Hey User", "Please Connect to the Internet", getContext());
    }
}

A: *

*import Gson.jar on your project

*Use new Gson().toJson(Object o) will return a String Object to you! That's what you need!
Good luck!

A: What you need is getting an Object to save your uploaded data;
When you login, just use Intent.putExtra(Data)!
I hope it can help you !
public class SumitData{
private String FristName;
private String LastName;
private String Email;
...
}
SumitData sumitdata;
public void requestData() {
sumitdata = new SumitData();enter code here
   ...
sumitdata.setFirstName(edtFirstName.getText().toString().trim());
sumitdata.setLastName(edtLastName.getText().toString().trim());
...
Map params = new HashMap();
params.put("FirstName", sumitdata.getFirstName());
params.put("LastName", sumitdata.getSecondName());
...
return params;
...}


text:
Q: ASP.NET GridView vertical scrolling I've Grid View inside a IFrame. Its working nice when the records fit within the frame. But if I show more records then I'm unable to click on the Footer Row. It automatically goes up when I tries to scroll down. I'm using this Grid View inside the Update Panel of AJAX. Why it is happening like this? What could be the solution.
Thanks in advance.

A: *

*One think is that you do not need UpdatePanel, inside the iframe. Iframe is by him self a self loaded and you do not need to add extra ajax to complicate the thinks. So ether leave iframe and remove UpdatePanel, ether remove UpdatePanel keep iframe and make a resize after the page loaf.

*One second think is to see if you have scroll bars on the iframe.

*And one third as solution to your issue, is to recalculate the iframe size, on every reload/update.
How to recalculate the size
Use the onload on your iframe and recalculate/set the new width and height on your iframe.
The onload is fired when new content has been loaded inside the iframe.
Some similar:
Dynamically resizing navigation div to main content
Displaying two web pages on one page
On the internet you can find some example how you can get the internal width.
Here is one...
http://www.infoqu.com/dev/javascript-development/getting-iframe-width-194102-1/
var the_height=document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;//find the height of the internal page

var the_width=document.getElementById('the_iframe').contentWindow.document.body.scrollWidth;//find the width of the internal page


text:
Q: How do I find .bash_profile and add to my shell's initialization file? I am trying to upgrade ruby using rvm.
On the pragmatic site, it says:

The important part is to add the following line to the end of your shell's initialization file (.bash_profile):
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"

How do I do this? Where is this initialization file?
Please help

A: It would be /home/$USER/.bash_profile, but would only be present if you're actually using bash as your shell. Other shells will use a 'dot file' with their name in them instead. You can view them with ls -ad $HOME/.*

A: There are two initialization files .bash_profile & .bashrc, both present in user home directory.
.bash_profile is initialized when you login with userid. .bashrc is initialized when you are already logged in and want to open one more terminal.
If you want to add some settings in both the file then you can do following
if [ -f ~/.bashrc ];
 then
source ~/.bashrc
fi


text:
Q: PHP Composer scripts don't fire I'm trying to get post install and post update scripts working in a Composer package. Here's an excerpt from the composer.json file:
"autoload": {
    "psr-4": {
        "App\\": "src/"
    }
},

"scripts": {
    "post-update-cmd": [
        "App\\Install\\ComposerScripts::postUpdate"
    ],
    "post-install-cmd": [
        "App\\Install\\ComposerScripts::postInstall",
        "./test.sh"
    ]
}

And here is ComposerScripts.php:
<?php

namespace App\Install;

use Composer\Script\Event;

class ComposerScripts
{

    public static function postInstall(Event $event)
    {
        $io = $event->getIO();

        if ($io->askConfirmation('Install Mecab? ', false)) {
            return true;
        }

        exit;
    }

    public static function postUpdate(Event $event)
    {
        $event->getIO()->write("Working!");

        return true;
    }
}

And the file test.sh:
#!/bin/sh
echo Working

The ComposerScripts methods work if I test them with composer run-script and the test.sh script works fine, but when I install or update the package, nothing happens at all. No output, no error, nothing. Any idea what's going on here?

A: try with
"autoload": {
    "psr-4": {
        "App\\": "src/"
    }
},

"scripts": {
    "post-update-cmd": [
        "App\\Install\\ComposerScripts::postUpdate"
    ],
    "post-install-cmd": [
        "App\\Install\\ComposerScripts::postInstall",
        "bash test.sh"
    ]
}


text:
Q: Mocking callbacks in Laravel 4 (Mockery) I'm currently writing tests for a package in Laravel 4.
I am mocking the Illuminate\Database\Query\Builder which works nearly all the time except when a where method uses a callback, I cannot check if the methods inside the callback are called.
I was hoping one of you could shed some light.
$query = \Mockery::mock('Illuminate\Database\Query\Builder', function ($mock) {
    /** @var \Mockery\Mock $mock */
    $mock->shouldReceive('where');
    $mock->shouldReceive('orWhere')->twice();
});

And the actual where method that should call orWhere. Note: That builder mock gets passed to the class below.
$builder = new LaravelBuilder($query);

Which then calls $builder->filter() which contains the below code.
$this->query->where(function ($query) use ($filterData) {
    /** @var \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $query */
    foreach($filterData['columns'] as $colData) {
        /** @var \Samvaughton\Ldt\Column $column */
        $column = $colData['column'];

        // See if this column is searchable
        if (!$column->isSearchable() || !$colData['searchable']) continue;

        // If the individual column term is empty, use the main term
        $term = (empty($colData['term'])) ? $filterData['term'] : $colData['term'];

        // Actually apply the filter
        $query->orWhere($column->getSqlColumn(), "LIKE", "%{$term}%");
    }
});

The main part is the bottom bit $query->orWhere, the PHPUnit tests fail every time as it doesn't run the orWhere even once. Before you say that it might not reach the execution of it due to continue, the data I am passing will allow this.
I suspect this is due to how I am mocking the where method in the first place. If I include an exit before the foreach it does not execute indicating that it doesn't even run anything inside the callback. I know that is the default behaviour but how do I get Mockery to run the same/similar callback?
I have tried using partial mocks, using shouldExpect but don't fully understand it. I've also tried searching around but no luck with this scenario.
Would be great if I could learn how to use mockery within callbacks.

A: OK so I think this can be done a better way, but I resorted to partially mocking Laravel's query builder.
See line 324 in Illuminate\Database\Query\Builder
When using a closure Laravel spawns a new query builder which also needs to be mocked. Here's the code that worked:
$query = \Mockery::mock('Illuminate\Database\Query\Builder', function ($mock) {
    /** @var \Mockery\Mock $mock */
    $mock->makePartial();
    $mock->shouldReceive('where')->once()->passthru();
    $mock->shouldReceive('newQuery')->andReturn(
        \Mockery::mock('Illuminate\Database\Query\Builder', function ($mock) {
            /** @var \Mockery\Mock $mock */
            $mock->makePartial();
            $mock->shouldReceive('orWhere')->twice();
        })
    );
});

I needed to use makePartial() so the query builder retained its original functionality for closures (which is not true to unit testing) so this isn't the best solution. From here I mock the newQuery method which is called to spawn a new query builder instance which I then mock in a similar format.


text:
Q: Terraform to create autoscale VM rule setting based on Disk Write Operations/Sec or Disk Write Bytes Based on the autoscale rule criteria I am trying to create a terraform azurerm_monitor_autoscale_setting rule which increase/decreases VM nodes based on Disk Write Operations/Sec or Disk Write Bytes. The metric trigger looks like the following:
rule {
     metric_trigger {
            operator           = "GreaterThan"
            threshold          = 50
            time_grain         = "PT1M"
            statistic          = "Average"
            time_window        = "PT5M"
            metric_name        = "Disk Write Operations/Sec"
            time_aggregation   = "Average"
    }
}

However, I believe this is not the right syntax since once applying the terraform script it never creates this rule. On the other hand replacing the rule with "Percentage CPU" works fine. Have anyone created any metrics other than "Percentage CPU"? Can you help figuring out what is the right way to do it in terraform?

A: You lack the metric_resource_id. You could try the following example, this works on my side.
resource "azurerm_monitor_autoscale_setting" "test" {
  name                = "myAutoscaleSetting"
  resource_group_name = "${azurerm_resource_group.test.name}"
  location            = "${azurerm_resource_group.test.location}"
  target_resource_id  = "${azurerm_virtual_machine_scale_set.test.id}"

  profile {
    name = "defaultProfile"

    capacity {
      default = 1
      minimum = 1
      maximum = 10
    }

    rule {
      metric_trigger {
        metric_name        = "Disk Write Operations/Sec"
        metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}"
        time_grain         = "PT1M"
        statistic          = "Average"
        time_window        = "PT5M"
        time_aggregation   = "Average"
        operator           = "GreaterThan"
        threshold          = 75
      }

      scale_action {
        direction = "Increase"
        type      = "ChangeCount"
        value     = "1"
        cooldown  = "PT1M"
      }
    }

    rule {
      metric_trigger {
        metric_name        = "Disk Write Operations/Sec"
        metric_resource_id = "${azurerm_virtual_machine_scale_set.test.id}"
        time_grain         = "PT1M"
        statistic          = "Average"
        time_window        = "PT5M"
        time_aggregation   = "Average"
        operator           = "LessThan"
        threshold          = 25
      }

      scale_action {
        direction = "Decrease"
        type      = "ChangeCount"
        value     = "1"
        cooldown  = "PT1M"
      }
    }
  }

  notification {
    email {
      send_to_subscription_administrator    = true
      send_to_subscription_co_administrator = true
      custom_emails                         = ["admin@contoso.com"]
    }
  }
}

Result:


text:
Q: jquery: execute function since screen resolution 650px width Execute this function below only when the screen resolution is at least 650px wide. Otherwise, do nothing.
$('.section-box').waypoint(function() {
    $(this).addClass('animated-107s bounceDown');
}, {
    offset: '25%'
});

Could you help me?

A: You can try it.
<div class=".section-box" id="myClass">

JS
//control first open browser
  $(document).ready(function () {
    if( $( window ).width() <= 650 ){

          $("#myClass").addClass("bounceDown");

    }
  });

  //change browser size
  $( window ).resize(function() {

    if( $( window ).width() <= 650 ){
          $("#myClass").addClass("bounceDown");
    } else {
       $("#myClass").removeClass("bounceDown");
    }
  });


text:
Q: UIButton - unwanted background well I'm creating UIButtons (type = UIButtonTypeCustom) with a custom background drawn by an artist; unfortunately UIButton is adding an unwanted 'well' effect around the backgroundImage (as specified via setBackgroundImage). Is there a way to disable the well? It's not a simple drop shadow, so messing with the CALayer properties doesn't seem to help. I realise I could use UIControl, but that's considerably more work, since I need to handle the label subview myself, and get the artist to produce highlighted versions of the artwork - UIButton is doing all that nicely, if I could only disable the well effect.

A: Put your image inside a UIImageView, and then position your UIButton on top of it. Use the "custom" style, which has no UI to it at all and is totally invisible.
If you want to change ("highlight") your button image when the button is hit, just change the image contained in the UIImageView in whatever method your UIButton targets.


text:
Q: what ..x.. stands for in ggplot notation Often I see notation like that in ggplot or ggridges:
Consider a generic df:
ggplot(df, aes ( x = x , y = factor(y) , fill = ..x.. ) )

What ..x.. represents in the code above ?

A: When building a plot, ggplot2 creates a data.frame with all data it needs for plotting. This notation can be used to access columns of that data.frame. You don't provide a full example, so I'm showing it with stat_summary:
library(ggplot2)
p <- ggplot(mtcars, aes(cyl, mpg, color = ..ymin..)) +
  stat_summary(fun.data = "mean_cl_boot", size = 2)
print(p)

g <- ggplot_build(p)
g$data
#[[1]]
#   colour x group        y     ymin     ymax PANEL size linetype shape fill alpha stroke
#1 #56B1F7 4    -1 26.66364 24.23614 29.19114     1    2        1    19   NA    NA      1
#2 #316794 6    -1 19.74286 18.77107 20.74321     1    2        1    19   NA    NA      1
#3 #132B43 8    -1 15.10000 13.75696 16.30714     1    2        1    19   NA    NA      1

As you see, stat_summary calculates ymin values and we can map color to this (internal) variable.


text:
Q: Drupal install on localhost asks for FTP info I'm running Drupal 7.4 on localhost, and I've downloaded some themes/modules but I'm unable to install them.  I go to administration/modules, for example, select 'Upload a module or theme archive to install', choose the tar.gz from my file system, and before the install I'm asked for a FTP user and password and can not advance.
I'm working locally, so I'm thinking maybe I made some mistake during the install.  How can I correct this?  I have to do a lot of testing on local before moving the site to a server.

A: I found the solution here.  All I have to do is place the modules/themes inside drupal_folder/sites/default/modules or themes and that's it.
Thanks @nmc

A: This can happen when sites/default folder is not owned by the user that executes the install script. Make sure the folder sites/default is owned by the apache user (from your drupal root):
Ubuntu:
chown www-data sites/default

Fedora:
chown apache sites/default

A: If your not able to install the module, because the lack of a ftp connection, it's possible to use the old fashion way.
The other solution has described it, but it's not correct for a 100%.
If you want to do it the drupal way, you need to install the modules/themes to
drupalfolder/sites/all/modules
or
drupalfolder/sites/all/themes
if you are having a multi-installation of drupal, then:
drupalfolder/sites/domain_name/modules
or
drupalfolder/sites/domain_name/themes


text:
Q: Attempt to de-reference a null object error when logged user is not System Administrator I am trying to get article owner name and i'm getting this error when i'm not logged in as System Administrator. I tried changing permissions but it seems like there is no solution but, running code as System Admin. Only problem is that runAs is only permitted in Tests methods. is there any workaround?
@AuraEnabled
public static String getCommunityFeedbackOnArticleApexController(String recordId, String description, String articleName, String articleUrl) {
    // if required fields are not null or empty string
    if(description == null || description.equals('') && recordId == null || recordId.equals('')){
        return 'false';
    }
        try{

            User current = [SELECT Id, Contact.Name, Contact.Account.Name, Contact.AccountId FROM User WHERE Id =: UserInfo.getUserId()];

            Id articleId = Id.valueOf(recordId.rightpad(15, '0'));
            // gets sobject type __ka or __kav
            Schema.SObjectType objectToQuery = articleId.getSObjectType();
            String strObjectToQuery = String.valueOf(objectToQuery);
            // dynamically querying __ka or __kav object
            String strQuery = 'SELECT Article_Owner__r.Name FROM ' + strObjectToQuery + ' WHERE Id = \'' + recordId + '\' LIMIT 1';
            List<sObject> sObjectReturned  = Database.query(strQuery);

            String articleOwnerName;
            if(!sObjectReturned.isEmpty()){

                    // THE LINE BELLOW IS PRODUCING ERROR

                articleOwnerName = (String) sObjectReturned[0].getSobject('Article_Owner__r').get('Name');

            }
            else{
                articleOwnerName = 'Unknown author';
            }

            Article_Feedback__c articleFeedback = new Article_Feedback__c(

                Contact_Name__c = current.Contact.Name,
                Account_Name__c = current.Contact.Account.Name,
                Feedback_description__c = description,
                Article_Name__c = articleName,
                Article_Owner__c = articleOwnerName,
                Link_To_Article__c = articleUrl
                );

            insert articleFeedback;
            return 'true';

        }catch(Exception e){
            return 'message = ' + e.getMessage() + ' cause = '+ e.getCause() + ' line = ' + e.getLineNumber();

        }
        return'false';
}

message = Attempt to de-reference a null object, cause = null, line = 28

A: Check the Field Article_Owner__c on every object you might be querying (not sure which ones it is, you just call them __ka or __kav.
Here, enable Read Access for all the profiles.
This is most definitely an error that happens because only your System Administrator can see the field and when running as another user sObjectReturned[0].getSobject('Article_Owner__r') returns null and this is where the NullPointerException happens.

A: The problem was in OWD(Org wide defaults) where community user did not have permission to access User details. After changing permissions from private to public, the problem dissapeared.


text:
Q: How to find the row index of the first occurrence of a match in a cell in Python dataframe (containing date) I have a Python data frame containing a column with Date Time like this
2019-01-02 09:00:00 (which means January 2, 2019 9 AM)
There may be a bunch of rows which have the same date in the Date Time column.
In other words, I can have 2019-01-02 09:00:00 or 2019-01-02 09:15:00 or 2019-01-02 09:30:00 and so on.
Now I need to find the row index of the first occurrence of the date 2019-01-02 in the Python data frame.
I obviously do this using a loop, but am wondering if there is a better way.
With the df['Date Time'].str.contains() method, I can get that all the rows that match a given date, but I need the index.
The generic question is that how do we find the index of a first occurrence of a match in a cell in Python data frame that matches a given string pattern.
The more specific question is that how do we find the index of a first occurrence of a match in a cell in Python data frame that matches a given date in a cell that contains date Time assuming that the Python data frame is sorted in chronologically ascending order of date Time , i.e.
2019-01-02 09:00:00 occurs at an index earlier than 2019-01-02 09:15:00 followed by 2019-01-03 09:00:00 and so on.
Thank you for any inputs

A: You can use next with iter for first index value matched condition for prevent failed if no matched values:
df = pd.DataFrame({'dates':pd.date_range(start='2018-01-01 20:00:00',
                                         end='2018-01-02 02:00:00', freq='H')})
print (df)
                dates
0 2018-01-01 20:00:00
1 2018-01-01 21:00:00
2 2018-01-01 22:00:00
3 2018-01-01 23:00:00
4 2018-01-02 00:00:00
5 2018-01-02 01:00:00
6 2018-01-02 02:00:00

date = '2018-01-02'
mask = df['dates'] >= date
idx = next(iter(mask.index[mask]), 'not exist')
print (idx)
4

date = '2018-01-08'
mask = df['dates'] >= date
idx = next(iter(mask.index[mask]), 'not exist')
print (idx)
not exist

If performance is important, see Efficiently return the index of the first value satisfying condition in array.

A: Yep you can use .loc and a condition to slice the df, and then return the index using .iloc.
import pandas as pd
df = pd.DataFrame({'time':pd.date_range(start='2018-01-01 00:00:00',end='2018-12-31 00:00:00', freq='H')}, index=None).reset_index(drop=True)

# then use conditions and .iloc to get the first instance
df.loc[df['time']>'2018-10-30 01:00:00'].iloc[[0,]].index[0]

# if you specify a coarser condition, for instance without time,
# it will also return the first instance
df.loc[df['time']>'2018-10-30'].iloc[[0,]].index[0]

A: I do not know, if it is optimal, but it works
(df['Date Time'].dt.strftime('%Y-%m-%d') == '2019-01-02').idxmax()


text:
Q: pyramid_handlers not working I'm currently moving a project from Pylons 1.0 to Pyramid.
My problem so far is how to use restful routes in Pyramid. I'm currently using pyramid_handlers since it seemed like a good start. I'm using Akhet.
So here is the two important lines in my route:
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts")
# or
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts", action="new")

My action:
@action(name="new_account", renderer='accounts/new.mako', request_method='GET')

The errors:
 TypeError: 'Accounts' object is not callable
 or
 ValueError: Could not convert view return value "{}" into a response Object.

Accounts... so far so good, it is easy to understand that pyramid_handlers doesn't seem to register normally or handle name as it should... that said in request.matched_route, I do have "new_account".
If I add "action='new'" in the route definition, it will find the function but it will not listen to the action definition. In other words, it will fail to find a renderer and expect a response object. The request_method parameter doesn't actually do anything yet, so removing it doesn't change any results.
In short, the @action(name="..." doesn't work. Pyramid fails to find the function by itself and if the function name is defined it fails to execute the action statement.
No idea what I'm doing wrong.
Correct way to do it.
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts", action="new_account")

EDIT
route_name is probably going to get used by url generator functions. While action is the actual name in @action. As I understood, @action name was the route_name and not the action name. That makes more sense now.

A: Well a call to add_handler needs an action pattern. So that's either adding {action} to the url pattern, or setting action= as an argument. Those actions must match the names defined in @action decorators. In your example, you named the action new_account, yet you called add_handler with an action of new. Thus they aren't properly connected.


text:
Q: Title of science fiction novel from the '80s or early '90s with small furry aliens There was another alien species that was invading Earth, and the little furry aliens helped us out. I think they liked having sex all the time and ended up having sex with the humans as well.

A: Might you be talking about Allen Dean Foster's Quozl?

The Quozl knew they'd love the third planet from the sun. But it never occurred to them that anyone lived there...

The eponymous Quozl, based off of rabbits, have a stereotypical fixation on constant sex, and indeed, part of the ending indicates that they have no problem with humans being the target of this behavior...


text:
Q: Trigger an action in C# windows form from command line? I've done some searching but conflicting terms for my question makes it hard to find what I'm looking for, if it's even possible.
What I would like to do is to run a windows form C# program and have it "listen" for external commands, ideally sent somehow through a windows command line.
The use case is that I have some automation software that I have to run with some test equipment software. During different points of my test, I need to run a script in my automation software (manually selecting the script and pressing a button). However, I can include steps in my sequence in the test software that fires windows command line commands. The goal is to send a command to my running C# application that will load my script, automating the process even further.
While I could simply re-write a smaller version of my automation software that is single-run use and uses command line arguments, there is a bunch of pre-amble that the automation software that connects to some hardware that would make the process take longer than working in the automation software manually.
Is it possible to create an external hook in C#? I'm not looking for a full code answer. I mostly just need the name of this feature so that I can look it up and learn it properly.
Hopefully I've made this clear enough.
Edit:
As an extra bit of information, I only have access to the source of my automation software, not the testing software. The only options I have for the testing software is to export a file (which I may end up having to poll a file for changes in the automation software), or running a windows CMD command.

A: There are multiple ways of passing information between applications as you can see from the link Ian Kemp posted in the comments. If you're looking for something simple, you could just use the Windows command line to create a text file in a specific folder. Your C# application could then monitor that folder for new files, read the content, delete the file and perform the required actions.
Here's an example command for creating the file from your script. I've used the date and time for the file name to try to make it unique. As long as there's a short delay between files being created this should be fine. Otherwise you may want to name the files another way, maybe incremental numbers? On my system the date and time are formatted as dd/MM/yyyy HH:mm:ss. This example replaces the forward slashes and colons with dashes to make a valid file name. You may need to adjust this dependent on the date and time format on your system.
echo some command > C:\SomeFolder\%date:/=-%-%time::=-%.txt

Then in your Win Forms C# app you could do something like this. You'll need to add using System.IO; for the FileSystemWatcher class.
private void Form1_Load(object sender, EventArgs e)
{
    FileSystemWatcher fileWatcher = new FileSystemWatcher()
    {
        Path = @".\", // Path of the directory you want to monitor
        Filter = "*.txt", // Filter for the file names
        NotifyFilter = NotifyFilters.LastWrite, // Raise an event when the write time of a file changes
        EnableRaisingEvents = true
    };
    fileWatcher.Changed += FileWatcher_Changed; // Subscribe to the file changed event
}

private void FileWatcher_Changed(object sender, FileSystemEventArgs e)
{
    // Read the contents of the file and delete it
    string command = File.ReadAllText(e.FullPath).Trim(); // ReadAllText() may not be the best option, but it's just an example
    File.Delete(e.FullPath);

    // Check the contents of the file and decide what to do
    if (command == "some command")
    {
        DoSomething();
    }
    else if (command == "something else")
    }
        DoSomethingElse();
    }
}


text:
Q: Lightning Web Component Push Failed i import the method that i have to use in JavaScript file like this
import getRoles from '@salesforce/apex/LeaveSettingsController.getRoles';
@wire(getRoles)
rolesList;
when i'm trying to push the code to my scratch org i got an error like this
Unable to find Apex action class referenced as 'LeaveSettingsController'
I create an apex class in my DevHub org
public with sharing class LeaveSettingsController {

    public LeaveSettingsController(){

    }

    @AuraEnabled(cacheable=true)
    public static List<UserRole> getRoles(){
        return [SELECT Id, Name FROM UserRole];
    }
}

I have a DevHub org and only one scratch org and i use this command to push the code to the scratch org using the VS Code:
sfdx force:source:push

A: First, you need to create an apex class using below command from command palette,
sfdx: create apex class

You need to enter your class name, then just press enter to select default directory for apex classes.
A class will be created in your project in a folder like ...\default\classes.
Just paste all your code over there.
Then you can push to scratch org, which will create an apex class in your scratch org, and you won't get any error.
Update - An alternate way: If scratch org is open in the browser, you can also create apex class from there by going to setup -> Apex Classes.

A: In my case, the problem appeared because during on deploy I forgot to include Apex Classes
I used a command
sfdx force:source:deploy -m LightningComponentBundle

while I should have used a command
sfdx force:source:deploy -m ApexClass,LightningComponentBundle

This helps in the case when the source code is deployed from Version Control System into Developer Edition organization or to the scratch org as well.
However, in case of scratch org, instead of command
sfdx force:source:push -m LightningComponentBundle

another command should be used
sfdx force:source:push -m ApexClass,LightningComponentBundle


text:
Q: filter dataframe on several columns using base or dplyr I'm trying to filter the rows of a data frame based on columns in another datagram. Basically, I want to extract rows with the same IDs where the position is between start and end. There is the extra trick that the IDs are formatted differently.
finally, the data involved in the script is huge so to save memory or speed is nice to have.
would be grateful to get some tips.
library(dplyr)

df1 <- data.frame(id = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                  pos = c(30, 40, 50, 35, 45, 55, 60, 63, 39))

df2 <- data.frame(idstr = c("id1", "id1", "id3", "id4", "id4"),
                  start=c(30, 20, 30, 40, 20 ),
                  end = c(40, 30, 50, 60, 45))

df.base <- df1[ paste0("id", df1$id) == df2$idstr &&
                 df1$pos >= df2$start &&
                 df1$pos <= df2$end,]

df.dplyr <- df1 %>%
            left_join(df2, by  = c('id' == 'idstr') ) %>%
            filter(pos >= start & pos <= end) %>%
            select(id, pos)

edit:
expected output, the rows from df1 meeting the condition (their position is in a range of df2 with the same id), so if no mistake:
id, pos
1, 30
1, 40
3, 39
explanation: for example, df1[3,] id == 1 and pos == 50
looking at df2, there is no row where df2$id == "id1" and df2$start <= 50 and df2$end >= 50, so df1[3,] would be filtered out.

A: We can use non-equi join in data.table.  Create the 'id' similar in both datasetss and then join on the 'id' columns and non-equi join with 'pos' and 'start', 'end' columns
library(data.table)
setDT(df1)[, id := paste0('id', id)]
df1[df2, on = .(id = idstr, pos >= start, pos <= end)]

A: I have taken your 2 DF df1 and df2, mutated column idstr from df2 into a numeric by extracting the digits. Then with a left_join, group_by and filter I get the result.
library(dplyr)

df1 <- data.frame(id = c(1, 1, 1, 2, 2, 2, 3, 3, 3), pos = c(30, 40, 50, 35, 45, 55, 60, 63, 39))

df2 <- data.frame(idstr = c("id1", "id1", "id3", "id4", "id4"),
                  start=c(30, 20, 30, 40, 20 ),
                  end = c(40, 30, 50, 60, 45))

df2 %>%
  mutate(idstr = as.numeric(stringr::str_extract(idstr, '[0-9]'))) %>%
  left_join(df1, by = c('idstr' = 'id')) %>%
  dplyr::filter(pos >= start & pos <= end)
#> # A tibble: 4 x 4
#> # Groups:   idstr [2]
#>   idstr start   end   pos
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     1    30    40    30
#> 2     1    30    40    40
#> 3     1    20    30    30
#> 4     3    30    50    39

There is one df1$id == 1 which fits into 2 start-end slots in df2. And therefore it has to be 3 positions with id =1.
If one of the limits is exlusive - like in the following code - it fits your wish.

df2 %>%
  mutate(idstr = as.numeric(stringr::str_extract(idstr, '[0-9]'))) %>%
  left_join(df1, by = c('idstr' = 'id')) %>%
  dplyr::filter(pos > start & pos <= end)

#>   idstr start end pos
#> 1     1    30  40  40
#> 2     1    20  30  30
#> 3     3    30  50  39


text:
Q: How do I use driver from Universal directory in a UEFI_APPLICATION I want to use some of the functions provided by the PartitionDxe, but I do not understand how to use this driver within my application as it does not have GUID in any header files. What do I need to include in the inf/dsc and how can I use it after it is linked to my application?
Thanks

A: PartitionDxe is a driver and not a library.
It provides access to the logical partitions based on the disk layout (Gpt, Mbr,...), to do that it creates new instances of BlockIo(2), DiskIo(2) and PartitionInformation protocols.
If you need some of its functions you have to copy it from the source code files.


text:
Q: Get characters after a given word How to find a certain word in a file name and get some characters after it?
For example:
File 01 - Vertical - Day 04 - Model 01-01
File 02 - Model 01-02 - Day 02
How forever find the word Model in a file name and extract the 5 characters that come after it, i.e. XX-XX?
I believe that after finding a way to search for the word Model I can use .substring() to get the characters I want, but I haven't found an exact way to do that, since the place of the word Model doesn't follow a pattern for me can use -Split.

A: Personally I would go with regex and named capture (though note the (in)famous quote - "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."):
PS C:\windows\system32> 'File 02 - Model 01-02 - Day 02' -match 'Model (?<model>\d+-\d+)'
True
PS C:\windows\system32> $Matches.model
01-02

Regex - Model (?<model>\d+-\d+)', regex explanation - @regex101:

Model  matches the characters Model  literally (case sensitive)
1st Capturing Group (\d+-\d+)
\d matches a digit zero through nine in any script except ideographic scripts (equivalent to \p{Nd})
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
- matches the character - with index 4510 (2D16 or 558) literally (case sensitive)


text:
Q: How to use existing go daddy certificate for nodejs application We have developed a single page application (static html files) and planned for deployment into QA and LIVE. It is using backend as Nodejs (Express js) as hosting server.
We are already having godaddy certificate authority g2 with other applications which wanted to use the same for the above developed nodejs based application.
How can use existing godaddy certificate with nodejs developed application for deployment testing like QA?


text:
Q: Replacing data on array list from index n to x I have two Integer type ArrayLists. How would I go about replacing the values of ArrayList 1 from index 5 to 10 with values of the same Index from ArrayList 2, without having to type it all separately?
What I tried to do :
ArrayList1.set(5, Arraylist2.get(5)); // Set 5th index of Arraylist1 to 5th of Arraylist2
ArrayList1.set(6, ArrayList2.get(6));

.....
ArrayList1.set(10, ArrayList.get(10));

While this certainly works, it takes a lot of lines of code and gets kind of hard to read.

A: What about a loop like this :
int startIndex = 5;
int endIndex = 10;
for(int i = startIndex; i < endIndex; i++){
   arrayList1.set(i, arraylist2.get(i));
   //-------------^-----------------^
}

A: references :

*

*addAll

*remove range

yourOldList.removeRange(fromIndex,toIndex);
yourOldList.addAll(fromIndex,yourNewList);

A: In adition to the other answers you can handle such an issue by utilising the Java 8 feature streams:
 arli1.stream().filter( e->(arli1.indexOf( e ) > startIndex && arli1.indexOf( e ) < endIndex)).map( e->arli2.set( arli1.indexOf(e), e ) ).count();
Which, to be fair, might be a little bit over the top for your particular issue but it works with interal iterations which performs quicker when a lot of data is processed.
Note:  count()  at the end of the stream is necessary to force the stream to execute since  filter()  and  map()  are "lazy" operations and need an "eager" operation to run. But any other eager method would to do the trick as well.


text:
Q: Assign object owner to a role other than the creator automatically on creation for a database Background:
I'll start by saying I'm fairly new to postgres, I generally work with web apps and I know my way around SQL but I'm new to both postgres and database administration. I have however read through the postgres docs for database roles.
My team at work is rather small and we're responsible for the building and deployment of a web application which uses postgres as our main database. There are about 3 of us who actively work on the database. This includes creating, altering (and occasionally dropping) tables, and doing the same to functions and types.
We've recently run into the problem of object ownership. It seems only the owner of an object can drop it from the database, be that any database object. We want reasonable freedom to be able to manipulate the database as required without messing around too much with object ownership all the time.
At the moment we haven't had the chance to automate the deployment of our database changes via migration scripts and the responsibility of running these falls to the individual leading a feature development and deployment.
Question:
We'd like a way to assign object ownership to a group role (which we would all have access to) without having to do it manually after every object creation. Is there a way to set this up globally for a schema or database, or even for a group role? If in the (likely) event that this is a really silly thing to do, does anyone have any suggestions of how we should be working in this scenario?
Things we've explored:
I have already gone through the alter default privileges but it seems this must be set for every login role (user), which feels like there's some friction meaning we might be going in the wrong direction. Past that, google and stack exchange have turned up little, though I may not be using the correct terminology.

A: You can't use alter default privileges because it can't reassign ownership.
What you could do instead is run for each dev:
alter user john_q_developer set role = feature_role;

This way all of the developers will by default create all their objects with feature_role as the owner.  This is pretty much the same thing as all the developers just logging on to the database as the same user, except this way they all get their own password (or their own authentication method of choice) rather than sharing one.
This has the same "friction" that alter default privileges does, in that you have to run the alter user ... one time for each create user ..., but that level of friction seems pretty small to me.
The objects won't be tagged inside the database with who created them, but you can set up the server to log that information if you want (include "%u" in the log_line_prefix, and set log_statement = 'ddl' in the configuration file postgresql.conf.)
A slightly more restricted approach would be to create a feature_owner role that can create objects, and a feature_dev noinherit in role feaure_owner role which has all rights other than to create objects, and grant all devs the role feature_dev.
That way attempts to create objects will fail by default, but anyone can just execute set role = feature_owner and then repeat the creation in order to create objects under that ownership.  It would just be common knowledge that only the feature lead is supposed to make use of this power under normal circumstances.


text:
Q: can't call onNewIntent My program has MainActivity and myService.
MainActivity is 'singletop', and MainActivity overrides onNewIntent class.
myService is 'foreground' Service.
It pop up a notification.
The notification has Intent(this,MainActivity.class) in pendingIntent to start MainActivity.
My program's flow is
Launch from icon (start) MainActivity (startService) myService (send broadcast) broadcast class(start MainActivity)onNewIntent@MainActivity
When program is Launched like this flow, onNewIntent is called exactly.
But when program is Launched from notification,
onNewIntent never called.
Launch from Notification (start) MainActivity (startService) myService (send broadcast) broadcast class(start MainActivity)onNewIntent@MainActivity

A: From the guide at http://developer.android.com/guide/topics/manifest/activity-element.html
Similarly, a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the "singleTop" activity is in the target task, but not at the top of the stack, or if it's at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack.
Thus onNewIntent is only called if there is an existing instance of the activity at the top of the stack.


text:
Q: Using if else on update sqlplus How do i actually use if else with update in sql?
I have tried a lot of ways but it still doesnt work.
This is the question:
Add a column called 'Status' to a relational table Customer and use one UPDATE statement to fill the column with information about the customer status. Mark 'Y' if the customers had placed any orders otherwise 'X' will be initialised.
I am stuck at the update part.
UPDATE CUSTOMER
IF(customer.customerID IN (SELECT customerID from invoice))
( set status = 'y' )
else
( set status = 'x' )
endif
where status is null;

A: You could use a case statement
UPDATE CUSTOMER
SET Status = CASE WHEN CUSTOMER.CUSTOMERId IN (SELECT customerID from invoice)
    THEN 'y'
    ELSE 'n' END
where status is null;

A: What you want to do is a case statement because that's the closest you can get to an IF in sql.
update customer
set status
  case
    when exists (select customerID from Customer where CustomerID in (select customerID from invoice)
    then
        'y'
    else
        'x'
  end
where stats is null

A: DECLARE      @customerID INT
SET          @customerID = (SELECT       CustomerID
                            FROM         Invoice
                            WHERE        CustomerName = 'some_customer_name')

IF (@customerID = NULL)
BEGIN
   UPDATE     Customer
   SET        Status = 'Y'
   WHERE      CustomerID = @customerID
END
ELSE
BEGIN
   UPDATE     Customer
   SET        Status = 'x'
   WHERE      CustomerID = @customerID
END


text:
Q: How to get deep relation in Entity Framework in many to many relation? I have following many to many relations:
PersonBook; BookAuthor; BookGenre;

I can get a Person's Books, but it does not contain Author and Genre list.
I created a model for each class and map entity object to that model.
Solution in EF6:
 Person person = db.Person
                 .Where(p => p.PersonID == 1)
                 .Include(p => p.Books.Select(b => b.Authors))
                 .Include(p => p.Books.Select(g => g.Genres))
                 .FirstOrDefault();

A: To get related data in Entity FrameworkCore the best choise is to use Include() and ThenInclude() methods:
Person person = db.Person
                .Where(p => p.PersonID == 1) // change this
                .Include(ba => ba.BookAuthor.Select(a => a.Author)
                .Include(bg => bg.BookGenre.Select(g => g.Genre)
                .First();


text:
Q: Using bufio in Golang to blank a line of all text I am using bufio and I want to erase a line.  The issue I'm running into now is I need to overwrite it with blanks and feels programmatically unsafe.  If there an idiomatic way to clear out a line in Stdout?
var Output *bufio.Writer = bufio.NewWriter(os.Stdout)

func MoveCursor(x int, y int) {
    fmt.Fprintf(Output, "\033[%d;%dH", y, x)
}

func Print(a ...interface{}) (n int, err error) {
    return fmt.Fprint(Output, a...)
}

Output.Flush()
scanner := bufio.NewScanner(os.Stdin)
const BLANK = "                                                      "

for {
    MoveCursor(1, 1)
    Print(BLANK)
    MoveCursor(1, 1)
    Print("Hello ", scanner.Text())
    MoveCursor(1, 4)
    Print(BLANK)
    MoveCursor(1, 4)
    Print("> ")
    Output.Flush()
    scanner.Scan()
}

One thing that is especially surprising is that Output.Flush() doesn't clear the entire content of the screen.


text:
Q: Is "deload" a legitimate verb? I was reading something about strength training and I came across that word. I am wondering if that's a legitimate verb?
If so, what would be the difference between "deload" and "offload" or even "unload"?
It seems that term was once coined as an attributive word (noun/adjective) and then evolved into the verb!
Added later: You can find several instances of this word in the link below, for example:

This is not referring to normal deloading.  With a deload, your goal is to do as little as you can to maintain performance while diminishing fatigue, meaning minimizing muscle loss and likely increasing in strength (with fatigue diminished). [Reference]

A: In the context you provide, "deload" is clearly a jargon term related to muscle strength training.  Presumably you can only "load" (meaning "train hard") for a limited period of time before you have to "deload" (train less strenuously) to allow your muscles time to recover.
It's unlikely the author coined this term, but rather just uses a common expression in the world of body building.  It was likely created because A) it's only meaningful in the context of a particular activity, and B) the meaning is completely different from "unload" or "offload".

A: It's not a standard or common word, but in the context you've provided it seems to have currency with a specific meaning of intentionally diminishing one's weight training amounts.
Offload means something a little different (to reallocate something away from something or someone, generally). Unload is a bit more technical, e.g. in structural engineering, where structures experience loading and unloading over time from changing factors-- or e.g. in software where bits of code could be loaded or unloaded from memory. (In both these latter cases, unload has a sense of "undoing" or reversing a load, which doesn't seem to really apply in the weight training context.)
I've never heard of deload and I wouldn't use it in any general context. This seems to be a case of a niche domain appropriating/creating a domain-specific bit of terminology.

A: We were talking about deloading in the Christian Morning show of the RBG Life FM in Auckland, New Zealand. For us deloading means to pass on, throw away, put down, get rid of something that is too much or heavy with the intention of never taking it back, and it can not come back either, ever. Like a donation, or confession of sin, or honestly open up about an issue, or speaking about depression, something that hurts in a way that it is finally out and away with it forever. After this the person feels much better, lighter, refreshed, forgiven, emptied out, decluttered, with a possibility of a fresh, new start, mentally renewed.


text:
Q: log4j doesn't see log4j.properties file I'm trying to configure logging in my app where log4j.properties is put to /resources folder an has the following content:
#log level
log4j.rootLogger=ERROR, file
log4j
#
log4j.appender.file=org.apache.log4j.RollingFileAppender
#
log4j.appender.file.File=D:\agent\temp\panel log.log
#
log4j.appender.file.MaxFileSize=1MB
#
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

and on my app start I see the following in the console:
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

what does this mean and how to fix it?

A: Try putting the log4j.properties in the root of your source folder. Or alternatively add resources to your classpath.
The root problem is log4j not seeing your config file, so you need to make it accessible.
Extract from log4j manual:

Default Initialization under Tomcat
The default log4j initialization is particularly useful in web-server
  environments. Under Tomcat 3.x and 4.x, you should place the
  log4j.properties under the WEB-INF/classes directory of your
  web-applications. Log4j will find the properties file and initialize
  itself. This is easy to do and it works.
You can also choose to set the system property log4j.configuration
  before starting Tomcat. For Tomcat 3.x The TOMCAT_OPTS environment
  variable is used to set command line options. For Tomcat 4.0, set the
  CATALINA_OPTS environment variable instead of TOMCAT_OPTS.

A: I had the same problem, I was using tomcat 7.
I solved the problem by adding conf path to the /bin/setenv.sh (if you are on linux, create the file if it does not exist) like this:
export JAVA_OPTS="$JAVA_OPTS -Dconfig.location=file -Dlog4j.configuration=file:///opt/apache-tomcat-7.0.61/lib/log4j.properties"

if you are on windows edit or create setenv.bat and write something like this (not sure about the path format):
set JAVA_OPTS=%JAVA_OPTS%-Dconfig.location=file -Dlog4j.configuration=file://c:/opt/apache-tomcat-7.0.61/lib/log4j.properties

Forgot to say: this will affect all the apps on the server

A: i've changed log4j.properties to log4j.xml and put it to resources folder and now everything is correct. maybe my log4j version doesn't supprot .properties format


text:
Q: asp.net mvc: how to keep data information to pass it from one element to another screen in javascript? I have created JS demo that has multiple listings. Each listing has a div with car details like name, price and kms. Along with this, each listing has two buttons "call" & "chat" to help the user to connect to the seller of this listing.
The fiddle demo is here. Example code:

1st listing

Model:Audi | Price:1,00,000,000 | Kilometers:1,000

<button class="call" data-model="Audi" data-price="100000000" data-id="#1">call</button>
<button class="chat" data-model="Audi" data-price="100000000" data-kms="1000" data-id="#1">chat</button>

I have a couple of doubts regarding bindings of information. I have MVC app so all attributes i.e. data-model, data-price etc. & information in each HTML element gets bound through the server.
Both of these buttons "call" & "chat" opens a pop up with different information and on confirmation on the pop up needs to hit different APIs. I have currently done duplicate bindings on both the buttons which isn't efficient way. How should such bindings be handled?
These buttons (chat/call) can be part of li as shown in example OR part of div where the listing is shown independently to the user (i.e. product details page of e-commerce). How should binding of these buttons be handled?


text:
Q: UICollectionViewFlowLayout subclass not working Here is my UICollectionViewFlowLayout subclass:
@implementation MyCollectionViewFlowLayout

- (id)init
{
    self = [super init];
    if (self) {
        [self setup];
    }

    return self;
}

- (void)setup
{
    self.itemSize = CGSizeMake(320, 320);
    self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.minimumInteritemSpacing = 0;
    self.minimumLineSpacing = 0;
    self.scrollDirection = UICollectionViewScrollDirectionVertical;
}

- (void)prepareLayout {
    [super prepareLayout];

}

- (CGSize)collectionViewContentSize {
    return self.itemSize;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray* allAttributesInRect = [super layoutAttributesForElementsInRect:rect];

    return allAttributesInRect;
}

- (UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes* attributes = [super layoutAttributesForItemAtIndexPath:indexPath];

    return attributes;
}

@end

When I do the following, the collection view will not scroll:
MyCollectionViewFlowLayout* flowLayout = [[MyCollectionViewFlowLayout alloc] init];

However if I do this:
UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.itemSize = CGSizeMake(320, 320);
flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
flowLayout.minimumInteritemSpacing = 0;
flowLayout.minimumLineSpacing = 0;
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

Then the collection view scrolls fine. What am I doing wrong in the UICollectionViewFlowLayout subclass?

A: The problem is collectionViewContentSize
- (CGSize)collectionViewContentSize {
    return self.itemSize;
}

Returning itemSize here means that the entire contentSize for your collection view is only the size of one item. Try removing that code, or changing it to
- (CGSize)collectionViewContentSize {
    [super collectionViewContentSize];
}


text:
Q: How do I connect these two forms to get the input working in React Native? I am having trouble getting these two forms to just show the number input from my Virtualized Keyboard. Essentially what is going on here is that I have a numeric keypad passing in the numbers from the virtualized keyboard and a currency component to be able to have the currency format (thousand commas, and decimals).
Here is the UI for better idea of what I'm trying to explain.

When I press the keypad it says this:
This is the error I get

Here is my code:

import React, { useState, useEffect, useCallback } from "react";
import {
  ScrollView,
  StyleSheet,
  Image,
  TouchableWithoutFeedback,
  ImageBackground,
  Dimensions,
  View,
  StatusBar,
  SafeAreaView,
  TextInput,
  Keyboard
} from "react-native";

import { Block, Text, theme } from "galio-framework";
import VirtualKeyboard from 'react-native-virtual-keyboard';
import CurrencyInput from '../components/CurrencyInput';
import Button from '../components/Button'
import { HeaderHeight } from "../constants/utils";

const { height, width } = Dimensions.get("screen");

const Give = () => {

  const [value, setValue] = useState(0);
  const handleValueChange = useCallback(val => {
    // eslint-disable-next-line
    console.log(val);
    setValue(val);
  }, []);

  return (

    <View style={style.container}>
      <SafeAreaView>
        <Block style={style.allContainer}>
          <Block style={style.numberContainer}>
            <TouchableWithoutFeedback onPress={Keyboard.dismiss()} accessible={false} >
              <CurrencyInput
                max={100000000}
                onValueChange={handleValueChange}
                style={style.inputNumber}
                value={value}
              />
            </TouchableWithoutFeedback>
          </Block>
          <VirtualKeyboard color='#000' pressMode='string' onPress={(val) => setValue(val)} />
          <Button style={style.button}><Text style={style.buttonText}>Ofrendar</Text></Button>
        </Block>

      </SafeAreaView>
    </View>
  )
}

const style = StyleSheet.create({
  container: {
    marginTop: Platform.OS === 'android' ? -HeaderHeight : 0,
    height: height,
    flex: 1,
    flexDirection: 'row',
    backgroundColor: "#fff",
    width: width
  },
  backgroundImage: {
    width: width,
    flex: 1,
    resizeMode: "cover",
  },
  animationContainer: {

  },
  animationImage: {
    height: 250,
    aspectRatio: 1,
    alignSelf: "center",

  },
  ofrenda: {
    fontSize: 55,
    textAlign: "center",
    fontWeight: "bold",
    marginBottom: 70
  },
  buttonText: {
    color: "#FFF",
    fontSize: 30,
    fontWeight: "bold",
    letterSpacing: 2
  },
  button: {
    height: 60,
    width: width - theme.SIZES.BASE * 6,
    marginBottom: 30,
    marginTop: 30,
    backgroundColor: "#00a8ff",
    borderWidth: 3,
    borderRadius: 10,
    borderColor: "#00a8ff",
    shadowColor: "transparent"

  },
  bottomButton: {
    position: 'absolute',
    bottom: 30
  },
  numberContainer: {

  },
  inputNumber: {
    fontSize: 50,
    fontWeight: "bold"

  },
  allContainer: {
    justifyContent: "center",
    alignItems: "center",
    height: height,
    width: width,
    alignSelf: "center"

  }

});

export default Give;


text:
Q: Wordpress: Get Terms of current archive or custom post type I'm trying to code a little Taxonomy-Filter for my Custom-Post-Type-Pages, Archives and Term-Pages. Therefore I try to find out, which taxonomy is used on current page.
For example: http://www.domain.de/taxonomy, or archive of custom-post-type like http://www.domain.de/portfolio
Example: I build a portfolio-page with custom post-type. I gave this the taxonomies "skills" and "category". On the page-portfolio.php and archive-portfolio.php there will be a filter with the terms of "skills" and "category".
$terms = get_the_terms($post->id, 'TAXONOMY_NAME'); should not fit, because, the filter should fit for many unknown Taxonomy and Custom-post-types. Also there is no fixed taxonomy-name available.
        $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
        $incname = $term->taxonomy;
        $args = array( 'hide_empty=0' );
        $terms = get_terms( $incname, $args );

        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
            //do spomething
            else {
            //do spomething
            }
        }

The code above works only, if the current page is already a term-page (http://www.domain.de/taxonomy/term)
        $term = $wp_query->queried_object;
        $taxonomy = $term->taxonomy;
        $terms = get_terms($taxonomy);

        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
            //do spomething
            else {
            //do spomething
            }
        }

The code above works only, if the current page is already a term-page (http://www.domain.de/taxonomy/term)
How can I get the taxonomies and (child-)terms of current post-type?

A: Have you looked at wp_get_post_terms()?(http://codex.wordpress.org/Function_Reference/wp_get_post_terms)
From your description, it looks like it should give you the terms you need.
HTH!
=C=


text:
Q: Make site page content load first before Footer component I have used setTimeOut on Footer Component but the footer still loads first on all the pages. How do I make sure the dynamic content loads first before the footer.
function Footer({ rawdata, theme, locale }) {
  const [isFooter, setFooter] = useState(false);
  useEffect(() => {
    setTimeout(() => setFooter(true), 3000); // let page load first before footer
  }, []);
  if (isFooter) {
    return ()

The main component where the footer is used
import ScrollToTop from 'react-router-scroll-top';
import styled, { ThemeProvider } from 'styled-components';
...
...
<ThemeProvider theme={theme}>
        <>
          {navbarState.data !== false && (
            <Navbar
              isUserAuthenticated={isUserAuthenticated}
              locale={locale}
            />
          )}
          <ScrollToTop>{renderRoutes(route.routes)}</ScrollToTop>
          <Footer rawdata={footerState.data} locale={locale} />
        </>
</ThemeProvider>

A: How is the dynamic content being loaded? Are you doing an ajax call? If so, you can change a state variable to show the footer when the ajax returns. You should put the isFooter variable (would showFooter be a better name?) in a place where both components can see it: either a common ancestor component or maybe React Context. isFooter will then be passed as a prop of Footer. Or you could check isFooter in the parent component and not render Footer at all while isFooter is false.


text:
Q: Submit Form with data to and from cURL request I'm trying to get a page that displays a form to allow a file upload which then, on submit runs a php function (curl) to upload the file to an API. But then I need an upload token from the API to come back and include itself in the form.
I'm not really sure what the best way to go about this is, and am a mere beginner with this stuff.
My code so far is as follows:
and as you can see I've tried running the php function on submit, and then jQuery to append a hidden input with a variable back from the curl response, but I have no idea if this is even possible.
Can anyone give any pointers to a potentially better way to do this?

<title>Zendesk Form</title>

<?php

require_once('zendesk.php');

if (isset($_POST["z_name"])) {

$upload = $_POST['z_attachment'];
$initial = curlWrap("/uploads.json?filename=license2233.txt", $upload, "POST");

?>

<?php } ?>

<form id="zenForm" method="POST" action="zenconnect.php" name="zenform">

Name:
<input type="text" value="" name="z_name">

Email:
<input type="text" value="" name="z_requester">

Subject:
<input type="text" value="" name="z_subject">

Change:
<textarea value="" name="z_description"></textarea>

Attach Files:
<input type="file" name="z_attachment">

<input type="submit" value="Send Changes" id="zenSubmit">

</form>

A: Maybe you should rethink about using php-curl.
You have tagged jquery - so i suggest you capture your submit event on your form and control it yourself. this will prevent your page from rerendering.. some code of what i mean:
get your form data with selectors in this style
var request_data = {
  z_name: $('input#(id of zname input field').val(),
  z_subject: $('input#(id of zsubject input field').val(),
...
} //you havent set your id's yet

$.post("youruri", request_data, function(data, err){
  if(err){
    console.log(err);
  } else {
    //do something with your received data
  }
});

does this help?


text:
Q: Lie Group Homomorphism from $U(n)$ into $SO(2)$ The task was to find an onto Lie Group Homomorphism from $U(n)$ onto $SO(2)$ and I know how to do this.
My prof then said that the crux was that the task said onto, if it would have said into you could have just used the identity map. I can't get my head around this statement.
I mean $id(AB)=id(A)id(B)=AB$ with $A,B \in U(n)$ is obviously not in $SO(2)$, is it?

A: No, that is not a map from $SU(n)$ into $SO(2,\mathbb R)$. What your teacher meant was the map $M\mapsto e_{SO(2,\mathbb R)}$.
But consider the map $\det\colon U(n)\longrightarrow\mathbb C\setminus\{0\}$, and the map$$\begin{array}{rccc}\psi\colon&\mathbb C\setminus\{0\}&\longrightarrow&GL(2,\mathbb R)\\&a+bi&\mapsto&\begin{bmatrix}a&-b\\b&a\end{bmatrix}.\end{array}$$Then $\psi\circ\det$ is a group homomorphism and its image is precisely $SO(2,\mathbb R)$, since\begin{align}\det\bigl(U(n)\bigr)&=\{z\in\mathbb C\mid\lvert z\rvert=1\}\\&=\bigl\{\cos(\theta)+i\sin(\theta)\mid\theta\in\mathbb R\bigr\}.\end{align}


text:
Q: Where should I place the process that don't have relation to UI In case I want to load data to display to UI (e.g.Timeline of Twitter), I place the process of API call to viewDidLoad.
however, I couldn't find the place similar to viewDidLoad in Apple Tutorials.
Where should I place the process that don't have relation to UI?

A: SwiftUI gives us same to UIKit's viewDidAppear() and viewDidDisappear() methods but their name is little bit different which are onAppear() and onDisappear().
struct DetailView : View {
    var body: some View {
        NavigationView {
            Text("Hello World")
            }.onAppear {
// enter viewDidAppear() code here
        }
    }
}


text:
Q: Upload Image From iPhone to WCF Service I'm trying to build an iPhone app and c# WCF Service to upload an image to a SQL Service database.
I've got my app breaking an image down to NSData and posting off to a WCF Service using the following code:
NSData *imageData = UIImageJPEGRepresentation(self.image, 90);

NSURL *url = [NSURL URLWithString:@"http://example.com/ImageDiaryService.svc/json/AddMediaItem"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Test" forKey:@"Name"];
[request setPostValue:@"Test description." forKey:@"Description"];
[request setPostValue:@"JPEG" forKey:@"ImageType"];
[request setPostValue:@"iPhone" forKey:@"MediaType"];

[request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"ImageData"];

[request setDidFinishSelector:@selector(uploadFinished:)];
[request setDidFailSelector:@selector(uploadFailed:)];
[request setDelegate:self];
[request startAsynchronous];

The problem I'm having is with the web service. I'm not sure what type of data I should be receiving from the app POST. I've tried receiving it as an a byte array but that didn't working.
My WCF Service is a REST service.
Any help is much appreciated.

A: Try receiving it as a Stream. The blog post at http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx shows how to receive arbitrary data in a WCF REST service.


text:
Q: How much affinity does the Doctor have for Gallifrey? How much affinity does the Doctor have towards Gallifrey and its inhabitants?
I'm a little bit confused as I started watching the show in 2005 with the Eccleston era. Here is the information I have:
SPOILERS ! (duh)

*

*Season 1: "Don't you think I want to go back and save them?"
Apparently the Doctor is missing Gallifrey and he feels alone as the unique member of his species.

*Season 4, The End of Time: "They must not come back, they will bring back the Nightmare Child"
Ok now this is weird: Gallifrey is now a threat?! Sure, appearing near Earth is a threat anyway but the Doctor seems to mention a lot of elements about the Time Lords themselves.

*Season 8, Death in Heaven: Missy gives the Doctor coordinates to go to Gallifrey.
We can see the Doctor going to Missy's coordinates, seeing nothing and slamming his fists on the TARDIS commands. Anger? Deception?

*Season 9, Hell Bent: The Doctor arrives at Gallifrey... and stays in a peasant's house while military and high council members come to greet him.
We see later in the episode that he is troubled by the death of Clara and wants to save her, therefore triggering the prophecy about "Me" destroying Gallifrey.
So what is the purpose of the Doctor trying to reach Gallifrey?

A: In short — the Doctor likes Gallifrey, and most of its people. But he doesn't like the Time Lords so much, for various reasons.

Taking your points one-by-one (and, as you rightly say, SPOILERS):

*

*Season 1: "Don't you think I want to go back and save them?"
In the Time War, the Doctor was forced to end the conflict by destroying both sides (the Daleks and Gallifrey) to save the rest of the universe. Ideally, he'd like to have not destroyed his entire planet.

*Season 4, The End of Time: "They must not come back, they will bring back the Nightmare Child"
The Time Lords, led by Rassilon, are a threat. Their solution to the Time War was to end time, destroying the rest of the universe to save themselves. They're now trying to implement that solution. The Doctor is not down with that.

*Season 7, The Day of the Doctor (you missed this bit)
All thirteen Doctors manage to go back to the Time War and end it without destroying Gallifrey. At the end of the episode, it's established that Gallifrey and the Time Lords on it are somehow locatable in our universe again.

*Season 7, The Time of the Doctor (this bit too)
The Time Lords are discovered, whispering through a wee gap between universes at Trenzalore, asking the Doctor to confirm that it's safe for them to return. It's not, because all the universe's bad guys have come to Trenzalore to destroy the Time Lords if they return.
The Doctor nearly dies forever defending Trenzalore from the bad guys, but Clara convinces the Time Lords to send him a new set of regenerations, and he uses some of that regeneration energy to repel all of the bad guys and thus end the conflict.

*Season 8, Death in Heaven: Missy gives the Doctor coordinates to go to Gallifrey.
Yup. She claims that Gallifrey did return to our universe after Trenzalore, and tells the Doctor where/when. Unfortunately, it seems that she was lying, as there's nothing at those co-ordinates. The Doctor is sad, because, y'know, he still misses his people.

*Season 9, Hell Bent: The Doctor arrives at Gallifrey... and stays in a peasant's house while military and high council members come to greet him.
Yup. Turns out Gallifrey hid itself at the end of time. The Doctor likes Gallifrey, and its people. As we saw in Season 8, Listen, the peasant's house appears to be where he grew up before he became a Time Lord.
But he doesn't like the Time Lords, because of their tendency to be a bit militaristic and not care much about the rest of the universe — and probably I guess also because they just locked him in a Confession Dial for billions of years to try to force him to reveal what The Hybrid is. That's how he finally got back to Gallifrey.

A: Regarding The End of Time: Gallifrey coming back would break the time-lock, and the Time War would start again.
But Gallifrey is his home, so when there is a way to save them without kick-starting a new war (The Day of the Doctor ) he does it.
 Then again he refuses to answer the question on Trenzalore for fear of another war.
So to answer your question, he wants to reach/save Gallifrey given that his doing so doesn't bring on another war.


text:
Q: How to overlay two image figures plotly (python) I'm trying to overlay an mask on an image in plotly. I'm trying to do this as you would with two scatter plots for instance, but the error says that the data property is wrong when adding the figure to the trace.
rgb_pad_removed, thermal_img = get_thermal_and_rgb(img_path)

img, mask = get_masked_image(rgb_pad_removed)

thermal_img_resized = cv2.resize(thermal_img, dsize=(mask.shape[1], mask.shape[0]), interpolation=cv2.INTER_CUBIC)

from plotly.subplots import make_subplots
f1 = px.imshow(rgb_pad_removed)
f2 = px.imshow(mask)

fig = make_subplots()
fig.add_trace(f1)
fig.add_trace(f2)

fig.show()

With the following error:
ValueError:
    Invalid element(s) received for the 'data' property of
        Invalid elements include: [Figure({
        ect...

Am I using the correct method or is there a better one?

A: Here the problem is, you are adding the figure as a trace. add_trace supports only a trace object. Trace is basically Scatter or Bar. You have added a figure as a trace. That is the error here.
To mask an image, this is what you can do.
Get your image and add the mask from opencv and show the image. I have added an example. Please check it.
import numpy as np
import plotly.express as px

img_rgb = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]],
                    [[0, 255, 0], [0, 0, 255], [255, 0, 0]]
                    ], dtype=np.uint8)

mask = np.array([[0, 1, 0],
                 [0, 1, 0]], dtype=np.uint8)

result = cv2.bitwise_and(img_rgb, img_rgb2, mask=mask)
f1 = px.imshow(result)

f1.show()


text:
Q: Apache Camel: GET service call using toD() results in infinite loop I want to read file(s) from a location, extract the fileName & make a rest call (GET) with the fileName as a request parameter. The file name is required to be passed dynamically as each file will be unique. I used toD() after going through the tutorials. The high level pseudo code is provided below (I am just interested with the status code from this call. There's further operations required after this.).
The issue I am facing now using toD() is that it is running into an infinite loop after making the Get service call.
How can this issue be handled? Appreciate your suggestions!
from("file:C:/inbound?delete=true&noop=true")
    .process(new Processor() {
        public void process(Exchange exchange) throws Exception {
            String fileName = exchange.getIn().getHeader("CamelFileName").toString();
            exchange.getIn().setHeader("fileName", fileName);
        }
    })
    .setHeader(Exchange.HTTP_METHOD, simple("GET"))
    .toD("http://localhost:8090/fileWatcher?fileName=${header.fileName}")

Here's a simple Get endpoint mockup running on port 8090:
@RequestMapping(value = "/fileWatcher", method = RequestMethod.GET)
public ResponseEntity<FileDetails> firstService(@RequestParam String fileName) {
    return new ResponseEntity<>(HttpStatus.OK);
}


text:
Q: Aside from level recommendations, when should I start the DLC? I'm currently replaying Witcher 3. I've done one playthrough before, but haven't played either of the expansion packs before. I was wondering just how 'absolute' the recommendations are (level 30+ each) . Right now I've confirmed Ciri is in neither of the 3 areas and am at level 20+
I've read that the expansion packs give you certain bonuses, like Gwent cards and mutagens or something, so I'd like to get the most out of those. I also wouldn't mind experiencing something fresh and new, rather than most quests I've already been through once.
So, my question is at what point in the story or at what level should I start which DLC? Spoilers for the main story  are fine, but please don't mention anything of HoS or BaW.

A: I think the required levels are fairly accurate. Especially for Blood and Wine you will run in to a lot of high level adversaries immediately even before you get to the new area.
I have recently got to this level playing at Death March difficultly. I started Blood and Wine while the main quest 'Final Preparations' was active and I was at around level 34.
If you play much of Blood and Wine you will end up very over leveled for the main story.
Since Hearts of Stone just extends the area of the Velen/Novigrad map you can reach the main merchant and craftsman there without necessarily engaging with high level adversaries. However they won't sell you the really good stuff until you have done some quests. The runewright also requires you to spend quite a lot of crowns (5000 for just the first level). You can buy some Gwent cards and good saddlebags from the merchant, and win a good saddle in a race.