text:
Q: after i config the vs and dr, it worked in default ns, but other ns doesn't worked
*

*What am i trying to achieve

i am trying to access flow dyeing

*what am i expecting to get out

when i visit the testaaa with header, then route to testaaa-<header-branch>, and it will pass the header route to the testbbb-<header-branch>, use curl "http://gateway:gatewayport/" --header 'project-version: release-v1', i hope it can return release-v1

*What did i get out (include error messages)

no error, but it did not work, i get the response of the poll of these pods what i deployed

*What else have you tried?

i have tried to move the server to default ns, it worked

*What do i think is causing it?

maybe my yaml is wrong, i think
this is my configuration yaml
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: gateway
  namespace: test-istio
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 80
        name: http
        protocol: HTTP
      hosts:
        - "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: testaaa
  namespace: test-istio
spec:
  gateways:
    - gateway
  hosts:
    - "*"
  http:
    - match:
        - headers:
            project-version:
              exact: release-v1
      route:
        - destination:
            host: testaaa.test-istio.svc.cluster.local
            subset: release-v1
    - route:
        - destination:
            host: testaaa.test-istio.svc.cluster.local
            subset: release
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: testaaa
  namespace: test-istio
spec:
  host: testaaa.test-istio.svc.cluster.local
  subsets:
    - labels:
        version: release
      name: release
    - labels:
        version: release-v1
      name: release-v1
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: testbbb
  namespace: test-istio
spec:
  hosts:
    - testbbb.test-istio.svc.cluster.local
  http:
    - match:
        - headers:
            project-version:
              exact: release-v1
      route:
        - destination:
            host: testbbb.test-istio.svc.cluster.local
            subset: release-v1
    - route:
        - destination:
            host: testbbb.test-istio.svc.cluster.local
            subset: release
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: testbbb
  namespace: test-istio
spec:
  host: testbbb.test-istio.svc.cluster.local
  subsets:
    - labels:
        version: release
      name: release
    - labels:
        version: release-v1
      name: release-v1
---

*after i use curl, i got this

[root@k3s-release-server1 ~]# curl  "http://10.1.4.5:31380/" --header 'project-version: release-v1'
release-v1[root@k3s-release-server1 ~]# curl  "http://10.1.4.5:31380/" --header 'project-version: release-v1'
release[root@k3s-release-server1 ~]# curl  "http://10.1.4.5:31380/" --header 'project-version: release-v1'
release[root@k3s-release-server1 ~]# curl  "http://10.1.4.5:31380/" --header 'project-version: release-v1'
release-v1[root@k3s-release-server1 ~]# curl  "http://10.1.4.5:31380/" --header 'project-version: release-v1'
release[root@k3s-release-server1 ~]# curl  "http://10.1.4.5:31380/" --header 'project-version: release-v1'
release-v1[root@k3s-release-server1 ~]# curl  "http://10.1.4.5:31380/" --header 'project-version: release-v1'
release

maybe it return release-v1, maybe release, [plus: this result is label of testbbb server]

A: my fault
i forgot to enable the istio inject, and service needs to add a protocol,
so my yaml change to this
apiVersion: v1
kind: Service
...
spec:
  selector:
   ...
  ports:
      ...
      appProtocol: HTTP
---
apiVersion: apps/v1
kind: Deployment
metadata:
   ...
spec:
   ...
  template:
    metadata:
      annotations:
        sidecar.istio.io/inject: 'true'

then use this config to test, it worked
[root@k3s-release-server1 ~]# curl "http://<ingressgateway>/" --header 'project-version: release-v1' -w '\n'
release-v1
[root@k3s-release-server1 ~]# curl "http://<ingressgateway>/" --header 'project-version: release' -w '\n'
release
[root@k3s-release-server1 ~]# curl "http://<ingressgateway>/" --header 'project-version: release-v3' -w '\n'
release
[root@k3s-release-server1 ~]#


text:
Q: How do I fix 'too many close_wait connections are created' even though the connections have been closed? The problem recently began on a server, there were too many sockets in close_wait state on the server, After increasing the server configuration the problem goes away, but the previous configurations are enough for the server. What might be the problem. The server is running on ubuntu 16.04.

A: The Problem is solved now, There was a bug in other part of the software which was consuming more CPU, thus eating up all the resources and not giving the server the resources to close the connections.

redpajama_set_name: RedPajamaStackExchange


text:
Q: npm failing to encode %5C I am trying to connect to npm from behind a proxy that uses a domain. I am trying to implement the solution from this question.
npm config set proxy "http://domain%5Cusername:password@servername:port/"

However, when I try this, it ends up turning the string into:
http://domain/%5Cusername:password@servername:port/

Note the "/" between "domain" and "%5C", which it doesn't encode.
I have tried this in both Git Bash and Windows Command-line. I've tried it with and without the quotations. Same result.
Why isn't npm, or whoever, encoding %5C properly?


text:
Q: Recordset: blank for string records? I have 2 excel workbooks and I am pulling data (A1:A20)from one (WB1) to another using below macro. I have problem that only records with numbers are pulled while string records are not. It seems that the field type is considered as a number and only numbers are being pulled. what should I change in the code to solve it?
below link includes the source file:
https://drive.google.com/open?id=0B64seB8-qtdLYk80N3hvX2F6VGc
Private Source As Variant

Sub Copy_Paste()
'copy the data from the source
Source = ThisWorkbook.Path & "\WB1.xlsx"
GetData Source, "Sheet1", "A1:A20", Sheets("Database").Range("A1")
End Sub

Public Sub GetData(Source As Variant, SourceSheet As String, SourceRange As String, TargetRange As Range)
Dim rsCon As Object
Dim rsData As Object
Dim szSQL As String
Dim szConnect As String
'Create the connection string based on excel version
    If Val(Application.Version) < 12 Then
        szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                    "Data Source=" & Source & ";" & _
                    "Extended Properties=""Excel 8.0;HDR=No"";"
    Else
        szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                    "Data Source=" & Source & ";" & _
                    "Extended Properties=""Excel 12.0;HDR=No"";"
    End If
szSQL = "SELECT * FROM [" & SourceSheet$ & "$" & SourceRange$ & "];"

On Error GoTo SomethingWrong
Set rsCon = CreateObject("ADODB.Connection")
Set rsData = CreateObject("ADODB.Recordset")
rsCon.Open szConnect
rsData.Open szSQL, rsCon, 0, 1, 1
' Check to make sure we received data and copy the data
If Not rsData.EOF Then
    TargetRange.Cells(1, 1).CopyFromRecordset rsData
Else
    MsgBox "No records returned from : " & Source, vbCritical
End If
' Clean up our Recordset object.
rsData.Close
Set rsData = Nothing
rsCon.Close
Set rsCon = Nothing
Exit Sub
SomethingWrong:
    MsgBox "The file name, Sheet name is invalid of : " & Source, vbExclamation, "Error"
On Error GoTo 0
End Sub

A: See here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/ce095b10-84a4-4ae3-8944-70a2b53daa44/mixed-data-types-in-excel-column-to-oedb-destination?forum=sqlintegrationservices
You need to add IMEX=1 to your connection strings.  Eg:
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                "Data Source=" & Source & ";" & _
                "Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"

Otherwise, the driver guesses your data column is numeric (based on the first few rows) and ignores any non-numeric values.


text:
Q: Tensorflow TabTransformer model get weights before training I am working with the Tensorflow Tabtransformer custom model and I am trying to get the initial weights after declaration using model.get_weights() but I get the following error:
from tabtransformertf.models.tabtransformer import TabTransformer
from tabtransformertf.utils.preprocessing import df_to_dataset, build_categorical_prep

numeric_features = ['TotPkts', 'TotBytes', 'Seq', 'Dur', 'Mean', 'StdDev', 'Sum', 'Min',
       'Max', 'SrcBytes', 'DstBytes', 'Rate', 'SrcRate',
       'DstRate']

cat_features = ['SrcPkts', 'DstPkts']
TARGET_FEATURE_NAME = "Category"

category_prep_layers = build_categorical_prep(tab_df, cat_features) #tab_df is the dataframe I am working on

model = TabTransformer(
        numerical_features = numeric_features,
        categorical_features = cat_features,
        categorical_lookup=category_prep_layers,
        numerical_discretisers=None, # simply passing the numeric features
        embedding_dim=32,
        out_dim=1,
        out_activation='sigmoid',
        depth=6,
        heads=5,
        attn_dropout=0.087687,
        ff_dropout=0.429539,
        mlp_hidden_factors=[1, 1],
        use_column_embedding=False,
    )

model.get_weights()

ValueError: Weights for model sequential have not yet been created. Weights are created when the Model is first called on inputs or `build()` is called with an `input_shape`.


text:
Q: Programmatically set the Background color of a Drawable in Android? I have an image in a resource file.
Drawable draw = getResources().getDrawable(R.drawable.my_icon);

The image has a transparent background.
Is there a way to programmatically set the background color to the Drawable before using the end product further in my code?

A: I think Drawing with PorterduffXferMode may help you in your case. This way you can merge two images (your image and a overlay completly in your color you want to replace the transparent pixels with) in many different ways.
Different porterduff modes explaned:
http://www.ibm.com/developerworks/java/library/j-mer0918/
Android example:
http://www.vogella.com/code/ApiDemos/src/com/example/android/apis/graphics/Xfermodes.html
This way you draw the result inside a new Bitmap. (SRC_OVER should work in your case if your image is the src and the background is used as the dst)

A: setColorFilter() with Porterduff SRC will break the transparent of drawable.
I used this in my code, and it work
disabledIcon = ContextCompat.getDrawable(getContext(), resId);
disabledIcon = DrawableCompat.wrap(disabledIcon);
disabledIcon.mutate(); // to not share its state with any other drawable
DrawableCompat.setTint(disabledIcon, ContextCompat.getColor(getContext(), R.color.button_text_disabled));


text:
Q: Windows updates fail to install on XP SP3 with error 0x8007001F I have an XP SP3 workstation where windows update seems to have stopped working properly.
Going to "update history" in windows update shows that the error is:
Installation Failure

Error Code: 0x8007001F

I have run malwarebytes and Microsoft Security Essentials scans, which have come up clean.
I attempted to use microsoft's "fix it" tool for windows update, but that didn't appear to do anything (the "loading" progress bar was displayed, then it disappeared). I also tried the manual reset instructions, but that was unsuccessful as well.
Any other suggestions?

A: The key here is the error code.

error: 0x8007001f, A device is not functioning

MS has a specific fix for this error in how it relates to a video capture card.  Just pointing out how that error code is not specific and limited to just your issue.
Either this was you, or someone else had this SAME problem, and posted about it Yesterday at Microsoft's Answers site.  They got advice, but there is no confirmation that the advice worked.  So, you might not be alone in this issue.
Here is a long thread about someone who lost sound AND had your issue.. and there is some very detailed repair work that is suggested
Here is someone who is getting this error when they installed a program and tried to use System Restore.
Someone else reports that error with a server installation, when attempting to save specific data.
... and here's a thread about someone with that error code, and a video capture system...
What's my point in mentioning all of that?  If they have anything in common, it seems to be related to writing data to a hard drive.  No, I'm not saying that your drive is failing, but the error of

error: 0x8007001f, A device is not functioning

seems to point to a device not functioning... or at least, not functioning as it is supposed to for a short amount of time.  Whether it is due to an infection, or a drive not being able to write information, or a video capture card hiccuping 1 time out of 10, no one seems to be able to determine yet.
You say this is a workstation.  Can you take it out of service long enough for a full Chkdsk, including a surface scan?  Not that this would take days... just an hour or so... but you really should try to determine or eliminate the drive as a suspect here.
As a side note, how long has this problem been going on? What happened with the computer before this problem started?
In the end, there is no single fix for that error, because there is apparently no single cause of it.  And yes, it might end up that reinstalling XP becomes a viable solution.  Just not the first one or next one.

A: I installed windows Xp Pro Sp3 and when i started to update windows i got same errors and windows was not updating at all despite many methods i used but here is one method i used and i was able to install windows updates. follow these steps (Time consuming but it will work)

*

*install a fresh copy of windows xp pro sp3 and install system drivers especially Network to connect to internet.

*download IE 8 and install it. (Reboot)

*download .Net framework 3.5 or greater install it(i used 3.5). (Reboot)

*download shockwave, flash player, install it. (Reboot)

*download MicrosoftFixit.wu.LB.148304778149291574.1.1.Run install,follow instructions when done then reboot.

*now click on start menu, click on windows update. (in my case when i clicked on windows update and it started to scan then it took more then 1 hour and i didn't touch anything else but left the pc alone to do its work) make sure you are connected to internet.

i hope this will help as i used the same method to get the windows updates.

A: MS has a fix for it:
You cannot install updates from Windows Update, Microsoft Update, or by using Automatic Update after a repair install of Windows XP or after you install Windows XP SP3 immediately after a clean install of Windows XP SP2
here is a link (just in case): http://support.microsoft.com/kb/943144

A: I ended up reformatting and installing a fresh operating system.


text:
Q: Check if Shiny app works correctly I started to work with shiny. I wonder what a simple way is to reproduce the outcome which is not visualized and displayed in the app. Meaning, the stuff which runs in the background. Something like print when writing and debugging a little script.
So, I assigned a variable test <- as.integer(1) in the server.R file. When I open the console in Firefox and I want to print out my variable test it says its not defined. Am I doing something wrong with checking weather the variable is assigned or did I do something wrong during the assigning process?!

A: No, not something like this
 test <- reactive({
      input$bounds
      print(bounds)
  })

Rather something like:
 test <- reactive ({
       print(input$bounds)
 )}

or
 test <- reactive ({
      input$bounds
 )}
 observe ({
      print(test())
 )}


text:
Q: Laravel pass value to model Right now I try this query with eloquent:
'MentorId'  => $employee->intern(true)->mentor(true)->MentorId,

And in my employee and intern model I've got this:
Intern
  /**
     * @return mixed
     */
    public function intern($withTrashed = false)
    {
        if($withTrashed == true)
        {
            return $this->belongsTo(internModel::class, 'InternId')->withTrashed();
        }

        return $this->belongsTo(internModel::class,'InternId');
    }

Mentor
 /**
     * @return mixed
     */
    public function mentor($withTrashed = false)
    {
        if($withTrashed == true)
        {
            return $this->belongsTo(mentorModel::class, 'MentorId')->withTrashed();
        }

        return $this->belongsTo(mentorModel::class,'MentorId');
    }

But it crashes:
BadMethodCallException in Builder.php line 2148:
Call to undefined method Illuminate\Database\Query\Builder::mentor()

How could I fix this?
--EDIT--
Employee
<?php

namespace App\src\employee;

use Illuminate\Foundation\Auth\User as Authenticatable;
use App\src\department\Department as departmentModel;
use App\src\employee\Employee as employeeModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\src\intern\Intern as internModel;
use App\src\mentor\Mentor as mentorModel;
use App\src\employee\Role as roleModel;

class Employee extends Authenticatable
{
    use SoftDeletes;
    use EmployeeServiceTrait;

    /**
     * table name
     */
    protected $table = 'employee';

    /**
     * Mass assignment fields
     */
    protected $fillable = ['RoleId', 'DepartmentId', 'InternId', 'FirstName', 'LastName', 'Bio','api_token', 'email', 'LinkedIn', 'password', 'Address', 'Zip', 'City', 'ProfilePicture', 'BirthDate', 'StartDate', 'EndDate', 'Suspended','LinkedIn'];

    /**
     * Primarykey
     */
    protected $primaryKey = 'EmployeeId';

    /**
     * Deleted_at
     */
    protected $dates = ['deleted_at'];

    /**
     * @return mixed
     */
    public function role()
    {
        return $this->belongsTo(roleModel::class,'RoleId');
    }

    /**
     * @return mixed
     */
    public function intern($withTrashed = false)
    {
        if($withTrashed == true)
        {
            return $this->belongsTo(internModel::class, 'InternId')->withTrashed();
        }

        return $this->belongsTo(internModel::class,'InternId');
    }

    /**
     * @return mixed
     */
    public function department()
    {
        return $this->belongsTo(departmentModel::class,'DepartmentId');
    }

    /**
     * @return mixed
     */
    public function mentor()
    {
        return $this->belongsTo(mentorModel::class,'MentorId');
    }

    /**
     * @return mixed
     */
    public function employees()
    {
        return $this->hasManyThrough(employeeModel::class,departmentModel::class,'CompanyId','DepartmentId');
    }

    /**
     * @param $role
     * @return bool
     */
    public function hasRole($role)
    {
        if(strtolower($this->role->RoleName) == strtolower($role))
        {
            return true;
        }
        return false;
    }
}

A: Try as below as per laravel guide. Keep in mind that parent model must have hasOne/hasMany method and child model must have belongsTo method.
Intern
/**
 * @return mixed
 */
public function intern($withTrashed = false)
{
    if($withTrashed == true)
    {
        return $this->hasOne('App\Intern', 'InternId')->withTrashed();
    }

    return $this->hasOne('App\Intern','InternId');
}

Employee
/**
 * @return mixed
 */
public function intern($withTrashed = false)
{
    if($withTrashed == true)
    {
        return $this->belongsTo('App\Intern', 'InternId')->withTrashed();
    }

    return $this->belongsTo('App\Intern','InternId');
}

Note: Same for all other models.

A: The problem you have is that any Eloquent relationship object is actually an instance of Relation.  This means when you create relationships you actually return a collection (instance of Builder); Hense your error:

BadMethodCallException in Builder.php line 2148:
  Call to undefined method Illuminate\Database\Query\Builder::mentor()

The simple solution, without any modification to your code would be something like:
'MentorId'  => $employee->intern(true)->first()->mentor(true)->first()->MentorId;

However, you could use overloading like the following:
'MentorId'  => $employee->intern->mentor->MentorId;

Although this will NOT include your withTrashed.  You can however tweak your relationship to something like:
public function intern($withTrashed = false)
{
    $relation = $this->belongsTo(internModel::class, 'InternId');

    if($withTrashed == true)
    {
        return $relation->withTrashed()->first();
    }

    return $relation->first();
}

But I wouldn't advise this because later on if you try using things like WhereHas you will get errors.  That said, another way would be to do something along the following lines:
public function intern()
{
    return $this->belongsTo(internModel::class, 'InternId');
}

Then get trashed like:
'MentorId' => $employee->intern()->withTrashed()->first()->mentor()->withTrashed()->first()->MentorId;


text:
Q: Filtering a object with query that contains reference to nested object I need to write a filter function that will allow me to query by nested object, like this:
var data = [
             { twitter: { id: 1, name: "Bob" } },
             { twitter: { id: 2, name: "Jones" } }
           ],
    query = { 'twitter.id': 1 };

# Perform filter using data and query variables
var search = …

console.log(search);
> ["0"]

The filter should return an array of indexes that match the query.
I currently have this working without nested object support at http://jsbin.com/umeros/2/edit.
However, I would like to be able to query for nested objects, such as the query seen above.

A: Using the function ref from this answer, your filter should look like this:
var search = _.filter(_.keys(data), function (key) {
    var obj = data[key];
    return _.every(query, function (val, queryKey) {
        return ref(obj, queryKey) === val;
    });
});


text:
Q: Best way to add pandas DataFrame column to row I have to find the best way to create a new Dataframe using existing DataFrame.
Look at this link to have full code : jdoodle.com/a/xKP
I have this kind of DataFrame :
df = pd.DataFrame({'length': [112, 214, 52,88], 'views': [10000, 50000, 25000,5000], 'click': [55, 64, 85,9]},
     index = ['id1', 'id2', 'id3','id4'])

     click  length  views
id1     55     112  10000
id2     64     214  50000
id3     85      52  25000
id4      9      88   5000

And need to have this result :
    type_stat   stat
id1     click     55
id2     click     64
id3     click     85
id4     click      9
id1    length    112
id2    length    214
id3    length     52
id4    length     88
id1     views  10000
id2     views  50000
id3     views  25000
id4     views   5000

Currently, I create a function who return DataFrame with one stat :
def df_by_stat(current_df,stat):
    current_df['type_stat'] = stat
    current_df['stat'] = current_df[stat].astype(int)

    return current_df[['type_stat','stat']]

After I make an .append with the function like this :
def final():
    return df_by_stat(df,'click').append(
    df_by_stat(df,'length')).append(
    df_by_stat(df,'views'))

print(final())

This way is working but its complexity depends on rows and columns cardinalities witch is too expensive.
That's why I need your help to find a best method.

A: Using pandas.melt after elevating your index to a series:
res = pd.melt(df.assign(index=df.index), id_vars='index',
              value_name='stat', var_name='type_stat')\
        .set_index('index')

print(res)

      type_stat   stat
index
id1       click     55
id2       click     64
id3       click     85
id4       click      9
id1      length    112
id2      length    214
id3      length     52
id4      length     88
id1       views  10000
id2       views  50000
id3       views  25000
id4       views   5000


text:
Q: How to scroll down a specific div of page having pagination using selenium webdriver I am trying to scroll down page and get the last element of that section/div.
i have executed the code:

Coordinates coordinate = ((Locatable)element).getCoordinates();
    coordinate.inViewPort();

and also tried with
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(0, 250)");

But it is scrolling the entire page instead of scrolling the specific section

And also the page has pagination

A: First you need to find the element you're trying to scroll to:
WebElement element = driver.findElement(By.xpath("xpath_here")); //or anything else used to identify the element

Afterwards, you can execute JS using JavascriptExecutor to bring the element into view using scrollIntoView() :
((JavaScriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);

A: What you have tried will scroll the window scroll bar, try something like below
JavascriptExecutor je = (JavascriptExecutor) dr;
je.executeScript("arguments[0].scrollIntoView(true);",dr.findElement(By...));

Specify the locator of the element which you are trying to find by scrolling down.
arguments[0]
Edit:
JavascriptExecutor je = (JavascriptExecutor) dr;
je.executeScript("arguments[0].scrollTop(arguments[0].scrollHeight);",dr.findElement(By...));


text:
Q: Create synchronizedList from within spring xml file The collection framework has Synchronization Wrappers that help create synchronized lists.
List list = Collections.synchronizedList(new ArrayList());

I am trying to create the list from the spring xml file. Following works fine for a simple List.
<bean id="listt" class="java.util.ArrayList"/>

Is there anyway i can directly create a synchronizedList from within the xml file?

A: You can construct using Collections.synchronizedList as a static factory method:
<bean id="list" class="java.util.Collections" factory-method="synchronizedList">
  <constructor-arg><bean class="java.util.ArrayList"/></constructor-arg>
</bean>


text:
Q: I Can not Show the selected value(Titles Not Ids) in this multiple List by javaScript Or jquery View:
TempData["LabelId"] = Json.Encode(item.LabelId);
@Html.ListBox("LabelId", new SelectList(calllabel, "Id", "text"), new {@class = "form-control select2 required", @multiple = true})

Init variable for load the selected value For Editing
var callItem = new
{
  // ...
  LabelId = item.LabelId.HasValue() ? item.LabelId.Split(',').Select(int.Parse) : new int[]{},
  // ...
};

Edit Button:
Edit

jQuery:
$("#LabelId").val(jsdata.LabelId);
jsdata.LabelId.forEach(function(valToSelect) {
  $('select#LabelId').find('option[value="' + valToSelect + '"]').prop('selected', true);
});
$("#select2-LabelId-container").html(jsdata.LabelId);


text:
Q: Changing every operator in a document I'm writing notes on vector calculus and have been using the \curl and \div operators from the physics package. Only after a while did I realise that \curl uses the bold-face version of \nabla rather than just \nabla.
Initially, I wanted to make all the bold-face nablas the same as the standard nablas, and managed to do that with this (from this post):
\DeclareDocumentCommand\vnabla{}{\nabla}
However, I think I actually like the bold-face version better and want to change all the existing nablas in the document to bold-face, preferably by redefining \nabla to produce the bold-face version (rather than manually searching for every single nabla in the document).
How would I do this? Sorry if this question is elementary. Any advice would be appreciated.

A: The \nabla command is defined as a character, using \mathchardef so to redefine it as a macro you need to create a new version of it that can be made bold in the same way that the physics package defines the \vnabla macro.
\documentclass{article}
\usepackage{physics}
\mathchardef\NABLA"272
\newcommand*{\Nabla}{\boldsymbol\NABLA}
\let\nabla\Nabla
\begin{document}
\[ \nabla(\frac{a}{b}) \]
\[ \grad(\frac{a}{b}) \]
\end{document}

A: You want to keep the standard \nabla somewhere and redefine the command, in order to avoid an infinite loop.
\documentclass{article}
\usepackage{amsmath,bm}

\AtBeginDocument{%
  \NewCommandCopy{\nablasymbol}{\nabla}%
  \DeclareRobustCommand{\nabla}{\bm{\nablasymbol}}%
}

\begin{document}

$\nabla$ (compare with $\nablasymbol$)

\end{document}

Note that you need to know nothing about how \nabla is defined to begin with. Also, \AtBeginDocument might be necessary if you use one of the math font packages that delay definitions at begin document; it doesn't harm doing it anyway.
If you're using unicode-math, the method is similar.
\documentclass{article}
\usepackage{amsmath}
\usepackage{unicode-math}

\AtBeginDocument{%
  \NewCommandCopy{\nablasymbol}{\nabla}%
  \DeclareRobustCommand{\nabla}{\symbf{\nablasymbol}}%
}

\begin{document}

$\nabla$ (compare with $\nablasymbol$)

\end{document}

Here \AtBeginDocument is certainly needed, because unicode-math does much of its job at that moment and we must delay the redefinition after that job.

A: If you are using Unicode math then all variants of nabla are ready in single font. Looking to unicode-math-table.tex we get:
\UnicodeMathSymbol{"02207}{\nabla          }{\mathalpha}{nabla, del, hamilton operator}%
\UnicodeMathSymbol{"1D6C1}{\mbfnabla       }{\mathalpha}{mathematical bold nabla}%
\UnicodeMathSymbol{"1D6FB}{\mitnabla       }{\mathalpha}{mathematical italic nabla}%
\UnicodeMathSymbol{"1D735}{\mbfitnabla     }{\mathalpha}{mathematical bold italic nabla}%
\UnicodeMathSymbol{"1D76F}{\mbfsansnabla   }{\mathalpha}{mathematical sans-serif bold nabla}%
\UnicodeMathSymbol{"1D7A9}{\mbfitsansnabla }{\mathalpha}{mathematical sans-serif bold italic nabla}%

So, if you want to use bold variant of nabla, you can set
\let\nabla=\mbfnabla

That is all. More things are simpler with Unicode math.

A: The \curl command is basically \vnabla with additional conditional formatting.
The package has the following definition:
\DeclareOption{bolddel}{\DeclareDocumentCommand\vnabla{}{\boldsymbol\nabla}}

So what you basically did is remove the \boldsymbol formatting command that enters the definition of the \curl command, via the \vnabla command.
Now, if you want all the "nablas" bold, I would suggest something along those lines:
\let\nablacopy\nabla
\newcommand{\boldnabla}{\boldsymbol{\nablacopy}}
\let\nabla\boldnabla

You could look into the package, it is always interesting.


text:
Q: implement Single page architecture using javascript for my website where i need to start? I want to implement Single page architecture using javascript for my website where i need to start?
window.onload= function ()
{

    var x=  hometemplate.home.statictemplateHome();
    document.getElementById("container").innerHTML = "";
    document.getElementById("container").innerHTML = x;

}

A: AngularJS is a popular web framework supporting SPA and
it has a simple tutorial you can follow by yourself
https://docs.angularjs.org/tutorial/step_00

BTW welcome to Stack Overflow, please read https://stackoverflow.com/help/how-to-ask


text:
Q: FileNotFoundError: [Errno 2] No such file or directory when trying to use local package Let's consider this directory structure:
package/
    rooster.py
    files/
        rooster.txt
app/
    main.py

and the content of the two Python files:
rooster.py:
def roost():
    file = open('files/rooster.txt')
    return file.read()

main.py:
from package.rooster import roost
print(roost())

Running main.py returns an error:
FileNotFoundError: [Errno 2] No such file or directory: 'files/rooster.txt'

That obviously happens because the working directory is app/ and there's no app/files/rooster.txt file. Thus the error. What solution does Python provide for such a scenario?

A: Maybe you can use the full path of the file, this should work, if it is always the same

A: Solution:
I am not sure if I understood the issue correctly, but this code might solve your issue.
rooster.py
def roost(path):
    import os
    file = open(os.path.join(path, 'files/rooster.txt'))
    return file.read()

main.py
import os
from pathlib import Path
from rooster import roost

p = Path(__file__).parents[1]
package_dir = os.path.join(p, 'package')
print(roost(package_dir))

OUTPUT:
Hello World1
Hello World2
Hello World3

Directory Structure:
testCode/
    package/
        rooster.py
        files/
            rooster.txt
    app/
        main.py

Let me know in case there is any issue.


text:
Q: How to know when a listitem in a listview is focused(highlighted) in Android? I searched a lot but I couldn't find a straight way for that. All I need is when I clicked on a menu-item I can realize that which on of items in the list is focused?
For example in the blow picture how can I know which item is highlighted(when i clicked on a button for example on the Back Button)?

A: You must implement an OnItemClickListener
myList.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
       YourClass yourObject = (YourClass) arg0.getItemAtPosition(arg2);
    }
}

A: This should do it:
http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()
or keep a reference of the current selection.


text:
Q: Desktop and Web application share Facebook Authentication I am building an application that has a web front end and a desktop client application.  The web front end allows users to login using Facebook.  It exposes a web service to the Desktop application for uploading data.  The web service needs to insure that the desktop application uploading data for a user is really from that user.  I have already implemented Facebook login on both the client and web interface using the Graph API.  How would I go about using Facebook to validate that the user using the desktop application is who they say they are? Also, how can I make it so the user can login once and not need to login again on the desktop application?

A: After much struggle I figured out that it's possible to receive a session key that does not expire.  You can do this by requesting offline access to a user's profile.  I stored this in the database on the web side and retrieved and stored it on the desktop side.  The only problem is the session key technically can be viewed and used by someone other than the user to make requests.  Any other suggestion would be appreciated.


text:
Q: how to pass parameters to follow redirects in jmeter? I'm writing performance test.
In step #1 I'm visiting url: https://example.com/oauth/authorize
Since i have selected follow-redirect, it redirects to second url - https://example.authenticate.com/login
Now when the redirect happens i need to pass the username and password in-order to get authenticate and get bearer token from the result of the second url
In my JMeter script how can i pass the parameter when redirect happens?
Could you please tell me how it can be achieved ?

A: If you need to "pass" the parameters you will need to create another HTTP Request sampler to "enter" the credentials.
The redirect URL can be extracted from the Location header using i.e. Regular Expression Extractor

and once you have it you can use it in the 2nd HTTP Request sampler in form of a JMeter Variable:


text:
Q: Looking for explanation for a stack corruption bug The following problem is distilled from a huge project and the most minimal example of the problem I was able to come up with.
I know, deriving from std::string is bad, and it already is changed in our code base, but I am trying to understand what is happening under the hood here.
The code crashes on Visual C++ 2017
Microsoft Visual Studio Community 2017
Version 15.2 (26430.14) Release
Visual C++ 2017   00369-60000-00001-AA257

in release-mode only (with speed optimization). It does not crash in release-mode without speed optimization.
#include <string>
#include <string_view>
#include <vector>

struct my_string : public std::string
{
    __declspec(noinline)
        my_string::my_string( const std::string_view& str ) :
        std::string( str.data(), str.size() )
    {}

    template <typename T>
    my_string& arg( T )
    {
        return *this;
    }
};

struct my_string_view : public std::string_view
{
    my_string_view( const std::string_view::value_type* val ) :
        std::string_view( val ) {}

    template <typename... PARAMS>
    my_string arg( PARAMS&&... prms ) {
        return my_string( *this ).arg( std::forward<PARAMS>( prms )... );
    }
};

template <typename T>
struct basic_color
{
    T r, g, b, a;

    basic_color() : r( 0 ), g( 0 ), b( 0 ), a( 255 ) {}

    template <typename U>
    explicit basic_color( const basic_color<U>& c ) :
        r( c.r ), g( c.g ), b( c.b ), a( c.a )
    {}
};

using color = basic_color<std::uint8_t>;
using float_color = basic_color<float>;

__declspec(noinline)
void change_float_color( float_color& color )
{
    color.r = 0.1f;
}

int main()
{
    std::vector<float_color> colors = { {} };
    float sum = 0;
    for ( std::uint32_t i = 0; i < 1; ++i )
    {
        float_color fc;
        change_float_color( fc );
        color c( fc );
        std::vector<std::string> msgs;
        msgs.push_back( my_string_view( "" ).arg( c.r ) );
        msgs.push_back( my_string_view( "" ).arg( c.g ) );
        sum += fc.b - colors[i].b;
    }
    return static_cast<int>(sqrt( sum ));
}

The error in Visual Studio is this (have a look at the broken sizes of msgs and colors at the bottom):

My guess is that the call of std::vector<std::string>::push_back(std::string&&) with a my_string is problematic (slicing-like behavior). But how can this corrupt the stack (or the stack pointer)?
Does anybody have an idea what could be happening here or how I can find out?
Here is my project in case anyone is interested in reproducing the problem.

A: I think it is a compiler bug.
Here's what I see from the disassembly: upon main() entry, esp is saved into ebx. At the end, esp is restored from ebx. However, in the middle (after calling std::_Destroy_range1) ebx value is overwritten with something else. So, at the end, the ret instruction uses a bogus esp value, and jumps to an invalid place.
So, actually, the stack isn't corrupted (this bug cannot be catched with data breakpoints as Hans suggested), but the stack pointer is.


text:
Q: htaccess: How to redirect to 404 if url parameter is missing or invalid? Assume the following folder structure on the webserver (Apache):
https://somedomain.com/parentfolder/childfolder.
Using .htaccess, I'd like to display the childfolder and any of it's children (files as well as folders) only the URL contains a certain parameter. For example, the page should be shown if it's requested by:
https://somedomain.com/parentfolder/childfolder?secretparameter=secretvalue123

However if

*

*the value of parameter secretparameter is not exactly secretvalue123 or

*the parameter secretparameter is missing,

then a 404 error should be returned.
Do you have any ideas how the .htaccess rules would look like to accomplish this? Your help is greatly appreciated, thank you.

A: So, if the query string is not secretparameter=secretvalue123 when requesting a resource within the childfolder then issue a 404 not found. You can do something like the following at the top of the .htaccess file in the document root using mod_rewrite:
RewriteEngine On
RewriteCond %{QUERY_STRING} !=secretparameter=secretvalue123
RewriteRule ^parentfolder/childfolder - [R=404]

This blocks the request if the query string is not exactly equal to secretparameter=secretvalue123. (You don't need the L flag here when specifying a non-3xx code as it is implied.)
You could simplify the RewriteRule slightly if instead, you placed these directives in the subdirectory you want to protect. ie. at /parentfolder/childfolder/.htaccess. For example:
RewriteRule ^ - [R=404]


text:
Q: Is assigning an inverse-Wishart distribution to a diagonal matrix problematic? I'm reading the paper Bayesian Vector Autoregressions by Thomas Wozniak. He considers the model
$$y_t = \mu + A_1 y_{t-1} + \cdots A_k y_{t-k} + u_t$$ where each $y_i$ is a $N$-vector, each $A_j$ is a $N\times N$ matrix and $u_t \sim N(0, \Sigma)$
He assigns the prior for $\Sigma$ to be inverse Wishart. I think that
the errors are independent, which would mean that $\Sigma$ is diagonal. If this is the case, then $N^2 - N$ of the entries are zero (i.e. non-random). If this is not the case, I am working with a similar model where the covariance matrix is diagonal. In either case, I am led me to the following question:

Is it okay to assign the inverse Wishart distribution to diagonal matrix?


text:
Q: Implementing safe shift-left I would like to implement a shift-left function that would trigger a failure upon overflow.
Here is my code:
uint32_t safe_shl(uint32_t x, uint8_t y) {
    uint32_t z = x << y;
    assert((z >> y) == x);
    return z;
}

Please assume that I the assert function registers an error in my system.
I would like to ensure that my method is bullet-proof (i.e., fails on every erroneous input and only on erroneous input).
And I would also like to ask if you know of a more efficient way to implement this (assuming that it is indeed bullet-proof).

A: If x << y is undefined, all bets are off.
The only safe way is to check that it's a valid shift before attempting it.
uint32_t safe_shl(uint32_t x, uint8_t y) {
    assert (y < 32);
    if (y < 32)
    {
        uint32_t z = x << y;
        assert((z >> y) == x);
        return z;
    }
    return 0;
}

Note that you need the condition – shifting unconditionally lets the compiler assume that y < 32 is true.

A: Are you asking to assert if the shift would cause a carry?
In which case it's a bit nasty in c++ without resorting to intrinsics or assembler.
#include <cassert>
#include <cstdint>
#include <limits>

bool shl_would_carry(uint32_t x, uint8_t y)
{
    constexpr auto nof_bits = std::numeric_limits<decltype(x)>::digits;
    if (y >= nof_bits)
    {
        if (x != 0) return true;
    }
    else
    {
        auto limit = decltype(x)(1) << (nof_bits - y);
        if (x >= limit) return true;
    }
    return false;
}

uint32_t safe_shl(uint32_t x, uint8_t y)
{
    assert(!shl_would_carry(x, y));
    return x << y;
}

I think that's right.
This might be better:
std::tuple<uint32_t, uint32_t> shl(uint32_t x, uint8_t y)
{
    uint32_t overflow, result;
    constexpr auto nof_bits = std::numeric_limits<decltype(x)>::digits;
    overflow = x >> (nof_bits - y);
    result = x << y;
    return std::make_tuple(overflow, result);
}

uint32_t safe_shl(uint32_t x, uint8_t y)
{
    auto t = shl(x, y);
    assert(!std::get<0>(t));
    return std::get<1>(t);
}

A: In C, x << y if defined for uint32_t provided y < 32. From the n1570 draft for C11 in 6.5.7 Bitwise shift operators:

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

The result in then required to be:  x × 2y, reduced modulo
one more than the maximum value representable in the result type
Let call that value z like it is in your proposed code. Like you use an unsigned type the value of z >> y is required to be the integral part of z/2y.
That means that provided y < 32 if there is an overflow, the value of z >> y will be strictly less than x because of the modulo, and if there is non overflow, you get exactly x
Full reference from 6.5.7 Bitwise shift operators:

...4 The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with
  zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo
  one more than the maximum value representable in the result type. If E1 has a signed
  type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is
  the resulting value; otherwise, the behavior is undefined.
5 The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type
  or if E1 has a signed type and a nonnegative value, the value of the result is the integral
  part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the
  resulting value is implementation-defined.

It is exactly the same in C++ from n4296 draft for C++14 in 5.8 Shift operators [expr.shift]:

...The behavior is undefined if the right operand
  is negative, or greater than or equal to the length in bits of the promoted left operand.
2 The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned
  type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable
  in the result type. Otherwise, if E1 has a signed type and non-negative value, and E1×2E2 is representable
  in the corresponding unsigned type of the result type, then that value, converted to the result type, is the
  resulting value; otherwise, the behavior is undefined.
3 The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed
  type and a non-negative value, the value of the result is the integral part of the quotient of E1/2E2. If E1
  has a signed type and a negative value, the resulting value is implementation-defined.

So in both languages, and assuming that the assert function registers an error in [your] system, code should be:
uint32_t safe_shl(uint32_t x, uint8_t y) {
    assert(y<32);
    uint32_t z = x << y;
    assert((z >> y) == x);
    return z;
}

A: In order to write a safe function, you must first identify what isn't safe. If you don't do this, the task is nonsense. The kind of "overflow" you mention is actually well-defined. But the following cases of dangerous behavior exist:

*

*Left-shifting further than the size of the variable, including shifting data into the sign bit of a signed variable. (Undefined behavior)

*The the right operator is a negative number. (Undefined behavior)

*Right-shifting a negative number. (Impl.-defined behavior)

*Implicit integer promotion of the left operand causing it to silently change signedness and thereby invoking one of the above errors.

To avoid this, you need to ensure that:

*

*The left operand must be unsigned.

*The right operand must be valid and in range of the type of the left operand.

*The left operand must not be a small integer type.

1) and 3) are solved by using uint32_t. There exist no system where uint32_t is smaller than int.
2) is solved by using an unsigned type and checking that it isn't too large.
In addition, you seem to have a requirement that shifting out of bounds of the left operand should not be allowed. This is weird, but ok, lets implement that too. It can be done by checking if the MSB bit position plus the number of shifts are larger than 31.
uint8_t msb_pos32 (uint32_t data)
{
  uint8_t result = 0;
  while(data>>=1 > 0)
  {
    result++;
  }
  return result;
}

uint32_t safe_LSL32 (uint32_t x, uint8_t y)
{
  if(y > 31 || y+msb_pos32(x) > 31)
  {
    __asm HCF;               // error handling here
  }
  return x << y;
}

Note that this code can be further optimized.

A: Step 1.  If x == 0and any shift amount, the result is conceptually still 0 and is not a problem.
Step 2.  Do not attempt excessive shifts.

If the value of the right operand is negative or greater than or equal to the width of the promoted left operand, the behavior is undefined.  C11 §6.5.7 3

Step 3.  Insure unsigned math while shifting.
If int/unsigned is wider than uintN_t x,  then x << y is done with int math.  This is rare with N==32 yet possible.  Signed math overflow is possible and leads to UB.  By 1u*x or (0u+x), code can insure the shift uses the wider of unsigned and uintN_t math.  Good compilers will still make optimal code.
Step 4.  Detect if a reduction occurred.

If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo
  one more than the maximum value representable in the result type §6.5.7 4

uint32_t safe_shl(uint32_t x, uint8_t y) {
  if (x == 0) {
    return 0;
  }
  assert(y < 32);
  uint32_t z = (1u*x) << y;
  assert((z >> y) == x);
  return z;
}


text:
Q: Inserting a table into Outlook email using VBScript I have a table in a Microsoft Word document that I want to insert into the middle of a message in an Outlook email. When I manually copy the table into an email draft, it preserves the formatting, but when I don't, the formatting changes into a list-style. For example, this is what the table would look like:
9898    Apple   color
1394    Banana  blue
with borders, but in the email that gets sent, it shows up as
9898
Apple
Color
1394
Banana
Blue
I had to add in extra lines above because Stack Overflow wasn't showing it as each element on an separate line.
Within my code, I've taken the table and concatenated it within the string that forms the message of the email. I think this may be the problem, but I'm not sure how to change this to separately include the table. Here is my code:
message = "Dear " & owner & ", " & vbCrLf & vbCrLf
message = message & "Here is the data we have: " & vbCrLf
message = message & vbCrLf & vbCrLf & textToTable(fileName, file)
message = message & "Can you please email us back with the updated data?"
message = message & vbCrLf & vbCrLf & "Thank you."

Set MyItem = ol.CreateItem(0)
With MyItem
    .To = me
    .CC = ""
    .BCC = ""
    .Subject = "Table"
    .BodyFormat = 3
    .Body = message
    .Send
End With

I used a lot of the code here in my textToTable function, which seems to work as intended. The only problem is getting Outlook to preserve formatting of the table; does anyone have any suggestions as to how to do this? Thank you so much!

A: You are setting the plain text Body property. Create an HTML table and assign the HTMLBody property to a property formatted HTML string.


text:
Q: setWantsLayer changes behavior of NSWindow I got an issue with NSWindow and it's content view - with appearance of title bar and rounded bottom corners to be specific. I'm observing the issue on 10.11 and on 10.10 everything looks fine. But to the point.
The title bar of the window looks like this:

and on the same time bottom looks like this:

No rounded corners.
Window is initiated programmatically and it consists of two subviews added programmatically, by using self.contentView addSubview: method.
After some work found out, that adding
[self.contentView setWantsLayer:YES];

at the beginning of window init the tittle bar looks like this:

Flat and solid darker than normal color - not good.
On the other hand bottom looks as I need it to look like:

I'm not allowed to show more of the windows.
And here's the init with my experiments:
[self.contentView setWantsLayer:YES];

self.identifier = someid;
self.styleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask;
self.backingType = NSBackingStoreBuffered;
[self setFrame:NSMakeRect(0, 0, windowInitWidth, windowInitHeight) display:NO];
[self setBackgroundColor:[NSColor colorForKeyPath:@"blackcolor"]];
NSButton *windowButton = [self standardWindowButton:NSWindowCloseButton];
[windowButton setEnabled:NO];
[self centerOnMainWindowScreen];

[self setupLeftPanel];
[self setupRightPanel];
[self setupConstraints];

Any help, that will explain why is this happening (what is the order of drawing window elements?) and how to properly init window, appreciated.
Once again: it's working fine on 10.10 both ways. 10.11 is causing corrupted drawing.

A: After all, you guys were right.
I wasn't able to create minimum complete and verifiable example, but I decided to change background color of the window to transparent color.
I don't know why it was initially set to grey (it was grey when I got the task) but changing it to transparent is not affecting any components put on it later.
So this is a solution for me, but still, I wonder, why is title bar affected when window's contentView is layer backed.

A: I don't have a solution, but I can reproduce this reliably (most recently on macOS 10.12.2), so it's not just you. Save and run the below with swift:
import Cocoa

let window = NSWindow()
window.setContentSize(NSSize(width: 100, height: 100))
window.center()

let layeredView = NSView(frame: window.contentView!.frame)
layeredView.autoresizingMask = [.viewWidthSizable, .viewHeightSizable]
layeredView.wantsLayer = true
layeredView.layer!.backgroundColor = NSColor.blue.cgColor
window.contentView!.addSubview(layeredView)

window.makeKeyAndOrderFront(nil)

NSApplication.shared().run()


text:
Q: plot 3D density plot use gglot/plot_ly I have one 11-dimensional vector which is a division of [0,1]:
Vec = seq(0,1,1/12)

and a 11-by-11 matrix
A = matrix(c(0.9024306 , 0.8452877 , 0.8141085,  0.7549162 , 0.6824799 , 0.6109678 , 0.5905854 , 0.5299411,  0.4550736,  0.3858676,  0.2143513,
         0.7819361,  0.8210354  , 0.8331744,   0.8182613  , 0.7622890 ,  0.7101383 ,  0.6931922  , 0.6408286,   0.5925585 , 0.5282755,  0.4037932,
         0.7213725 ,  0.8014270,   0.8334573 ,  0.8394664 ,  0.7965267  , 0.7557029 ,  0.7411934  , 0.6947566 ,  0.6590388  , 0.5987447 , 0.4968339,
         0.6747898  , 0.7823459  , 0.8286614 ,  0.8500438  , 0.8196929 ,  0.7884412 ,  0.7761882  , 0.7352614 ,  0.7087581 ,  0.6523485 , 0.5672221,
         0.6344532 ,  0.7626475  , 0.8205274  , 0.8546509  , 0.8372373 ,  0.8149571  , 0.8049617   , 0.7695615   , 0.7506879 ,  0.6982902 , 0.6272401 ,
         0.5953397  ,  0.7403922  ,  0.8086858 ,   0.8545969  ,  0.8517511  ,  0.8388487 ,   0.8313441   , 0.8020533  ,  0.7902309 ,   0.7423674  , 0.6845121 ,
         0.5607208  ,  0.7177988 ,   0.7945752  ,  0.8503988  ,  0.8623037  ,  0.8583240 ,   0.8533009   , 0.8301061   , 0.8242061 ,   0.7809468  , 0.7343530 ,
         0.5235966  ,  0.6901752  ,  0.7751871 ,    0.8410303 ,    0.8709305 ,    0.8772494 ,    0.8752120 ,    0.8593621 ,    0.8594394 ,    0.8218108 ,    0.7868039 ,
         0.4792436 ,    0.6519074 ,    0.7454233  ,   0.8222904 ,    0.8770665 ,    0.8968215  ,   0.8988547 ,    0.8930324  ,   0.8996717  ,   0.8698448 ,    0.8479224 ,
         0.4310832  ,   0.6026974 ,    0.7035051 ,    0.7909658  ,   0.8776638  ,   0.9136550  ,   0.9208403  ,   0.9277279 ,    0.9406499 ,    0.9208578 ,    0.9120395 ,
         0.3622446  ,   0.5148011 ,    0.6215788  ,   0.7210252 ,    0.8646102  ,   0.9275842  ,   0.9438128  ,   0.9730440   ,  0.9930145 ,    0.9911498  ,  0.9985318),nrow=11,byrow=TRUE)

What I expect is like a scatter plot like the following:

each point represents a pair, e.g., (0.08333, 0.08333, 0.90243) etc.
I tried plot_ly to plot this, but failed. Can anyone shed lights on how to draw this? I truly appreciate your suggestions!

A: Here is one that is quite close:

library(RColorBrewer)
library(plot3D)

colfun <- colorRampPalette( c("blue","cyan","orange","yellow") )
mycolors <- colfun(11)
persp3D(
    z=t(A),
    col=mycolors,
    border="black",
    theta=45+270,
    phi=15,
    zlim=c(0,1.5),
    colkey=FALSE,
    lwd=.3,
    ticktype="detailed",
    nticks=7,
    bty="b2"
)

A: The A matrix can be the z argument to plot_ly`. Plotly figures out the dimensions from the matrix. In your case you would not need to add labels to the axis ticks, but you could add axis labels when the range of x and y values were not [0,1](although this does generate a warning despite being entirely successful):
if( !require(plotly) ){install.packages("plotly", dependencies=TRUE)
                       library(plotly)}
plot_ly(z = A, type = "surface", labels=list(x=(1:11),y=(1:11)))

And you can forget about ggplot2. It does not do pseudo-3D. Hadley is philosophically opposed to that type of visualization. The R package that  does this sort of plotting with interactive rotation is rgl.


text:
Q: Email - Process Ads website emails with custom solution or using Celery/RabbitMQ? I need to process e-mails for a medium project that will be expectecting to send 20 or 30 emails per hour.
I've designed a solution in other project that uses a database table and a cronjob running every 5 or 10 minutes to handle this. The Database table is very simple. Looks like this:
CREATE TABLE "atem_emails_envios" (
    "id_email_envio" int4 NOT NULL,
    "id_email_msg" varchar(20) NOT NULL,
    "dat_inserted" timestamp NOT NULL,
    "dat_sended" timestamp,
    "try_number" int4,
    "max_tries" int4 NOT NULL,
    "email_from" varchar(500) NOT NULL,
    "email_to" varchar(500) NOT NULL,
    "email_cc" varchar(500),
    "email_bcc" varchar(500),
    "email_subject" varchar(500) NOT NULL,
    "email_msg" text NOT NULL,
    "error_msg" text,
    "i_started" timestamp,
    "pid" int4,
    "coment" varchar(2000),
    "id_utiliz_ins" varchar(45),
    "id_utiliz_upd" varchar(45),
    "data_ult_actual" timestamp,
  PRIMARY KEY("id_email_envio"),
  CONSTRAINT "Ref_atem_emails_envios_to_atem_mensagens_email" FOREIGN KEY ("id_email_msg")
    REFERENCES "atem_mensagens_email"("id_email_msg")
    MATCH SIMPLE
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
    NOT DEFERRABLE
);

When an e-mail is being processed I just store the PID to the table to avoid collisions.
My question goes in this direction. I've been using this table to process e-mails in a website with low traffic, and works well. What advantages I have using a Queue manager like Celery and a broker like RabbitMQ? It seems to me that I will add another layer of complexity. What benefits I will gain using a solution like Celery/RabbitMQ?
Please give me some clues.
Best Regards,

A: Well like the old adage "it it ain't broke, don't fix it". Doesn't sound like you really need to complicate the architecture if you aren't planning on scaling or worrying about the current CRON/PG setup.
That said, there are benefits to using an async framework like Celery. To name a few:

*

*You may very well have future use cases that can take advantage of an async system (SMS sending, user processing, integration, cache warming, webhooks, etc.)

*easier to maintain if/when you scale as it's well documented and has a large community

*greater visibility and control

As for complexity, we built an integration to Celery so you can replace the broker with our cloud message queue service IronMQ. Check out http://Iron.io/celery. This will help reduce your complexity and broker point of failure by replacing RabbitMQ.
Hope this helps!


text:
Q: Can we Use Z3 SMT Solver for SW testing Can we use Z3 to do functional verification of software. For example , if i have a code which does lets say vending machine controller , can we use Z3 to functionally test it , if yes, to how much depth and if no why?

A: Using SMT solvers for verification is both "routinely done" and is also the topic of current research in both academia and industry. And Nikolaj is being modest: I'd recommend reading his excellent and highly accessible CACM article to start with, which also contains many useful further references.


text:
Q: How do I turn off caching in IIS7? I'm developing an ASP classic site under Windows 7 (form a queue ladies). The problem is IIS seems to be heavily making use of its cache for both static and dynamic content which really conflicts with my 'make a small change, alt-tab, hit ctrl-F5' development style. Changes made to .asp files may take two or three refreshes to show up where as changes to .js files can take 20 times as many. How do I go about turning the caching off on my development machine?
Cheers.
in b4 stop using asp classic

A: Click on the server name then go to output caching.
Click Add Cache Rule then type the extensions - .aspx, .aspx.vb, .aspx.cs, .js etc. (not sure if you can do all on one)
Then simply either tick the prevent all caching or untick user-mode caching and it should stop IIS from keeping a cache of the pages.
Next time you do a full refresh, it should get the files from the hard drive and not the cache/memory
 I do not currently have a machine with IIS7 on that I can muck around with so I Googled and found the picture below:

A: This answer helped me, (note: i'm using IIS8)
link
I think its better to disable "Cache" of "Output Cache feature" by clicking the "Edit Feature Settings"

A: This blog might help: Response caching in IIS7.
It explains how this functionality can be controlled by editing system.webServer/caching section or by using IHttpCachePolicy intrinsic.


text:
Q: laravel how to specifiy the input columns I have a form in html that has an input with name restaurantName, but my column in the database is name. I am not able to use this in the controller
Restaurant::create(Input::only('restaurantName'));

Because there is no column with restaurantName so my question is how to tell laravel that restaurantName is maped to name ?
many thanks
Edit
the html form has these fields:
restaurantName
website
username
password
mobileNumber
firstName
lastName

The database has two tables which are Admin and Restaurant, each restaurant has one admin and the admin is one for each restaurant, so it is one to one relationship
when I submit the form I do the following:
$input = Input::all();
 $admin = Admin::create(Input::only('username', 'password', 'mobileNumber', 'firstName', 'lastName'));

                $data = ['name' , Input::get('restaurantName'), 'website' => Input::get('website')];
                $restaurant = new Restaurant($data);
                $admin->restaurant()->save($restaurant);

the admin row is inserted to the database so the problem starts with the $data line code.
the exception is:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::save()

A: Firstly, you should never just blindly pass user input to models, and secondly, this particular problem has absolutely nothing to do with laravel.
Your problem can be solved with basic PHP. Simply, create your own array of input.
$data = [
    'field'    => Input::get('field'),
    'name'     => Input::get('restaurantName')
];

There seems to be a grave misconception that Laravel is its own independant system, it is not. It is literally a collection of PHP code, it doesn't do anything that can't be done with PHP and it doesn't prevent you from doing anything you can normally do with PHP.


text:
Q: Code doesn't execute HttpResponse for second time when called twice I'm doing and app who calls the same method two times and the second time I call the method it doesn't execute the line with HttResponse.
Here is the AsyncTask where everything starts:
private class FetchSubjectsTask extends AsyncTask<String, Void, List<Subject>> {
    private ProgressDialog pd;
    @Override
    protected List<Subject> doInBackground(String... params) {

        List<Subject> subjects = null;
        try {
            subjects = api.getMySubjects(params[0]);

        } catch (Exception e) {
            e.printStackTrace();
        }
            return subjects;
    }

    @Override
    protected void onPostExecute(List<Subject> result) {

        printSubjects(result);

        if (pd != null) {
            pd.dismiss();
        }
    }
}

Then I get the subjects through the method getMySubjects which is:
public List<Subject> getMySubjects(String username) {
    List<Subject> subjects = new ArrayList<Subject>();
    java.lang.reflect.Type arrayListType = new TypeToken<ArrayList<Subject>>() {
    }.getType();
    String url = BASE_URL_VM + "users/" + username + "/subjects";
    HttpClient httpClient = WebServiceUtils.getHttpClient();
    try {
        System.out.println("inside try");
        HttpResponse response = httpClient.execute(new HttpGet(url));
        System.out.println("response executed");
        HttpEntity entity = response.getEntity();
        Reader reader = new InputStreamReader(entity.getContent());
        subjects = gson.fromJson(reader, arrayListType);
    } catch (Exception e) {

    }
    System.out.println("Array lenght " +subjects.size());
    return subjects;
}

That's the first time HttpResponse executes and I get the "response executed" and "Array lenght 2" which are the number of subjects that user (username) has in the database.
The problem is when in onPostExecute I call the method printSubjects which is:
private void printSubjects(List<Subject> subjects){
    adapter = new SubjectAdapter(this,(ArrayList<Subject>)subjects, (String) getIntent().getExtras().get("username"));
    setListAdapter(adapter);
    adapter.notifyDataSetChanged();
}

This calls the SubjectAdapter which prints the Subjects in a ListView:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ViewHolder viewHolder = null;
    if (convertView == null) {
    convertView = inflater.inflate(R.layout.subject_detail, null);
    viewHolder = new ViewHolder();
    viewHolder.tvsubject = (TextView) convertView
            .findViewById(R.id.tvsubject);

    boolean match = api.checkMySubjects(username, data.get(position).getId());

    Button addButton = (Button) convertView.findViewById(R.id.bAdd);
    if(match){
        addButton.setText("Delete");
    }else{
        addButton.setText("Add");
    }

    String content = data.get(position).getName();
    viewHolder.tvsubject.setText(content);
    }
    return convertView;
}

private static class ViewHolder {
    TextView tvsubject;
    TextView tvauthor;
}

There I call the method checkMySubjects which calls again getMySubjects to compare.
public boolean checkMySubjects(String username, String id) {
    List<Subject> mySubjects = getMySubjects(username);
    boolean match = false;
    for (Subject s1 : mySubjects) {
        if (s1.getId().equals(id)) {
            match = true;
        }
    }
    return match;
}

But now the method getMySubjects doesn't arrive until "Response executed" and the Array lenght is 0. It only shows "Inside try".
Why? I'm calling the same method with the same URL but first time I get the 2 subjects in the array and the second time I get nothing because HttResponse doesn't execute.
Thank you!

A: It's hard to say what's happening, but I'd like to point out what I think it's wrong. First, let's state the fact thatgetMySubjects performs a network operation, now, the first time you call it, it is called from within an AsyncTask on a thread other than the UI thread. This is perfectly fine
Then you call printSubjects in onPostExecute which populates a ListView with the results...
private void printSubjects(List<Subject> subjects){
    adapter = new SubjectAdapter(this,(ArrayList<Subject>)subjects, (String) getIntent().getExtras().get("username"));
    setListAdapter(adapter);
    adapter.notifyDataSetChanged();
}

Now, the problem is in your getView implementation of the adapter. More specifically here...
boolean match = api.checkMySubjects(username, data.get(position).getId());

this is terribly bad because you are making a network connection on the UI thread everytime you inflate a ListView item, so if you had ten items you will be making a network connection ten times (plus everytime you you scroll up and/or down the list).
Moreover, Android complains with a FATAL exception if you attempt to make a network connection on the UI thread. You're not even noticing because you are not doing anything with this exception...
try {
        System.out.println("inside try");
        HttpResponse response = httpClient.execute(new HttpGet(url));
        System.out.println("response executed");
        HttpEntity entity = response.getEntity();
        Reader reader = new InputStreamReader(entity.getContent());
        subjects = gson.fromJson(reader, arrayListType);
    } catch (Exception e) {

    }

the catch block is empty, if you print it to the LogCat you'll see the details
Suggestion

*

*Don't make a network connection on the UI thread...you can't

*On getView instead of making a network connection for every single iteration, eagerly load the data in memory before you set the ListView

Again, the offending line of code is...
boolean match = api.checkMySubjects(username, data.get(position).getId());

in getView


text:
Q: Encrypt in C# and decrypt using Apex I want to pass a field in the query string from asp .net to Apex . I want to encrypt the value of the field and then pass it in the query string.
I am not sure how to approach this, are there any example code /links for same ?
Basically i want to encrypt in C# and decrypt using Apex.
In C#
 static string key = "eU5WzoFgU4n8Apu5PYxcNGRZswRDZJWDEMdbQVU85gw=";
 static string IV = "9ehY9gYtfIGlLRgwqg6F2g==";
    static void Main(string[] args)
    {
        string source = "test";
        string encrypted = EncryptStringToBytes_Aes(source, Convert.FromBase64String(key), Convert.FromBase64String(IV));

        Console.ReadLine();
    }
static string EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");
        string encrypted;
        // Create an AesManaged object
        // with the specified key and IV.
        using (AesManaged aesAlg = new AesManaged())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = Convert.ToBase64String(msEncrypt.ToArray());// ToArray();
                }
            }
        }

        // Return the encrypted bytes from the memory stream.
        return encrypted;

    }

In Apex:
string cryptoKey='eU5WzoFgU4n8Apu5PYxcNGRZswRDZJWDEMdbQVU85gw=';
 String det= System.currentPageReference().getParameters().get('Det');
 Blob decryptedData = Crypto.decryptWithManagedIV('AES256', EncodingUtil.base64Decode(cryptoKey), EncodingUtil.base64Decode(det));

But this doesn't work, decryptedData.toString() does not come as 'test' (the original text). How do i decrypt it back ?

A: Why? All communication with SF is done via SSL anyway (https://salesforce.stackexchange.com/questions/8273/data-loader-cli-and-encryption for example).
If you absolutely have to - Apex has Crypto class that supports several algorithms. Hopefully you'll find matching ones in C# libraries.
There's also EncodingUtil class if you need to pass some binary data (as base64 for example).

A: The person who created the above example was VERY close.  They probably would have realized it if they had encrypted a longer string than "Test" -- they just needed to insert some padding in front of what they were encrypting:
string spadding = "paddingxxxxxxxxx";
string source = spadding + "Opportunity0065";
-- Output would have been "Opportunity0065"


text:
Q: Disagreement on Convergence of Integral between Mathematica and WolframAlpha I am trying to do the integral $ \int_{-\infty}^{\infty} (1+\cos(t))\cosh(t)dt$. Doing this on Mathematica gives me that the integral is equal to 0. However, doing this on WolframAlpha gives me that the integral does not converge. Why are the results different?

A: This is a bug specific to version 11.3 of Mathematica.  The correct answer is non-convergence.  Indeed since the integrand is even, we can compute the integral as
Limit[2 Integrate[(1 + Cos[t]) Cosh[t], {t, 0, b}], b -> \[Infinity]]
(* \[Infinity] *)

which evaluates correctly even in version 11.3.  BTW, this disproves the comment that the limit of the integral over symmetric domains is zero.  That could only happen for an odd function such as the following one
Limit[Integrate[(1 + Cos[t]) Sinh[t], {t, -b, b}], b -> \[Infinity]]
(* 0 *)

Limit[Integrate[(1 + Cos[t]) Sinh[t], {t, a, b}], {a, b} -> {-\[Infinity], \[Infinity]}]
(* Indeterminate *)

Integrate[(1 + Cos[t]) Sinh[t], {t, -\[Infinity], \[Infinity]}]
(* returns unevaluated with non-convergence message *)


text:
Q: Read style information from JavaScript Web Animations API, mid state Given a web animation, such as the one over here: https://codepen.io/arxpoetica/pen/aXqEwe
How do I get CSS or style information based on state between keyframes at any given point and time?
Sample code:

NOTE: this API only works in limited browsers / platforms.

A: WAAPI method .animate returns Animation object which includes all you need:
Run the snippet below:

var keyframes = [{
    transform: 'rotate(0) scale(1)',
    backgroundColor: 'orange'
  },
  {
    transform: 'rotate(180deg) scale(3)',
    backgroundColor: 'blue'
  },
  {
    transform: 'rotate(360deg) scale(1)',
    backgroundColor: 'orange'
  }
];

var options = {
  duration: 3000,
  iterations: Infinity
};

var thing = document.querySelector('.thing');

var A = thing.animate(keyframes, options);

console.clear();

function getState() {
  if (A.playState === 'running') {
    document.querySelector('section').innerHTML += `

      progress: ${getProgress()*100|0}%

      transform: ${getComputedStyle(thing).transform}

      backgroundColor: ${getComputedStyle(thing).backgroundColor}

`;
    //A.startTime = 0;
    A.pause();
  } else {
    A.play();
    document.querySelector('section p:last-of-type').remove();
  }
}

function getProgress() {
  return A.effect ?
    A.effect.getComputedTiming().progress :
    A.currentTime % options.duration / options.duration
}
html {
  height: 100%;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #0a2933;
}

section {
  position: absolute;
  z-index: 1;
  top: 0;
  left: 1em;
  color: silver
}

.thing {
  height: 100px;
  width: 100px;
  background-color: orange;
}

How do I get CSS or style information based on state between keyframes at any given point and time?

  <button onclick="getState()">Click here</button>

Also, WAAPI has a nice polyfill.
Hope it helps.

A: You can use requestAnimationFrame to achieve the expected result, see How to detect changes made by CSS3 animation or web animations API?


text:
Q: Java PreparedStatement setting NULL parameters Java PreparedStatement allows you to set a value for a given parameter or to set it to NULL
SELECT *
FROM ADDRESS
WHERE ADDRESS_LINE1 = ?

so we could write code to set this parameter:
 if (addressLine1 != null) {
      preparedStatement.setString(1, addressLine1);
    } else {
      preparedStatement.setNull(1, VARCHAR);
    }

however it is also declared that you should never compare a value to null using the = operator and actually use the IS operator for null comparisons.
Is the prepared statement actually swapping the = operator for IS under the covers here or is the null just being inserted still using the = operator? If the latter then when is it ever useful to use this and are you actually getting the expected outcome?
I am asking this on the back of the following stack overflow question
SQL is null and = null

A: No, the prepared statement is not swapping out = for IS. Your code is responsible for that. Just like you would be responsible for queries literally using something = NULL instead of something IS NULL.
The point of being able to set things to null, is for use in for example update or insert statement, or in cases where you do correctly use is or is distinct from.
It is also used for null-conditional checks like where ? is null or something = ? with
String something = "xyz"; // or String something = null;
statement.setString(1, something);
statement.setString(2, something);


text:
Q: Error executing S3Hook list_keys or read_key methods I get this error message:
{logging_mixin.py:112} INFO - [2020-03-22 12:34:53,672] {local_task_job.py:103} INFO - Task exited with return code -6
 when I use the list_keys or read_key methods of S3 hook. The get_credentials method works fine though. Have searched around and can't find why this occurs.
I'm using apache-airflow==1.10.9, boto3==1.12.21, botocore==1.15.21
Here's my code for my custom operator that makes use of the S3Hook:
class SASValueToRedshiftOperator(BaseOperator):
    """Custom Operator for extracting data from SAS source code.
    Attributes:
        ui_color (str): color code for task in Airflow UI.
    """
    ui_color = '#358150'

    @apply_defaults
    def __init__(self,
                 aws_credentials_id="",
                 redshift_conn_id="",
                 table="",
                 s3_bucket="",
                 s3_key="",
                 sas_value="",
                 columns="",
                 *args, **kwargs):
        """Extracts label mappings from SAS source code and store as Redshift table
        Args:
            aws_credentials_id (str): Airflow connection ID for AWS key and secret.
            redshift_conn_id (str): Airflow connection ID for redshift database.
            table (str): Name of table to load data to.
            s3_bucket (str): S3 Bucket Name Where SAS source code is store.
            s3_key (str): S3 Key Name for SAS source code.
            sas_value (str): value to search for in sas file for extraction of data.
            columns (list): resulting data column names.
        Returns:
            None
        """
        super(SASValueToRedshiftOperator, self).__init__(*args, **kwargs)
        self.aws_credentials_id = aws_credentials_id
        self.redshift_conn_id = redshift_conn_id
        self.table = table
        self.s3_bucket = s3_bucket
        self.s3_key = s3_key
        self.sas_value = sas_value
        self.columns = columns

    def execute(self, context):
        """Executes task for staging to redshift.
        Args:
            context (:obj:`dict`): Dict with values to apply on content.
        Returns:
            None
        """
        s3 = S3Hook(self.aws_credentials_id)
        redshift_conn = BaseHook.get_connection(self.redshift_conn_id)

        self.log.info(s3)
        self.log.info(s3.get_credentials())
        self.log.info(s3.list_keys(self.s3_bucket))

A: s3 = S3Hook(self.aws_credentials_id)
s3.list_keys(bucket_name=s3_bucket, prefix= s3_path, delimiter=delimiter)


text:
Q: How to wait for Promise to resolve before returning a new Promise? I'm building a web application for creating retail signage. Firestore holds information about the signs, and I want to be able to remove all of the signs if a user clicks on 'Remove all Signs.' A dialog will then appear which will ask the user to confirm deleting all signs in the database. If they confirm, then all the signs should then be deleted from Firestore.
The document ID of each sign is stored in an array called signIds. I want to be able to iterate through signIds and delete each document from the signs collection in Firestore. Once all the Promises have resolved, I want to return a Promise and resolve it in the event handler in mounted().
I've tried returning a Promise at different places in the code, to no avail. I've also tried using async and await but that seemed to have the same issue.
data() {
        return {
            signIds: [],
        }
},
methods: {
    showModal(message, type) {
        this.$root.$emit('openModal', {
            closed: false,
            text: message,
            type: type
        })
    },
    emptyQueue() {
        let self = this;
        let deleted = 0;

        for (let id of self.signIds) {
            database.collection("signs").doc(id).delete()
                .then(() => {
                    console.log("Document successfully deleted!");
                    deleted++;
                }).catch((error) => {
                    console.error("Error removing document: ", error);
                });
        }

        // Once all signs are deleted, return new Promise
        return new Promise((resolve, reject) => {
            return (deleted === self.signIds.length) ? resolve() : reject(new Error('An error occurred while deleting signs.'));
        });
    }
},
created() {
        // Get and store the document id for each sign
        database.collection("signs").get()
            .then(snapshot => {
                snapshot.forEach(doc => {
                    this.signIds.push(doc.id);
                })
            });
    },
mounted() {
        // When the user clicks 'OK' on the dialog, delete all signs from the database
        this.emptyQueue()
            .then(() => {
                setTimeout(function() {
                    self.showModal('All signs were successfully removed.', 'success');
                }, 300);
            }).catch(() => {
                setTimeout(function() {
                    self.showModal('An error has occurred. Some signs were not removed.', 'error');
                }, 300);
            })
        }

I expect the new Promise to return after Firestore's Promises have resolved, but currently the new Promise is returned immediately after the for loop is finished.

A: Your current iteration through signIds's Promises is not being chained with anything else - the .delete() Promises aren't being used anywhere at the moment. It would be better to .map each id to a Promise in an array, then use Promise.all on that array. If errors are handled in the consumer, there's no need to catch in emptyQueue just to throw a new error - instead, just return the Promise chain alone, and avoid the explicit Promise construction anti-pattern:
emptyQueue() {
  return Promise.all(
    this.signIds.map(id => (
      database.collection("signs").doc(id).delete()
    ))
  );
}

If any one of the .delete() calls result in an error, that error will percolate up to your
this.emptyQueue()
  // ...
  .catch(() => {
    ...
  });

section automatically via the Promise.all.

A: Making use of write batch may answer your needs https://firebase.google.com/docs/reference/js/firebase.firestore.WriteBatch

A: You should be able to do that using batch, with a code that should look something like the following:
// start a batch
var batch = database.batch();

for (let id of self.signIds) {
  // for each, add a delete operation to the batch
  batch.delete(database.collection("signs").doc(id));
}

// Commit the batch
batch.commit();


text:
Q: Embedded software question: why the down votes? I've been given a lot of quick downvotes with no feedback to https://stackoverflow.com/questions/16758723 with several close votes.
I read https://meta.stackexchange.com/a/39136/191913 that it is perfectly acceptable to ask embedded software questions on SO, so what is the reason?

A: Probably because of the one line in the FAQ that states:

If you can imagine an entire book that answers your question, you're asking too much.

The first part of the question, where you request specific advice on what channel you should proceed through (IRC, Google Groups, yada yada) could lead to open-ended discussions about which chat room is better for what. Plus, this is just one aspect of your multi-faceted question. You'd probably have better luck going straight to IRC yourself. #hardware has some good people.
You say that while you have asked an embedded software question, you have done more than that. You have directly asked a "how to" question:

And more specifically, how do I:
-Find out if the firmware can be repackaged with existing tools (such as firmware-mod-kit)
-perform checks/tests before pushing to the device to minimise bricking risk

This is unanswerable. You could right a book about the second bullet alone. That's why it's getting downvoted.

A:
does anybody have any suggestions on suitable IRC channels, Google
  Groups, open source projects, forums, etc. ?

This perfectly fits the scope of not constructive on StackOverflow. This is not the place for discussing which groups, fora etc. are suitable or not. Neither for resource and tutorial recommendations.
The answer you link is not precise. SO is for programming questions, and that particular question is not about any programming problem, but about finding tutorials etc. Maybe it would be on-topic on Electronics.SE or anywhere else.
However, in my opinion it does not deserve to be downvoted. Closing with explanation would be the most appropriate action. Closing and downvoting are 2 separate things.

A: Q & A should be black & white. A concrete question asking for concrete a Answer. Otherwise, you end up with a question that is asking for opinions, and opinions do not fit the Q & A model, thus deemed "Not Constructive".


text:
Q: How to create a jquery mobile ordered list with list symbols set to outside?

heading

description

The result is:
   1.
   Heading
   Description

I want:
    1.    Heading
          Description

I would have thought I could have stuck list-style-position:outside as an inline style with the li tag. No luck. If I remove the listview data-role, the style is applied correctly.
Some how the listview date-role is manipulating the styles, I can't figure out how though... I've searched for the list-style-position line in the jquery mobile css and js files and no results were returned, what is going on here?
Some help please?
PS. using jquery mobile 1.0a4.1

A: Looks like you need to add some custom CSS
Live Example: http://jsfiddle.net/7Bn2z/43/
Live Example #2: http://jsfiddle.net/7Bn2z/48/ (Fixed the layout a little)
HTML:

                    heading
                    description

CSS:
.oi-li-heading {
    font-size: 16px;
    font-weight: bold;
    margin: .6em 0;
}

.oi-li-desc {
    font-size: 12px;
    font-weight: normal;
    margin: -.5em 0 .6em;
}

UPDATE:
If you have chrome installed you can right click the example page here: http://jsfiddle.net/7Bn2z/49/ and inspect element. As you can see jQM adds a to of CSS
So in the example we start off with:

heading

description

And jQM adds it's tags to this:

heading

description

A: I had the same issue when creating a numbered list in my jquery mobile app. The css below fixed the problem for me:
  ol.ui-listview .ui-li-heading {
    display: inline-block;
    width: 100%;
    margin-left: -1.3em;
    text-indent: 1.3em;
    vertical-align: middle;
  }


text:
Q: Retrieve my number after make it in Byte[] I want to retrieve a basic number after make it in Byte[]
     public static void main(String[] args) throws IOException {
           LinkedList<Byte> s1 = new LinkedList<Byte>();
           String a = "0.111112345";
           for (byte bb : a.getBytes()) {
                s1.add(bb);
            }
 //how to retrieve "0.111112345"; from s1 ?

}
Retrieve my number after make it in Byte[] ?

A: I think you are using Byte[] in place of byte[]:
    byte[] t = (byte[]) s1.subList(0, 3).toArray();
    System.out.println(convertByteToInt(t));

Also You may want to use parse() to convert string to numbers e.g. below:
    String intString= new String(t); //<--get String from byte array
    int numInt = Integer.parseInt(intString);

A: A Byte[] is not a byte[], but you don't need to use the linked list and sublist, you could do it purely with byte[], something like
public static void main(String[] args) throws IOException {
  String a = "0.111112345";
  byte[] allBytes = a.getBytes("UTF-8");
  byte[] t = Arrays.copyOf(allBytes, 4);
  System.out.println(convertByteToInt(t));
}

java.util.Arrays.copyOf returns a copy of the initial segment of the given array truncated or extended with zeroes to the given length.
This should print the result 808333617, which is the decimal representation of hex 302E3131 (the UTF-8 bytes of the characters zero, dot, one, one).

A: Re-write this line:
Byte[] t = (Byte[]) s1.subList(0, 3).toArray();

as following:
Byte[] t = s1.subList(0, 3).toArray(new Byte[3]);

Method toArray() return Object[]. However method toArray(array) returns array passed to it as a parameter or, if this array is not long enough, other array of the same type.

A: Byte[] t = s1.subList(0, 3).toArray(new Byte[3]);
Then, look this BigInteger constructor public BigInteger(byte[] val)
Then, use:
int intValue();


text:
Q: Average distance between two randomly chosen indexes in array Interesting thought question for you guys. Given an array of length n, if I were to pick two random indexes in this array, a and b on average how far apart would they be? As in how many steps would I have to take to walk from a to b. There are no restrictions so there's a chance I pick the same index for both, and there's a chance a and b are at opposite ends of the array.
I've thought about this for a while, my initial idea being they're on average n/2(ish) apart, but I think this hunch is incorrect. An index chosen in the center of the array at most would have to walk n/2 places to find its corresponding second choice, whereas only at the ends of the array would the second choice ever be around n distance away.
Thanks!

A: After scribbling some grids of possible distances for the first few values of n, I think the exact result is in fact given by:
f(n) = (n² - 1) / 3n

A: Choosing two places in an array is equivalent to splitting the array up into 3 sections. The average size of each of those sections will be n/3 so the average distance between the two points is also n/3.

A: Using a monte carlo method in python:
from collections import defaultdict
import random

sample = [abs(random.choice(range(0,10)) - random.choice(range(0,10))) for i in range(0,10000)]

avg = float(sum(sample) / len(sample))
print ("Average: %f" % avg)

freq = defaultdict(int)
for s in sample:
    freq[s] += 1

scale = 40.0 / max(freq.values())
for i in range(0,10):
    print ("%d : %s" % (i, "#" * int(freq[i] * scale)))

Output:
Average: 3.293700
0 : ######################
1 : ########################################
2 : ####################################
3 : ###############################
4 : ##########################
5 : ######################
6 : #################
7 : #############
8 : #########
9 : ####

So, looks like it's n/3 - but it's not evenly distributed.

A: There is an easy way to know: for all the couples (a, b), computer their distance. Knowing that all the couples (a, b) have the same probability of appearance, you will just need to do the average of those distances in order to answer your question.


text:
Q: Need guidance in delimiter for regex Trying to send multiline Kafka log from RSYSLOG to FLuentd.
(?<date>\[.*?\]) (.*?) ((.|\n*)*)

Here is the link:
https://regex101.com/r/iFHyTi/1
But my regex is considering next timestamp pattern as a single line. Requirement is to stop before the next timestamp starts.

A: You can match all subsequent lines that start with either a TAB or a space char:
(?<date>\[[^][]*]) ([A-Z]+) (.*(?:\n(?!\[\d{4}-\d\d-\d\d).*)*)

See the regex demo.
Details

*

*(?<date>\[[^][]*]) - Group "date": [, zero or more chars other than square brackets, ]

*  - space

*([A-Z]+) - Group 2: one or more uppercase ASCII letters

*  - space

*(.*(?:\n(?!\[\d{4}-\d\d-\d\d).*)*) - Group 3:

*

*.* - any zero or more chars other that line break chars as many as possible

*(?:\n(?!\[\d{4}-\d\d-\d\d).*)* - zero or more sequences of

*

*\n(?!\[\d{4}-\d\d-\d\d) - a newline, LF, char not followed with [, four digis, -, two digits, -, two digits

*.* - any zero or more chars other that line break chars as many as possible


text:
Q: C# Principal System.DirectoryServices.AccountManagement EmailAddress I feel like I'm losing my mind here. I'm querying AD with a person's first and last name in order to get their AD ID and email address. At design time there is no EmailAddress property but at run-time it exists. What gives and how can I access this EmailAddress at run-time if it won't compile if I code it at design time?
private Dictionary<string, string> GetActiveDirectoryID(string firstName, string lastName)
        {
            var result = new Dictionary<string, string>();

            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

            // query AD by first and last name
            UserPrincipal qbeUser = new UserPrincipal(ctx);
            qbeUser.GivenName = firstName;
            qbeUser.Surname = lastName;

            PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

            var found = srch.FindOne();

            result.Add("id", found.SamAccountName);
            result.Add("email", found.EmailAddress);    //??

            return result;
        }


text:
Q: How can I make a link_to remote link pull up a jQuery dialog in Rails 3.1 In my view that I want to add the link, I have:
= link_to 'My Account', edit_user_registration_path( :format => js), :remote => :true
#edit-dialog

My controller action is empty.
My edit.js.erb looks like:
$("#edit-dialog").dialog({
  autoOpen: true,
  width: auto,
  open: function() {
    $("edit-dialog").html(<%= escape_javascript(render('form')) %>")
  }
});

When I click the link, I get the Javascript rendered as text in a new page.
$("edit-dialog").dialog({
  autoOpen: true,
  width: auto,
  open: function() {
    $("edit-dialog").html(<the partial contents are loaded here>)
  }
});

Why isn't the js getting executed. Instead it is getting returned as text and being rendered into a separate page.

A: Turns out I did not have jquery_ujs in may application.js. I changed it to include:
//= require jquery
//= require jquery_ujs
//= require jquery_ui

It now works.


text:
Q: Can't style my login form to be at the center with a beautiful card I'm trying to make a login form like This one using Bootstrap5, but i can't, is anybody who can help me to make a login form  like the one i mentioned here ? Actually I'm begineer in bootstrap and css.
my template:

    {% for message in messages %}

{{ message }}

    {% endfor %}

            <form method="POST" action="{% url 'login' %}">
                {% csrf_token %}

                    Enter Username
                    <input type="text" class="form-control" name="username">

                    Enter Password
                    <input type="password" class="form-control" name="password">

                <button type="submit" class="btn btn-primary">Login</button>
            </form>

A: A few additional classes from their library and it looks like so. There is a class referenced called font-weight-bold that wasn't working, so I added that as CSS. I guess it depends on which version bootstrap you are using.

.container {
  background: #1D8FF9;
  padding: 10rem 0;
}
.font-weight-bold {
  font-weight: 600;
}
.btn-block {
  display: block!important;
  width: 100%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>

Sign In

              <form method="POST" action="{% url 'login' %}">

                      Enter Username
                      <input type="text" class="form-control" name="username" placeholder="Enter Email">

                      Enter Password
                      <input type="password" class="form-control" name="password" placeholder="Enter Password">

    <input type="checkbox" class="form-check-input" id="exampleCheck1">
    Remember Me

                  <button type="submit" class="btn btn-primary btn-block">Submit</button>
              </form>

A: I've tried to get as close to the example you have shown, but I would recommend you to recreate this purely using CSS first, especially get a good working knowledge of CSS Grid and Flexbox, later when you jump into Bootstrap you will understand it much faster.

body {
  background: #f5f6f9;
}

.card {
  border-radius: 10px;
  border: 0;
  box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />

Sign In

            <form action="" method="post">

                  Email address
                  <input type="email" class="form-control" id="exampleFormControlInput1" placeholder="Enter email">

                  Password
                  <input type="email" class="form-control" id="exampleFormControlInput1" placeholder="Enter password">

                  <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
                  Remember me

                  <button class="btn btn-primary w-100">Submit</button>

                  Forgot password?

          </form>

Hope this helps :)


text:
Q: Interact with databases from ADO.NET Hi there I try to learn some ADO.NET. I'm working in Visual Studio 2015 using C#. I made a Database with some table in it which are stored on my local machine. Here is my C# code trying to connect to the database:
string constring = "Data Source=.; Database = CarShop;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(constring);
con.Open();

An error is thrown when I try to Open the SqlConnection saying this:

An unhandled exception of type 'System.Data.SqlClient.SqlException'
  occurred in System.Data.dll Additional information: A network -
  related or instance - specific error occurred while establishing a
  connection to SQL Server.The server was not found or was not
  accessible.Verify that the instance name is correct and that SQL
  Server is configured to allow remote connections.(provider: Named
  Pipes Provider, error: 40 - Could not open a connection to SQL Server)

So far I have tryied to change the connection string to something like:
string constring = "Data Source=192.168.0.101; Database = CarShop;Integrated Security=True;Connect Timeout=30";

or
constring = "Data Source=(LocalDB)/MSSQLLocalDB;AttachDbFilename=D:/Proiecte/Visual Studio/C#/DataBases/DataBaseTut2/DataBaseTut2/CarShop.mdf;Integrated Security=True;Connect Timeout=30";

But neither have worked.

A: Try this one:
Data Source=.;
Initial Catalog=database name;
Integrated Security=True;
Max Pool Size=2048;
Pooling=true;

A: *

*I would visit http://www.connectionstrings.com/sql-server/ to get the correct connection string instance for an ADO.net Sql Server connection.
I would suggest Standard Security or Trusted Connection from the examples.

*I would save it in a config file be it app.config or web.config

*When creating a connection always use the using() statement to properly dispose of the connection once it is out of scope.
Therefore:
 using(SqlConnection sqlconn = new SqlConnection(
ConfigurationManager.ConnectionStrings["defaultconnection"].ConnectionString))
 {
    sqlconn.Open();

   using(SqlCommand sqlcommand  = new SqlCommand("Select field1 FROM
   Table",sqlconn))
   {
     //code here
   }
}

*Ensure that the database on the localhost (.) can accept trusted connection and not rather use Standard Security - sql authentication - by specifying the user credentials i.e. "User Id=username;Password=pwd;"

A: I figured it out. For those who have this problem. you can get the Connection String by right clicking your database in the Server Explorer and then properties. If you do this you'll find the Connection String in the Properties panel. Copy that string but when you use it in your code use it like this:
@"whatever your Connection String is"

A: Ensure that tcp/IP is enabled in sql server manager. If not then you won't be able to communicate to it. Also check if you need to provide a named instance. Eg. localhost/sqlexpress