text:
Q: Well-designed Expandable TextBoxes in an Expandable Panel I have records in my .NET WinForms app that I lay out with enhanced TextBox controls on panels when the records are editable, but I set the TextBoxes to ReadOnly when the records are not editable.  Clicking the save button on an editable record saves the text to the database, and then it is displayed as an un-editable record (until the edit button is clicked).  Please see the following screen grab:

As you can hopefully see, the first record is not editable, but the second one is.  The problem I have is that I would like the TextBox to grow in Height if the text is too much to fit.  It seems that the TextBox is doing the WordWrap, but it either only shows one line of the text or only the first two.  Something is always cut off at the bottom.
I have looked at several other posts on this site, including, especially, Expandable WinForms TextBox.
Here is some sample code for the panel:
AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
        ...
Field1 = new ExpandoField { Multiline = true, WordWrap = true };
Field1.Location = new System.Drawing.Point(42, 3);
if (CanEdit)
{
    Field1.BackColor = System.Drawing.Color.White;
    Field1.TabIndex = 20;
}
else
{
    ((ExpandoField) Field1).ReadOnly = true;
    Field1.ForeColor = System.Drawing.Color.FromArgb(0, 50, 0);
    Field1.BackColor = System.Drawing.Color.Snow;
    Field1.TabIndex = 0;
    Field1.TabStop = false;
}
Field1.Text = Text1;
Field1.Dock = DockStyle.None;
Field1.Size = new System.Drawing.Size(538 - 25, 34);
Field1.MinimumSize = Field1.Size;
Field1.AutoSize = true;
Controls.Add(Field1);

As you can see, I have AutoSize set to true for the panel.  The code for Field2 is similar to Field1.
ExpandoField is based on sample code I saw from a response by dstran in Expandable WinForms TextBox.  It seemed to be the most complete implementation of the suggestion marked as the answer to that post.  Here's the code:
class ExpandoField : TextBox
{
    private double m_growIndex = 0.0;
    private Timer m_timer;

    public ExpandoField()
    {
        AutoSize = false;
        this.Height = 20;

        // Without the timer, I got a lot of AccessViolationException in the System.Windows.Forms.dll.
        m_timer = new Timer();
        m_timer.Interval = 1;
        m_timer.Enabled = false;
        m_timer.Tick += new EventHandler(m_timer_Tick);

        this.KeyDown += new KeyEventHandler(ExpandoField_KeyDown);
    }

    void ExpandoField_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
            this.SelectAll();
    }

    void m_timer_Tick(object sender, EventArgs e)
    {
        var sz = new System.Drawing.Size(Width, Int32.MaxValue);
        sz = TextRenderer.MeasureText(Text, Font, sz, TextFormatFlags.TextBoxControl);

        m_growIndex = (double)(sz.Width / (double)Width);

        if (m_growIndex > 0)
            Multiline = true;
        else
            Multiline = false;

        int tempHeight = (int) (20 * m_growIndex);

        if (tempHeight <= 20)
            Height = 20;
        else
            Height = tempHeight;

        m_timer.Enabled = false;
    }

    public override sealed bool AutoSize
    {
        get { return base.AutoSize; }
        set { base.AutoSize = value; }
    }

    protected override void OnTextChanged(EventArgs e)
    {
        base.OnTextChanged(e);
        m_timer.Enabled = true;
    }

    protected override void OnFontChanged(EventArgs e)
    {
        base.OnFontChanged(e);
        m_timer.Enabled = true;
    }

    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        m_timer.Enabled = true;
    }
}

This is obviously not quite working.  I have the panel set to AutoSize, but it is not growing to accomodate the second TextBox.  Also, I need to somehow push the second TextBox down when the first one grows.  Is there some good way for the panel to know when ExpandoField gets an OnSizeChanged event?  It seems like the growth of that panel would then need to cause the remainder of the list of panels to be redrawn in lower locations.  I'm not sure how to get this cascade effect to work right...
I also think the use of the timer seems like an inefficient kluge...
I'm still learning WinForms.  Is there some well-designed way I can get the behavior that I want?  Is there some event I can catch when the WordWrap takes place (or when the text exceeds the size of the TextBox)?  That would allow me to resize the TextBox.  And how does the TextBox let the panel know that it has changed?  Does it need to call the OnSizeChanged handler for it's parent panel?  Does the panel need to call the OnSizeChanged handler for it's parent list?
Any suggestions?

A: I believe I have the answer, after 3 or 4 failed attempts...
class ExpandoField : TextBox
{
    private bool UpdateInProgress = false;
    private static System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(@"\r\n");

    public delegate void CallbackFn();
    CallbackFn VSizeChangedCallback;

    public ExpandoField(CallbackFn VSizeChanged)
    {
        AutoSize = false;
        VSizeChangedCallback = VSizeChanged;

        this.KeyDown += new KeyEventHandler(ExpandoField_KeyDown);
    }

    public void ExpandoField_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
            this.SelectAll();
    }

    public void UpdateSize()
    {
        if (UpdateInProgress == false && Text.Length > 0)
        {
            UpdateInProgress = true;

            int numLines = 0;
            System.Drawing.Size baseSize = new System.Drawing.Size(Width, Int32.MaxValue);
            System.Drawing.Size lineSize = baseSize;  // compiler thinks we need something here...

            // replace CR/LF with single character (paragraph mark '¶')
            string tmpText = rgx.Replace(Text, "\u00B6");

            // split text at paragraph marks
            string[] parts = tmpText.Split(new char[1] { '\u00B6' });

            numLines = parts.Count();

            foreach (string part in parts)
            {
                // if the width of this line is greater than the width of the text box, add needed lines
                lineSize = TextRenderer.MeasureText(part, Font, baseSize, TextFormatFlags.TextBoxControl);
                numLines += (int) Math.Floor(((double) lineSize.Width / (double) Width));
            }

            if (numLines > 1)
                Multiline = true;
            else
                Multiline = false;

            int tempHeight = Margin.Top + (lineSize.Height * numLines) + Margin.Bottom;

            if (tempHeight > Height ||                 // need to grow...
                Height - tempHeight > lineSize.Height) // need to shrink...
            {
                Height = tempHeight;
                VSizeChangedCallback();
            }

            UpdateInProgress = false;
        }
    }

    public override sealed bool AutoSize
    {
        get { return base.AutoSize; }
        set { base.AutoSize = value; }
    }

    protected override void OnTextChanged(EventArgs e)
    {
        base.OnTextChanged(e);
        UpdateSize();
    }

    protected override void OnFontChanged(EventArgs e)
    {
        base.OnFontChanged(e);
        UpdateSize();
    }

    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        UpdateSize();
    }
}

Note that on the constructor this subclass of TextBox now accepts a delegate callback to let the parent class know that the TextBox has changed its size.  (I suppose I should have handled the possibility of a null value here...)
Thankfully, this solution no longer required a timer.
I have tested this code pretty well, and I have watched it both grow & shrink.  It respects MaximumSize, and it even handles the presence of carriage-return/line-feed pairs.  (This code assumes Windows; it should be trivial to modify it for Linux, etc.)  Feel free to suggest improvements.


text:
Q: Gradle error: Error:Error converting bytecode to dex: Cause: java.lang.RuntimeException: Exception parsing classes To start off, this is the whole message:

Error:Error converting bytecode to dex: Cause: java.lang.RuntimeException: Exception parsing classes
Error:1 error; aborting

Error:Execution failed for task
  ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: java.lang.RuntimeException:
    com.android.ide.common.process.ProcessException:
    java.util.concurrent.ExecutionException:
    com.android.ide.common.process.ProcessException:
    org.gradle.process.internal.ExecException: Process 'command
    'C:\Program Files\Java\jdk1.8.0_51\bin\java.exe'' finished with
    non-zero exit value 1

This is what I have tried:
Restarting AS.
Restaring my computer.
Tried invaldiate caches and restart.
Rebuilt the project serveral times.
Earlier today I installed that latest java update, but it did not affect anything. After a couple of hours of coding, I added a jar file to my libs folder and wrote a class that used some of the classes from that library.
Now I can't seem to build the application at all anymore, even if comment out the class that uses the dependency.
Using Android Studio 2.0, Java 1.8.0_91-b14 and the library mysql-connector-java-5.1.38-bin
Edit:
I just tried removing the jar file, and now it builds just fine. So that's the thing causing the problem. Now how to solve it...

A: I think you need to add the following line in your app's build.grade file
defaultConfig {
    ...
    multiDexEnabled true
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: More current in non-inverter comparator hysteresis using a photoresistor I'm doing a small circuit where I need automatic LED's to turn ON in a low light environment. So I decided to use a photoresistor (more light less resistance) connected to a non-inverter hysteresis comparator (I used hysteresis for a more controlled light detecting range) and in the OpAmp (TL084CN) output I connected the LEDs. The supply voltage in the IC(TL084CN) is +10V and -10V because I'm using a battery cell to make this circuit portable.
As you can see in the circuit diagram I connected 16 LEDs in parallel in the OpAmp output. The issue is: I connected only one LED at first and it was an OK brightness, I measured the current and it was about 23mA. Now you can imagine 23mA divided by 16 LEDs, the brightness is almost 0 (still brights but poorly).
I want to find a solution to give more current to the LEDs not disturbing the comparator circuit output.
PD: Forgot to mention that this circuit is connected to a 24.7V battery that is connected to a step-down circuit that outputs 10V and then to a voltage inverter to get that -10V to the supply voltage. The step-down I used has a 1A max output so maybe I need to get that current directly from the battery (I do not have another step-down)


text:
Q: Is it possible for me to write to Outlook using Excel and VBA Here is my dream; I have a master sheet in excel that contains 100 names and dates. I want to write a VBA code that will take those dates and times and throw them into a shared outlook calendar. Part 2 of the code would be to compare if the date was changed , if so delete previous event and make a new one. I also need it to be able to change the color of the event. If anyone can point me in a direction to start that would be awesome, thank you! Also I will have to look to see if excel macro recorder can record outlook events...

A: The Excel Macro recorder will not record anything outside of the current Excel instance. You can automate Outlook using VBA but you need to write the code yourself (or find some).
In the Excel VBA Editor, the first step is to choose the Tools menu, References and tick the Microsoft Outlook 14.0 Object Library (or 12.0 for Office 2007).
After ticking the reference, typical Outlook automation code might start like this:
Sub AutomateOutlook()
    Dim ol As Outlook.Application
    Dim ns As Outlook.Namespace
End Sub

Outlook Object Model Overview: MSDN
There are more restrictions with Outlook than other applications. You might want to research firstly whether you can write to a shared calendar. This social.msdn link is also relevant.


text:
Q: Parsing And Accessing Dom Elements From HTML Page Fetched Via Ajax XHR Get Request We are trying a access various DOM elements from full HTML pages that are remotely fetched via XHR GET request.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com/test.html", true);

xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    var newdom = xhr.responseText;
    var val_result = newdom.a_div.innerText;
    // we want to access the text within this div, from the fetched html page?
  }
}

xhr.send();

Any ideas?

A: Easily enough you could do this:
var xhr = new XMLHttpRequest()
xhr.open('GET', 'https://stackoverflow.com/questions/53661013/parsing-and-accessing-dom-elements-from-html-page-fetched-via-ajax-xhr-get-reque/53661204', true)

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    var dom = new DOMParser().parseFromString(xhr.responseText, 'text/html')
    console.log(dom.querySelector('#question-header h1').innerText)
  }
}

xhr.send()

If you copy this code as-is in your browser console, it will print the title of your StackOverflow question! Simply use the dom variable to query for the element you are looking for in.

A: You need to create an element with
const el=document.createElement('div')

then assign its innerhtml
el.innerHTML = newdom

Then you should be able to access the nodes


text:
Q: General advice for responsive margins on sections Im building a responsive site. It basically has <sections> that are stacked down the page. Broken up by <H1,H2> etc.
I was wondering  really what the best way to set the margins so sections and headers don't appear too close and bunched up. I have tried the following:

*

*set the margins using px and then write media queries to adjust as the screen get smaller

*set the margins using (em) I saw this approach on a video is this even recommended?

*set the margins using %'s. Again not sure if this is best?

Im getting to a point now where I need to refactor my CSS and make my decision going forward.
Any help much appreciated.
Pete

A: *

*mobile first media queries work the best at the moment as you always have less to do as screen size gets smaller,

so like
media screen and (min-width: 320px) {}
media screen and (min-width: 769px) {}

*

*dont use ems too much, they are relative to their parent layer and if you go too deep in cascading, it's impossible to track down, rem is supported by all browsers now i believe.

*

*% is good for setting width perhaps, i mean margins do not have to be smaller or larger with screen sizes too much i think, but rem with a backup px setting is the best i believe.

A: You have to look into viewport metadata:
<meta name="viewport" content="width=device-width, user-scalable=false;">

More on Mozilla Developers: https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag


text:
Q: how to redirect all pages to the root, without affecting css files? I changed the design of a site to a single-page design. Now I want all the requests for the previous pages to redirect to the homepage (domain.com).
I tried this:
RewriteRule ^.+$ / [R=302,NC,L]

but if I use it, my CSS files won't load!
any tips?

A: Add exceptions as conditions for that rule:
RewriteCond %{REQUEST_URI} !\.(png|jpe?g|gif|js|css)$ [NC]
RewriteRule ^.+$ / [R=302,NC,L]

So that it won't redirect images/css/scripts to the homepage.


text:
Q: vba : why click event is diffused on initialising? In excel, I have an userForm with checkBox dynamically created from a list
on initialize, I call a sub to affect a click event to my checkbox.
I have then a classmodule call MyEvents in wich I declare click event for check box.
Here is the class module MyEvents :
Option Explicit

Public WithEvents chkGroup As MSForms.CheckBox

Private Sub chkGroup_Click()
    Debug.Print "chkGroup_Click -----> " & chkGroup.Caption
End Sub

Here is the sub on userForm :
Private Sub initCheckBox(chanelList As Variant)

    Dim myEvent As MyEvents
    Dim chkBox As Collection
    Dim n As Long, j As Integer, i As Integer
    n = Application.CountA(chanelList)
    Dim checkBoxChanel() As MSForms.CheckBox
    ReDim checkBoxChanel(n) As MSForms.CheckBox
    n = 1
    j = 1
    i = 1
    Set chkBox = New Collection
    chkBoxNum = 0
    For Each chanel In chanelList
        Set myEvent = New MyEvents
        Set checkBoxChanel(n) = Frame1.Controls.Add("Forms.CheckBox.1", "chkBoxChanel" & n)
        Set myEvent.chkGroup = Frame1.Controls("chkBoxChanel" & n)
        chkBox.Add myEvent
        With checkBoxChanel(n)
            .Top = j
            .Left = i
            .Caption = chanel
            .AutoSize = True
            .Value = True
            .Enabled = False
        End With
        n = n + 1
        i = i + 80
        If n Mod 3 = 0 Then
            j = j + 20
            i = 1
        End If
    Next

End Sub

Can someone explain me why clickevent is diffused on initialising. Is it the normal behavior ?

A: okay, I've found the trick. Setting check box value to true is like clicking on check box ! to avoid this, I just have to affect event after setting value to true. Thanks to all for you comment and answers


text:
Q: How to Drawing Vertical Bezier in Processing? I have the following bezier shape:

The shape was achieved by the following code:
int width = 800; int height = 800;
int centerX = width/2; int centerY = height/2;
int lefterX = width/6; int upperY = height*5/6;
int righterX = width*5/6; int lowerY = height*5/6;

for (int y = 0; y <= height; y += 9) {
  bezier(lefterX, centerY,
    centerX, y,
    centerX, y,
    righterX, centerY);
}

Now, I want to make a vertical version of this. I wrote the following code:
for (int x = 0; x <= width; x += 9) {
  bezier(centerX, upperY,
    x, centerY,
    x, centerY,
    centerX, lowerY);
}

However, the outcome turns out incomplete, only rendering the bottom half:

What is missing from the code?

A: The issue is upperY and lowerY have the same value:
int upperY = height*5/6;
int lowerY = height*5/6;

You probably meant:
int upperY = height/6;

Here's what I mean:
int centerX,centerY;
int lefterX,righterX;
int upperY,lowerY;

void setup(){
  size(800,600);
  noFill();
  centerX = width/2;
  centerY = height/2;

  lefterX = width/6;
  righterX = width*5/6;
  upperY = height/6;//height*5/6;
  lowerY = height*5/6;
}

void draw(){
  background(255);

  for (int y = 0; y <= height; y += 9) {
    bezier(lefterX, centerY,
      centerX, y,
      centerX, y,
      righterX, centerY);
  }

  for (int x = lefterX; x <= righterX; x += 9) {
    bezier(centerX, upperY,
      x, centerY,
      x, centerY,
      centerX, lowerY);
  }

}
void mouseDragged(){
  ellipse(mouseX,mouseY,10,10);
  if(keyPressed){
    if(key == 'l') lefterX = mouseX;
    if(key == 'r') righterX = mouseX;
    if(key == 't') upperY = mouseY;
    if(key == 'b') lowerY = mouseY;
  }
}

You can hold l for left, r for right, t for top, b for bottom and drag to adjust values. Running the demo bellow and using either t/b keys and dragging one side on top of the other will reproduce your problem:

var centerX,centerY;
var lefterX,righterX;
var upperY,lowerY;

function setup(){
  createCanvas(800,600);
  noFill();
  centerX = width/2;
  centerY = height/2;

  lefterX = width/6;
  righterX = width*5/6;
  upperY = height/6;//height*5/6;
  lowerY = height*5/6;
}

function draw(){
  background(255);

  for (var y = 0; y <= height; y += 9) {
    bezier(lefterX, centerY,
      centerX, y,
      centerX, y,
      righterX, centerY);
  }

  for (var x = lefterX; x <= righterX; x += 9) {
    bezier(centerX, upperY,
      x, centerY,
      x, centerY,
      centerX, lowerY);
  }

}
function mouseDragged(){
  if(keyIsPressed) {
    if(key == 'l' || key == 'L') lefterX = mouseX;
    if(key == 'r' || key == 'R') righterX = mouseX;
    if(key == 't' || key == 'T') upperY = mouseY;
    if(key == 'b' || key == 'B') lowerY = mouseY;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.0/p5.min.js"></script>

A: Don't: just rotate your coordinate space around the center of the screen by a quarter circle, and then draw the exact same thing, so it looks vertical.
int right, top;

// remember to use setup()
void setup() {
  size(800,800);
  noLoop();
  noFill();
  right = width/2;
  top = height/3;
}

void drawYourStuff() {
  for (int y = -top; y <= top; y += 10) {
    // the center is (0,0), so we don't need
    // complicated center computations.
    bezier(-right,0, 0,y, 0,y, right,0);
  }
}

void draw() {
  // change the coordinate system so that
  // (0,0) is the center of the screen.
  translate(width/2,height/2);
  drawYourStuff();
  // rotate the entire coordinate system
  // by a quarter turn, scale it down, redraw:
  rotate(-PI/2);
  scale(0.5);
  drawYourStuff();
  // done.
}

And you're done. A solution using four lines of code. Although a little more because in order to follow proper Processing conventions you need to rewrite that code of yours a little bit to use setup and draw, and have your variables live in a sensible place =)


text:
Q: Override Django Password Reset I was able to set up a Custom User using AbstractUser.
I'm trying to find a way to use Django's Password Reset Class to reset my users. So I implemented it the way it is normally used but I get the following error:
ProgrammingError: column app_user.date_joined does not exist

or
app_user.is_active does not exist

I shouldn't have to add any of these fields to my AbstractUser and I'm sure there is a way to override the Django auth. Does anyone know how?
EDIT: I've already migrated all my databases.

A: Your database is not migrated.
You have to run python manage.py migrate to migrate the DB.
If that was never run, than you have to make the migrations before applying them.
python manage.py makemigrations
python manage.py migrate


text:
Q: What connection should I enter for USB printer? (HPLIP) I am trying to add a HP LaserJet 1320N printer to CUPS. The printer is connected by USB. in the CUPS web admin interface, I selected HPLIP, then on the next page I have to enter Connection. According to HPLIP documentation for connection by USB: You MUST make a selection from the drop down that appears such as "hp:/usb/hp_deskjet_5600?serial=MY31R1K02179".
However there is no dropdown, only a freeform text entry field. So I made a guess and entered hp:/usb/laserjet, but communication with the printer doesn't work.
What should I enter for Connection?
I am running Debian 3.2 with the Lynx text browser on the command line.

A: By looking at /etc/cups/printers.conf, I found out that connection refers to DeviceURI. HPLIP provides a tool to obtain that:

*

*Connect printer by USB.

*Get bus and device ID:
$ lsusb
[...]
Bus 003 Device 005: ID 03f0:1d17 Hewlett-Packard LaserJet 1320

*Get URI:
$ hp-mkuri -b 003 -d 005
hp:/usb/hp_LaserJet_1320_series?serial=00CNHW69TGWQ
[...]


text:
Q: How do I translate or strip character sequences like "\xC2\xBB" in my strings? How do I translate or strip character sequences like "\xC2\xBB" in my strings in Ruby 1.9.2?

A: You will usually see hex bytes like that when the string is using an encoding that does not handle those bytes. If you know what encoding the string is supposed to be using, you can use String#force_encoding to re-interpret the bytes according to your desired encoding.
# Under a UTF-8 locale:
ruby-1.9.2-head :013 > "\xC2\xBB".force_encoding(Encoding::UTF_8)
 => "»"

# Under the "C" locale:
ruby-1.9.2-head :007 > "\xC2\xBB".force_encoding(Encoding::UTF_8)
 => "\u00BB"

Both result in the same UTF-8 encoded string internally. When under the C locale, Ruby prints an escaped version to avoid printing binary data to the terminal (which, according to the locale setting, might not support it).
If the string is already using the appropriate encoding, then you should re-encode the string to your desired output encoding before using it:
# Under a UTF-8 locale:
ruby-1.9.2-head :026 > "\xC2\xBB".force_encoding(Encoding::ISO_8859_1).encode(Encoding::UTF_8)
 => "»"

# Under the "C" locale:
ruby-1.9.2-head :014 > "\xC2\xBB".force_encoding(Encoding::ISO_8859_1).encode(Encoding::UTF_8)
 => "\u00C2\u00BB"

Above, I use String#force_encoding to make sure the bytes in the string are are flagged as ISO 8859-1 (because, for instance, a header accompanying the bytes said that they represented an ISO 8859-1 encoded string) and then use String#encode re-encode it as UTF-8 (the desired output encoding).
Finally, if you really just want to strip out anything that is not ASCII, you could use the negated [:ascii:] character class with String#gsub:
ruby-1.9.2-head :030 > "foo\xC2\xBBbar".force_encoding(Encoding::UTF_8).gsub(/[[:^ascii:]]/,'')
 => "foobar"


text:
Q: OData Authentication without site URL We are currently in the process of developing a range of SharePoint applications which will have mobile apps alongside them which connect to the SharePoint site.
We are having a few issues getting authentication to work on the mobile (iOS) side of things to work.
In development we have been able to define our own SharePoint Online URL for user authentication but in an actual release this wouldn't work since each user will have their own AD in their own Office 365 tenancy (which also means a different SP site URL).
Ideally we don't want to have to make users enter the site URL (although this is an option if needed). The applications are SharePoint Online only if that makes a difference.
Is there anyway that we can have the user login with their Office 365 credentials, then get their original office 365 domain (xxxx.sharepoint.com) returned or something similar?
Ideally we want a user to be able to pick up their phone, login with their Office 365 credentials on the application and then have the application connect to their SharePoint Online deployment automatically.
Thanks,
Ben

A:
we can have the user login with their Office 365 credentials

No, until user hand them to you himself.

then get their original office 365 domain (xxxx.sharepoint.com)
  returned or something similar?

Create a remote event receiver, so when an app is installed, it will return with host web URL, which can be done using an hidden app part (maybe) or somehow.
Remote Event receiver for Apps
Note:
Remote Event receiver will only work with auto-host apps (As far as I know).
You might want to change logic of your app, as you should develop an auto hosted app, which web services or site hosted on window azure (which is free, I guess if you are Microsoft partner) and then get details from Azure, e.g. then your app will contact windows azure for data operations, if I make any sense.


text:
Q: puppeteer chromium url redirects to malware I have a node.js (v12.17.0) npm (6.14.4) project I am running on my Windows 10 command prompt. It is using puppeteer ("puppeteer": "^5.3.1",) to go to a url and get info.
My puppeteer code runs this to go to the page:
let targetURL = "https://www.walmart.com/ip/Small-Large-Dogs-Muzzle-Anti-Stop-Bite-Barking-Chewing-Mesh-Mask-Training-S-XXL/449423974";
                await page.goto(targetURL, { waitUntil: 'networkidle2' });

And my puppeteer is running a chromium exe I just downloaded, I specify it's locating when I start puppeteer:
 var options = {
        executablePath: "C:\\Users\\marti\\Downloads\\chrome-win-new\\chrome-win\\chrome.exe",

So when puppeteer stars and goes to that URL, it loads the walmart page at first and seems fine, then a couple of seconds later the page looks like this:

I ran windows defender and malware antibytes to double check if i had a virus, I checked and if i open chromium without puppeteer it doesnt redirect, only seems to happen in my node js program when I run it.
I tried using  a different url (https://www.petcarerx.com/chicken-soup-for-the-soul-bacon-and-cheese-crunchy-bites-dog-treats/32928?sku=50857#50857) and it did not redirect, does anyone know how i can fix this for my Walmart url?


text:
Q: Sharepoint 2010 2 columns showing up in list from a content type I have a content type with about 20 fields
Everything was fine until I added a hyperlink field called "MySite". When I get to the list instance and add a new item -> low and behold there are 2 "MySite" hyperlink fields instead of just one.
I'm using a content type ref in the list schema not manually adding columns.
Any idea why this is happening and how to fix it?

A: Its one of those strange bugs I couldn't find a scientific fix for.
Just redeployed the solution a few times and retracted it, after about 3 attempts without changing code it fixed itself.


text:
Q: write json to a file using jQuery and Ajax and PHP I'm trying to write a json file based upon a filled in Form
So I used an external Library for jquery that converts the Form into legitimate JSON.
When I console.log that output I do get a valid json data returned.
So whenever I pass the data into a php using $.ajax and write the content to a file
the PHP saves the file but the inside it just says "NULL"
here is my AJAX:
$(document).ready(function() {
    var json = $("#user-form").serializeJSON();
    $.ajax({
        url: "writejson.php",
        type: "POST",
        data: json,
        processData: false,
        contentType: 'application/json'
    });
})

And here is my PHP:
<?php
    $myFile = "kiosk.json";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh,var_export($_POST['data'], true));
    fclose($fh);
?>

and here is what the outputted file says:
NULL

I tried looking it up here first and tried numerous options but none of them seem to save the correct data.
really strange.
Thanks in advance!

A: You could always change your json string from this
 var json = $("#user-form").serializeJSON();

to this
 var json = {data: $("#user-form").serializeJSON()};

That way when you try to retrieve $_POST['data'], it will actually be set because you defined it.
EDIT: Important point by Shuyinsama - pointed out that you have to use the JSON.stringify method on JSON objects before posting them to PHP:

In my case this is what I did:
var jsontext = JSON.stringify($("#user-form").serializeJSON());

var json = {data: jsontext};

and then use the first PHP file to write it into a valid JSON file.

And always remember you can use the json_decode(); within PHP if you ever need to do some processing on your JSON data, and json_encode();, respectively.

A: Unless there's a post variable called "data", this will return null.  You might want to try http_get_request_body()


text:
Q: translation does not work with text_domain I am trying to translate my custom plugin.
I can translate my plugin if I place the fr_CA.po/.mo into my
wp-content\languages\plugins manually.
But I would like to be able to put my .po/.mo into my plugins folder in "myplugin/languages"
Well, in the main file, I have this:
 * Text Domain: myplugin
 * Domain Path: /languages/

my text
    add_action( 'init', 'myplugin_load_textdomain' );

function myplugin_load_textdomain() {
    load_plugin_textdomain( 'myplugin', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}

all my .po / .mo is in that folder myplugin/languages/
My Wordpress is in fr_CA ( WordPress 4.7.2–fr_CA)
I have a fr_FR.po /fr_CA.po (and their .mo).

Like I said previously, my plugin change the language if I put my .po/.mo into the wp-content\languages\plugins and I change the fr_FR(.mo/.po) to myplugin-fr_FR(.mo/.po)
but I would like to keep my .po/.mo into my plugins folder.
Anyone know what is the problem?

A: From the source code of load_plugin_textdomain it becomes appararent that the function will first look for $domain . '-' . $locale . '.mo' (so, that's myplugin-fr_FR.mo) in WP_LANG_DIR . '/plugins/' . $mofile.
Only when the file is not there, it will start looking at the specified path and if it is not there in the main plugin directory. So, if you don't get the mo-file in the specified directory, either it isn't there or you are supplying the wrong path.
I cannot see whether you have made any typos, but instead of combining dirname and plugin_basename you might want to stick to plugin_dir_path to supply the correct directory.


text:
Q: Xamarin.Android SQLite SQLiteConnection.Insert does not return inserted object's ID I'm very new to Xamarin and C# and trying to insert some sample data to my simple recipe database for testing purpourses.
However, when inserting a new recipe, the SQLiteConnection.Insert(data) does not return the ID of the inserted record as it should (see here), but instead returns 1 every time.
My insert data method:
public static int insertUpdate(Object data) {
        string path = DB.pathToDatabase ();
        DB.createDatabase ();
        try {
            var db = new SQLiteConnection(path);
            int inserted = db.Insert(data);
            if (inserted != 0)
                inserted = db.Update(data);
            return inserted;
        }
        catch (SQLiteException ex) {
            return -1;
        }
    }

Inserting the sample data:
        int stand = insertUpdate (new Recipe {
            Name = "Standard",
            Author = "Aeropress Nerd",
            Description = "The perfect recipe for your first cup",
            Type = "Default"
        });

        insertUpdate (new Step { Action = "Pour", Duration = 10, Recipe = stand });
        insertUpdate (new Step { Action = "Stir", Duration = 20, Recipe = stand });
        insertUpdate (new Step { Action = "Steep", Duration = 15, Recipe = stand });

        int inv = insertUpdate (new Recipe {
            Name = "Inverted",
            Author = "Aeropress Nerd",
            Description = "A more advanced brew using the inverted method.",
            Type = "Default"
        });

I cannot figure out what I am doing wrong. Thanks in advance for any help and sorry for the (probably) stupid question.

A:
However, when inserting a new recipe, the SQLiteConnection.Insert(data) does not return the ID of the inserted record as it should (see here), but instead returns 1 every time.

I am pretty sure you downloaded some nuget package or component to include SQLite functionality to your Xamarin.Android App and it may be slightly different from the native implementation. Then, you should refer to the specific documentation for whatever it is that you're using on Xamarin.
My wild guess is that you are using this component. If I'm wrong, please comment to correct my answer. If I'm right, you should try this:
The object you want to insert
class Row
{
   public int Id { get; set; }
}

class Recipe : Row
{
    //Recipe's properties
}

class Step : Row
{
    //Step's properties
}

The insertUpdate method definition
public static int insertUpdate(Row data) {
    string path = DB.pathToDatabase ();
    DB.createDatabase ();
    try {
        var db = new SQLiteConnection(path);
        int inserted = db.Insert(data); //will be 1 if successful
        if (inserted > 0)
            return data.Id; //Acording to the documentation for the SQLIte component, the Insert method updates the id by reference
        return inserted;
    }
    catch (SQLiteException ex) {
        return -1;
    }
}

The insertUpdate method usage
 //As Step and Recipe both are derived classed from Row, you should be able to use insertUpdate indistinctively and without casting

    insertUpdate (new Step { Action = "Steep", Duration = 15, Recipe = stand });

    int inv = insertUpdate (new Recipe {
        Name = "Inverted",
        Author = "Aeropress Nerd",
        Description = "A more advanced brew using the inverted method.",
        Type = "Default"
    });

A: why after inserting data to your db, you starting to update it by the same object right away. This code most likely redundant.
if (inserted != 0)
  inserted = db.Update(data);
return inserted;


text:
Q: Accessibility Issue in selected Devices The following snippet unable to deduct by the samsung edge device accessibility.

Can you suggest me what went wrong as well as what is the best way to test across multiple device variants.

text: Sample text

Raja K


text:
Q: java swing displays incorrectly - squares covering content My problem is difficult to describe in words, but I have no reputation to post image :(. I have strange squares on my JOptionPanel, they are moving while I'm typing. What is more curious for me the same code works fine on other computers.
It is the code:
String inputValue = JOptionPane.showInputDialog("Please write, what does " +
      res.get(0).getZ1() + " means ?");

It is the only one place where I need swing, so I think all code is useless, and it is something wrong with my computer, but dont know what.

I have Win8.1 and I use Eclipse, if you need any other informations please ask.
My video card is: Intel R HD Graphics 4000


text:
Q: Wrong Answer while implementing queues -reference binding to null pointer of type I was solving this problem on codeforces : Lose it! when I submitted and got a WA(wrong answer) on test case 6.
The Problem: Remove minimal number of elements from an array such that the array is composed of {4,8,15,16,23,42} and in order. To read the problem in detail, please refer to the link.
My Code:
#include <iostream>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;

#define rep(i,a,b) for(auto (i)=a;i<b;i++)
#define list(i,N) for(auto (i)=0;i<N;i++)

typedef long long ll;

int indexOf(int element, int array[], int N){
    list(i,N){
        if(array[i]==element) return i;
    }
    return -1;
}

int main(){

    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int N; cin >> N;
    int array[N];
    int counter = 0;
    int elements[6] = {4,8,15,16,23,42};
    list(i,N){ cin >> array[i]; }
    int len = N;
    int rem = len%6;
    int quo = len/6;
    //an array of queues
    queue<int> removals[quo];
    //initialize the removals array
    list(i,quo){ list(j,6) removals[i].push(elements[j]); }

    list(i,len){
        int tops[quo];
        list(j,quo){
            if(removals[j].empty()) tops[j] = -10;
            else tops[j] = removals[j].front();
        }
        int idx = indexOf(array[i],tops,quo);

        if(idx==-1){ counter++; /*cout << "Incrementing Counter at " << i << "!\n";*/ }
        else removals[idx].pop();
    }

    cout << counter;
    return 0;
}

Approach:
Basically, what I am doing is to maintain an array of queues. As we iterate through the elements in the array, we check which queue has the element on top and pop it. If not found on the top of any queue, increase the counter by 1.
The Problem:
So, I submitted my code and found out that it failed on:
100
4 42 23 23 8 42 16 23 42 16 42 8 4 23 4 4 23 42 16 42 23 23 23 42 4 42 8 8 16 23 15 23 16 4 42 15 15 23 16 15 16 4 4 15 23 42 42 15 8 23 8 23 4 15 16 15 42 8 23 16 15 42 23 8 4 16 15 16 23 16 16 4 23 16 8 23 16 15 23 4 4 8 15 4 4 15 8 23 23 4 4 8 8 4 42 15 4 4 42 16
giving the answer of 41 instead of the correct answer 64. I tried to find out where the error is, but unforunately, the test size is too long. What is possibly wrong in this code?
What it says
Diagnostics detected issues [cpp.clang++-diagnose]: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\include\deque:329:10: runtime error: reference binding to null pointer of type 'const long long'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\include\deque:329:10 in

The above is what the diagnostics say. I checked online for what it meant, and it is something related to the size of a vector but I have not used vectors anywhere. Moreover, if there was a big fault, I would not have passes test cases 1-5. I think there is an error directly related to the above test cases.
Any help would be appreciated.
Thanks!
EDIT: Thanks to Igor Tandetnik, the diagnostics is now gone. I had forgotten to put an else statement. But still, my code gets WA. Any suggestions?


text:
Q: Register page not inserting into my database anymore I got this code from an online source and it was working fine but when I tried using today it logs the user into the website but doesn't insert anything into the table. So if I log out of the newly created account then try to sign in it wont work.
My data connection page is server.php. register page is register.php
I looked over for self error. I even re copied the code from online into it and replaced with data connection info and still doing the same thing.I thought maybe it was my server.php but all the user accounts in the table still work so it isn't the server.pgp page.
Register.php
<!DOCTYPE html>

  <title>Registration system PHP and MySQL</title>
  <link rel="stylesheet" type="text/css" href="style.css">

Register

  <form method="post" action="register.php">
    <?php include('errors.php'); ?>

      Username
      <input type="text" name="username" value="<?php echo $username; ?>">

      Email
      <input type="email" name="email" value="<?php echo $email; ?>">

      Password
      <input type="password" name="password_1">

      Confirm password
      <input type="password" name="password_2">

      <button type="submit" class="btn" name="reg_user">Register</button>

        Already a member? Sign in

  </form>

Server.php

// initializing variables
$username = "";
$email    = "";
$errors = array();

// connect to the database

$db = mysqli_connect(REMOVED FOR PUBLIC VIEWING);

// REGISTER USER
if (isset($_POST['reg_user'])) {
  // receive all input values from the form
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  if (empty($username)) { array_push($errors, "Username is required"); }
  if (empty($email)) { array_push($errors, "Email is required"); }
  if (empty($password_1)) { array_push($errors, "Password is required"); }
  if ($password_1 != $password_2) {
    array_push($errors, "The two passwords do not match");
  }

  // first check the database to make sure
  // a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);

  if ($user) { // if user exists
    if ($user['username'] === $username) {
      array_push($errors, "Username already exists");
    }

    if ($user['email'] === $email) {
      array_push($errors, "email already exists");
    }
  }

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    $password = md5($password_1);//encrypt the password before saving in the database

    $query = "INSERT INTO users (username, email, password)
              VALUES('$username', '$email', '$password')";
    mysqli_query($db, $query);
    $_SESSION['username'] = $username;
    $_SESSION['success'] = "You are now logged in";
    header('location: index.php');
  }
}

This should result in the user being created and logged in automatically which is what it does. It doesn't insert into the database like it should.Should insert
id
Username
Email
Encrypted Password

A: From the code posted, it looks like the form in register.php is posting to itself, not to server.php.
Maybe change
<form method="post" action="register.php">

to
<form method="post" action="server.php">

[Aside, definitely consider the comments made by @magnus-eriksson, which aren't directly related to the question, but are very relevant]

A: Server.php
Check if you actually don't have any errors in $error
and what are errors when inserting by mysqli
an example how to do that:
<?php

// initializing variables
$username = "";
$email    = "";
$errors = array();

// connect to the database

$db = mysqli_connect('REMOVED FOR PUBLIC VIEWING');

// REGISTER USER
if (isset($_POST['reg_user'])) {
  // receive all input values from the form
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  if (empty($username)) { array_push($errors, "Username is required"); }
  if (empty($email)) { array_push($errors, "Email is required"); }
  if (empty($password_1)) { array_push($errors, "Password is required"); }
  if ($password_1 != $password_2) {
    array_push($errors, "The two passwords do not match");
  }

  // first check the database to make sure
  // a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);

  if ($user) { // if user exists
    if ($user['username'] === $username) {
      array_push($errors, "Username already exists");
    }

    if ($user['email'] === $email) {
      array_push($errors, "email already exists");
    }
  }

echo "\nThere should be no errors here\n";
var_dump($errors);

if (count($errors)) {
    die('There ware errors!');
}

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    $password = md5($password_1);//encrypt the password before saving in the database

    $query = "INSERT INTO users (username, email, password)
              VALUES('$username', '$email', '$password')";

    if(!mysqli_query($db, $query)) {
        die("Mysqli error: " . mysqli_error($db));
    }

    $_SESSION['username'] = $username;
    $_SESSION['success'] = "You are now logged in";
    header('location: index.php');

  }
}

Once you got it working:
read about PDO and MySQL injection and rewrite your mysql code by using PDO


text:
Q: importing scripts in html: sjcl.hash.sha512 is undefined I wrote an .html file to test importing stuff from another file. The file structure looks like this:
test(is a folder)
ㄴasdf.html
ㄴlib(is a folder)
---ㄴsjcl.js
asdf.html looks like this:
<!DOCTYPE html>

        <title>form test</title>

        <form action="" method="POST" onsubmit="sjcl.hash.sha512.hash(document.getElementsByName('normaltext')[0].value);">

input password.

            <input type="text" name="normaltext" value="">
            <input type="submit" value="submit">
        </form>

As for sjcl.js, I copy-pasted the contents here(http://bitwiseshiftleft.github.io/sjcl/sjcl.js) into the file lib/sjcl.js.
When I open asdf.html on Firefox, type something in the text box and click "submit", the console says "sjcl.hash.sha512 is undefined", even though it is clearly defined in the sjcl.js file.
I am inclined to think that this is not a problem with sjcl.js, but instead I messed up somewhere along the lines.
What can I do to make sure that the sha512 hash value of what I submit is printed on the console?

A: The particular version of the sjcl library that you're using doesn't have the code for sha512.
It looks like the developer hasn't updated the compiled package to match the current source code. You'll need to download and compile the repository yourself or use a different library in order to have that functionality. You might also submit an issue to encourage the developer to update the compiled library.


text:
Q: Postfix + Dovecot fatal: no SASL authentication mechanisms When I try to login via telnet I am getting kicked out immediately:
telnet localhost 25
Trying ::1...
Connected to localhost.localdomain.
Escape character is '^]'.
Connection closed by foreign host.

In the logs I get the following error message:
Jul 17 23:15:26 mail postfix/smtpd[1606]: connect from localhost[::1]
Jul 17 23:15:26 mail postfix/smtpd[1606]: fatal: no SASL authentication mechanisms
Jul 17 23:15:27 mail postfix/master[597]: warning: process /usr/lib/postfix/smtpd pid 1606 exit status 1
Jul 17 23:15:27 mail postfix/master[597]: warning: /usr/lib/postfix/smtpd: bad command startup -- throttling

I am getting the same error message too, when a MTA from outside wants to deliver a mail.
My 10-master.conf:
# Postfix smtp-auth
unix_listener /var/spool/postfix/private/auth {
mode = 0666

}

Auth seems to exist:
ls -l /var/spool/postfix/private/auth
srw-rw-rw- 1 root root 0 Jul 17 22:55 /var/spool/postfix/private/auth

And last but not least my postconf -n:
postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
broken_sasl_auth_clients = yes
config_directory = /etc/postfix
inet_interfaces = all
mailbox_size_limit = 0
mydestination = XXX, localhost.XXX, localhost, $mydomain
myhostname = XXX
mynetworks_style = subnet
myorigin = /etc/mailname
readme_directory = no
recipient_delimiter = +
relay_domains = hash:/etc/postfix/relay_domains
relayhost = XXX
smtp_generic_maps = hash:/etc/postfix/generic
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sender_dependent_authentication = yes
smtp_tls_security_level = may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtp_use_tls = yes
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous, noplaintext
smtpd_sasl_tls_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes
transport_maps = hash:/etc/postfix/transport, $relay_domains
virtual_alias_domains = hash:/etc/postfix/virtual_domains
virtual_alias_maps = hash:/etc/postfix/virtual_maps

Did I make a mistake somewhere? If not, how can I debug any further?
Thank you very much in advance (:
EDIT:
my 10-auth.conf:
disable_plaintext_auth = yes
auth_username_format = %Ln
auth_mechanisms = plain login
!include auth-ldap.conf.ext

A: Do you have an auth_mechanisms line in your dovecot configuration?
If so, post it, if not that's probably the issue.
default for reference:
auth_mechanisms = plain login
But you're probably going to want something else because of your postfix sasl security options, both plaintext and login are considered plaintext.
More: http://wiki2.dovecot.org/Authentication/Mechanisms


text:
Q: Searching in a large html list with more than 6000 list items I have a large html list in the below format. The html page size is 6 mb and there are more than 6000 list items. I want to add search and sorting functionality to it. I tried list.js, it is working perfectly with less list items but when I am loading it with the 6 MB html list the browser is crashing and taking around 3 to 4 minutes for first load offline. How can I add search in this large list ?

   content from list one

   content from list two

   content from list three

   content from list four

A: Cache all items into an object first:
var abbrs = {};

$("ul#abbreviations li").each(function (i) {
    abbrs[this.firstChild.nodeValue] = this;
});

Then look for the typed text in your object:
var li = abbrs[this.value.toUpperCase()];
// show li, hide others

Update: For partial matches, you'd have to iterate through the collection:
var filterBy = this.value.toUpperCase();

for (var abbr in abbrs) {
    if (abbr.indexOf(filterBy) !== -1) {
        var li = abbrs[abbr];
        // show li
    }
}


text:
Q: Which is the shortest way to integrate something like $\int\left(\frac{dv}{g-\frac{k}{m} v^2}\right)$? I know that it can be integrated by trigonometrical substitution but I wonder if there is a shortest or easiest way
$\int\left(\dfrac{dv}{g-\frac{k}{m} v^2}\right)$, where $g, k , m$ are positive constant values.

A: $$I=\int\dfrac{dv}{g-\frac{k}{m} v^2}=\dfrac 1 g\int\dfrac{dv}{1-\frac{k}{gm} v^2}$$
Now use arctan function for $\frac{k}{gm}<0$ ( change of variable). Otherwise use fraction decomposition and the log function.

A: For $\frac{gm}{k}>0$, substitute $v=\sqrt{\frac {gm}k}\sin\theta\implies dv=\sqrt{\frac {gm}k}\cos\theta d\theta$ $$\int\dfrac{dv}{g-\frac{k}{m} v^2}=\int\dfrac{\sqrt{\frac {gm}k}\cos\theta d\theta}{g-\frac{k}{m} \left(\sqrt{\frac {gm}k}\sin\theta\right)^2}$$
$$=\sqrt{\frac {gm}k}\int\dfrac{\cos\theta d\theta}{g\cos^2\theta}$$
$$=\sqrt{\frac {m}{gk}}\int\sec\theta\ d\theta$$
$$=\sqrt{\frac {m}{gk}}\ln|\sec\theta+\tan\theta|+C$$


text:
Q: add svg element at runtime in angular with 2 way data binding I want to add svg element line at runtime with ng-attr-x1={{some scope varaible}}.
I tried 2 ways:
In 1 way I tried with $compile:
var g=angular.element(document.createElementNS("http://www.w3.org/2000/svg", "g"));
var line=$compile('<line ng-attr-x1={{$scope.array[array.length-1].x1}} ng-attr-y1={{$scope.array[array.length-1].y1}} ng-attr-x1={{$scope.array[array.length-1].x2}} ng-attr-x1={{$scope.array[array.length-1].y2}} style="with mandatory styling for line">')($scope);
g.append(line);
parentg.append(g);

In this method line is not showing and g is showing with 0px height and width.
In a 2 way I treid like :
var line=angular.element(document.createElementNS("http://www.w3.org/2000/svg", "line"));
line.attr('ng-attr-x1','scopeVariable');
line.attr('ng-attr-x2','scopeVariable');
line.attr('ng-attr-y1','scopeVariable');
line.attr('ng-attr-Y2','scopeVariable');

In this ng-attr attributes does not resolved to x and y. In DOM it shows as

A: This is possibly coming in way too late to help you, but I was stuck for a little while on the same question.
Turns out that $compile can take an element created with document.createElementNS() - like this:

var actApp = angular.module('actApp', []);

actApp.controller('shapeController', ['$scope', '$compile',
  function shapeController($scope, $compile) {
    $scope.color = 'green';

    var svgEle = $(document.getElementById('mySvgElement'));

    var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');

    line.setAttribute('x1', '0');
    line.setAttribute('x2', '0');
    line.setAttribute('x2', '20');
    line.setAttribute('y2', '20');

    line.setAttribute('style', 'stroke: {{color}};');

    svgEle.append($compile(line)($scope));
  }
]);

  <input type="button" ng-click="color='blue'" value="To blue" />

  <svg id="mySvgElement" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">

  </svg>

Hope this saves someone a little bit of time in the future.


text:
Q: How to Set Pagination Align Center using Angular How to Set Pagination Align Center using Angular ? I have added css for pagination too.
I had tried some styles but that are not effecting.
(1)  justify-content-center class (2) class="pagination justify-content-center"
But none of them working. Please suggest some other designs if possible.

                _id
                Autodesk Material Description
                Autodesk SAP Material Description

                    {{pricedata['_id']}}

                    {{pricedata['Autodesk Material Description']}}

                    {{pricedata['Autodesk SAP Material Description']}}

            <pagination-controls (pageChange)="pages = $event" style="width:100px"></pagination-controls>


text:
Q: Laravel-websocket: Apache + Vue + Laravel Tengo el siguiente inconveniente. Tengo una aplicación desacoplada. El frontend por un lado y el socket por el otro. El siguiente problema es que mi socket funciona solo en local y no sé cómo hacerlo funcionar en un hosting compartido. Instalé el paquete laravel-websocket y mi backend está hecho en laravel y mi frontend en vuejs.
Esta es mi configuración en el config/broadcasting.php
'pusher'                  => [
        'driver'                 => 'pusher',
        'key'                    => env('PUSHER_APP_KEY'),
        'secret'                 => env('PUSHER_APP_SECRET'),
        'app_id'                 => env('PUSHER_APP_ID'),
        'options'                => [
            'cluster'               => env('PUSHER_APP_CLUSTER'),
            'useTLS'                => true,
            'encrypted'             => true,
            'host'                  => 'backtotal.test',
            'port'                  => 6001,
            'scheme'                => 'https',
            'curl_options'          => [
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
            ]
        ],
    ],

Esta es mi configuración en el config/websocket.php
'ssl' => [
    'local_cert' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT', null),

    'local_pk' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),

    'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),

    'verify_peer' => false,

    'allow_self_signed' => true,
],

Variables en el archivo .env para los certificados:
LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT=/etc/ssl/certs/backtotal.crt
LARAVEL_WEBSOCKETS_SSL_LOCAL_PK=/etc/ssl/private/backtotal.key

Este es mi mi main.js en mi aplicación vuejs:
import Echo from 'laravel-echo';

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: '***************',
    cluster: 'tls',
    forceTLS: true,
    wsHost: 'backtotal.test',
    wssPort: 6001,
    wsPort: 6001,
    scheme: 'https',
    authEndpoint: `${config.url}/broadcasting/auth`,
    enabledTransports: ['ws', 'wss'],
    encrypted: false,
    auth: {
      headers: {
        "Authorization": "Bearer " + token
      }
    }
});

He tratado de seguir este ejemplo que me encontré Laravel + Nuxt + Nginx
Pero siempre me muestra este error cuando lo monto en producción

Si alguien me pudiera ayudar o guiar, le agradecería mucho su ayuda.
ACTUALIZACIÓN
He leído que necesito hacer un ProxyReverse para que mi socket tenga salida por un puerto con ssl. Estos han sido los intentos de crear un ProxyReverse desde Apache y continuo sin poder acoplar mi socket con mi frontend con ssl:
INTENTO 1:
<VirtualHost *:443>
    <Proxy *>
        Require all granted
        Allow from all
    </Proxy>

    SSLEngine on
    SSLProxyEngine on
    SSLProxyVerify none
    SSLProxyCheckPeerCN off
    SSLProxyCheckPeerName off
    SSLProxyCheckPeerExpire off

    RewriteEngine on
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule .* wss://127.0.0.1:6001%{REQUEST_URI} [P]
    ProxyPass / ws://127.0.0.1:6001
    ProxyPassReverse / ws://127.0.0.1:6001

    SSLCertificateFile /etc/ssl/certs/websocket.crt
    SSLCertificateKeyFile /etc/ssl/private/websocket.key
</VirtualHost>

INTENTO 2:
<VirtualHost *:443>
    Include /etc/apache2/default-ssl.conf

    ServerName websocket.test
    ServerAlias *.websocket.test
    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/backtotal.crt
    SSLCertificateKeyFile /etc/ssl/private/backtotal.key

    RewriteEngine On
    RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
    RewriteCond %{QUERY_STRING} transport=websocket    [NC]
    RewriteRule /(.*)           ws://localhost:6001/$1 [P,L]

    ProxyPass / http://localhost:6001/
    ProxyPassReverse / http://localhost:6001/
</VirtualHost>

INTENTO 3:
<VirtualHost *:443>
    DocumentRoot /var/www/html/tastytotal/public

    <Directory /var/www/html/tastytotal/public>
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>

    ProxyPass /wss ws://127.0.0.1:6001 retry=3 keepalive=On
    ProxyPassReverse /wss ws://127.0.0.1:6001 retry=3
</VirtualHost>

A: Hace poco tuve un problema similar para configurar un WebSocket, lo logré con Apache configurando mod_proxy y mod_proxy_wstunnel. Ten presente que debes realizar la conexión sobre SSL y tanto el Fronted como el Backend deben estar en el mismo hosting
Y lo que hice fue agregar a la configuración de mi virtualhost
<IfModule mod_proxy.c>
        <IfModule mod_proxy_wstunnel.c>
        ProxyPass /wss ws://127.0.0.1:8081 retry=0 keepalive=On
        ProxyPassReverse /wss ws://127.0.0.1:8081 retry=0
        </IfModule>
</IfModule>

En el mismo Virtualhost garantizo que se realice una redirección de este dominio a SSL con esta configuración
<VirtualHost *:80>
       RewriteEngine on
       RewriteCond %{SERVER_NAME} = NOMBRE_DOMINIO.COM
       RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
</VirtualHost>


text:
Q: How to only print the variable name itself as part of the recipes? Example:
var1 = x

dep : $(var1)
     echo ($^ -> $@)

This will show x -> dep, but what I really want to show is var1 -> dep.
I basically want to sprinkle this echo all over the rules so I can make sense of a dependency graph. Nothing else worked.

A: Firstly, to work in my environment your makefile needs two slight modifications: replace the parentheses in echo with quotes, and add a rule for x, to give:
var1 = x

dep: $(var1)
    echo "$^ -> $@"

x:

There appears to be no method to recover the unexpanded form of a variable name in a recipe.  My suggested solution/work-around is twofold: cache the variable name in another variable, and as per MadScientist's comment use $(warning ...). For example, the makefile:
var1 = x

dep: var1_=var1
dep: $(var1)
    @echo "$^ -> $@"
    @echo "$(var1_) -> $@"
    $(warning "Info: Using $^ to build $@")
    $(warning "Info: Using $(var1) to build $@")
    $(warning "Info: Using $(var1_) to build $@")
    $(warning "Info: Using $($(var1_)) to build $@")

x:

will give:
Makefile:7: "Info: Using x to build dep"
Makefile:8: "Info: Using x to build dep"
Makefile:9: "Info: Using var1 to build dep"
Makefile:10: "Info: Using x to build dep"
x -> dep
var1 -> dep

The var1_ variable needs to be defined on a separate line (see https://stackoverflow.com/a/20714468/318716), which doesn't appear to be well-documented. And the order of the output is interesting.
Edit: A more simple variant of this idea is to replace:
var1 = x

dep: var1_=var1

with just:
var1 = x
var1_ = var1


text:
Q: Is disk serial readable from supermicro chassis? We are working with a hosting company for managing our dedicated servers. We asked for a replacement disk on one of the servers by providing the serial number. They took out 2 other disks instead and put them back in. When we asked for an explanation, they told us that it is very hard to read the serial number and they mistakenly took other disks out.
They also provided us a photo to show us that it is indeed very hard to read the serial number. It is here.

Is the only way to read the serial number peeking through the holes?
This is the chassis.
EDIT: I have provided them the port number of the disk along with the serial number. They told me that they "think the controller cabling is mixed up or upside-down"
UPDATE: This is the final perspective of the DC.

Normally when our customer provides us with a controller port number
  and a serial we have all the required information to replace the disk.
  However in this case it appears that the wiring between the controller
  and the backplane in your server is incorrect. This is an unforseen
  event that should not happen.

A: Supermicro is rough... But so is your hosting company!!
There's no excuse for that. Ask for a credit on your monthly bill for the mistake if it caused downtime.
So think of this:

*

*The disk serial number should be irrelevant. Replacements should be based on model number. (One of the downsides of DIY Supermicro hardware is that you aren't dealing with a single manufacturer/warranty and unified part numbers)

*The model/types of the drive should be known to the owner of the hardware or hosting company. Their inventory system should have this information readily available.

*Pulling the wrong disks is just dangerous. I'm hoping this didn't happen while the server was running.

*It is possible to illuminate a disk locator LED under mode RAID situations. For instance, I will light a disk beacon for an hour to make sure a datacenter technician pulls the proper drive.

*Any form of hardware RAID and most software RAID solutions under every OS I'm familiar with is capable of providing disk information. Hardware controllers will give you the raw disk manufacturer, model and firmware:

  physicaldrive 3C:1:6
     Port: 3C
     Box: 1
     Bay: 6
     Status: OK
     Drive Type: Data Drive
     Interface Type: SATA
     Size: 1 TB
     Firmware Revision: 80.00A80
     Serial Number:      WD-WCAV5F799696
     Model: ATA     WDC WD10EARS-22Y
     SATA NCQ Capable: True
     SATA NCQ Enabled: True
     Current Temperature (C): 39
     Maximum Temperature (C): 53
     PHY Count: 1
     PHY Transfer Rate: 3.0Gbps

A: There exist no way at all to (optically) read a disk serial number once the disk is inserted into the system - the holes in the front of the disk caddy are not meant to facilitate reading a serial number but are there out of thermal and/or design considerations. This is generally true for every server/disk array manufacturer.
Usually, you replace disks  by slot numbers (or the "error LED", which also can be activated by command in many RAID controllers), but for that you have to be sure of the mapping between controller port/disk numbers and physical slots.
Nevertheless, what the DC did was beyond irresponsible, they had to get back to you before just pulling random disks to work out the correct slot. Doing this twice is beyond stupid, as you can kill even a RAID6 this way.

A: The only sensible way to ask for a replacement would be by knowing the slot number of the disk. It should be possible to map from the OS to the slot number but it requires calibration in that you need first to learn what identifies a slot and where it is physically.
The disk serial number of part number is not readable from the outside.


text:
Q: Variable String no soporta un imagen in base64 Buenos días tengo una librería, que me genera una imagen base64 desde mi JSP, esa imagen la envio servlet mediante un post, cuando lo recibo no recibo la información de caracteres completa , acaso el string no soporta la cadena en base64.
Funcion desde el jsp con el javascript:
function proceso(){
     var socio  = document.getElementById('socio').value;
     var foto64  = document.getElementById('foto64').value;
     f.action='/APLICACIONES/CL_T_FirmaFoto_Servlet?persona='+socio+'&foto64='+foto64;
     f.submit();
}

Recepción en el servlet:
Date fec = new Date(System.currentTimeMillis());
String strCodUsu = session.getAttribute("strCodUsu")== null ? "" : (String)session.getAttribute("strCodUsu");
String strCodFoto = request.getParameter("foto64")!=null?(String)request.getParameter("foto64"):"";
String  strCodigoCliente = request.getParameter("persona")!=null?request.getParameter("persona"):"";

El sistema tiene java 6, acaso no soporta esa cadena de base64, acabo de leer que el string soporta hasta 2gb

Aca envio la cadena de imagen en base64 y la cantidad que llega en mi string , espero lo puedan apreciar

Aca la cantidad de caracteres que llegar a mi servlet

A: "estas seguro que estas usando POST en lugar de GET? ten en cuenta que no todos los caracteres se intepretan correctamente en una URL, asegurate de pasar la representacion base64 de la imagen por POST "
Don Klaimmore , revise y mi codigo y lo envie la imagen por post correctamente gracias por la ayuda recién soy estudiante.

A: Dependiendo del servidor y su configuración, la longitud máxima admitida de la URL puede variar. En Tomcat ese valor suele estar alrededor de los 8000 caracteres, así que una imagen que ocupe más de 8KB no se puede mandar como un parámetro en la URL.
En cualquier caso, si estás haciendo un POST, lo lógico y habitual es usar el cuerpo de la petición para mandar la información.


text:
Q: Adding the using clause to the project - beginner I created a C# MVC project, and later added a Unit test project to it. The structure now is as follows;

Solution
|
|_ UnitTest Project
|
|_ MyProject

Now from the unit test project i need to refer the MyProject how can i write it;
I wrote the following but it didn't work;
using MyProject.View;

How can i solve this ?

A: Right click "References" within "UnitTest Project" and click "Add Reference...", select your other project from within this dialog.


text:
Q: Web browser that only runs JavaScript, to use as a development sandbox I'm looking for a JavaScript read-evaluate-print loop for development prototyping.
For now, I am using the Firebug Console, the Firefox Developer Tools Web Console, repl.it, jsFiddle, plunker, or one of the other online tools.
The problem is that a Firefox console is linked to the tab/window on which I opened it. The web based ones have restrictions too; for instance, jsFiddle.net doesn't show console output and repl.it does not let me use Fiddler to watch an XMLHttpRequest.
What I would like is a Windows desktop application that is very similar to the PowerShell ISE but that runs JavaScript instead.
+-------------------------------+----------------------------------+
|                               |                                  |
|  JavaScript to Run            |  Console Output                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
|                               |                                  |
+-------------------------------+----------------------------------+

It still needs to have the same functionality as the Firebug Console or Firefox Web Console. I.e. it needs to evaluate JavaScript, output console messages, and send HTTP requests via XMLHttpRequest. Does this exist? Where can I get it?

A: I ended up using PhantomJS,  Notepad, and the Windows Command Line. First, install PhantomJS. Then...
Edit

*

*Open Notepad.

*Create a JavaScript file.

*Type console.log('foo');

*Save.

Run

*

*Open the Command Line.

*Run phantomjs myfiddle.js.

*Press Ctrl + C to exit phantom.

Repeat

*

*Switch to Notepad. Edit. Save.

*Switch to Command Line. Run.

Here is a screen shot of a streamlined process running on my machine.

It works with XMLHttpRequests, I can inspect the request with Fiddler, and the nice-to-have is that we can adapt it for use with Vim to create an integrated scripting environment.

A: As a professional developer, I have to point out this makes absolutely no sense. The code you write is not going to be understandable or meaningful in terms of "console output", unless you write toy code, or what you want is actually a live-reloading server environment, where you write html+js, and you want the browser to autoreload when you save updated files. In which case live-server may already be all you need.
If, on the other hand, what you need is a REPL like python or the like, then just Node.js is literally what you want. But then that doesn't make the most sense because why on earth would you edit your source code in a REPL instead of using a code editor...?


text:
Q: Indicar pagina inicial, dentro de uma pasta do meu site Tenho um site, onde criei algumas paginas em html dentro de uma pasta, como posso especificar a pagina inicial, uma vez que usuário acessa a pasta e a pagina escolhida abra automaticamente?
Tentei por nomenclatura index.html dentro da pasta, não funcionou...
(Lembrando que é dendro de uma pasta, na raiz do servidor quando coloco index.html funciona normalmente!)

A: Redirect em PHP
Redirecionamento de páginas em PHP
Para fazer com que o usuário ao acessar um determinado endereço do seu site seja redirecionado para outro endereço, dentro ou fora do seu site, você deverá utilizar o parametro location: da função header(). Abaixo segue um exemplo de uso básico desta função:
Da maneira como esta acima, sempre que o usuário acessar a página que contém o código acima, ele será redirecionado automaticamente para http://www.seusite.com.br/pasta.
O redirecionamento não se restringe a endereços absolutos de sites, sendo que você também pode redirecionar para pastas dentro do seu FTP, ou mesmo arquivos que estão na mesma pasta utilizando um caminho relativo a ela.
Para melhor exemplificar isto, vamos criar um script que irá capturar o endereço pelo qual esta acessado, e redirecionar o usuário para outro conforme este endereço de acesso.
Lembrando que para o script acima funcionar, todas as entradas usadas no script deverão estar criadas no DNS.

A: O ideal seria renomear ela para index, no entanto só irá funcionar se seu site estiver em um servidor apache, ao contrário disso não.


text:
Q: LLVM IR: get the return value of the callsite Here is a quick question on analyzing LLVM IR. So basically I am trying to fetch the return value of the LLVM IR function call statement, something like this:
%47  =   call i256 @test(i256 %46)

I want to get access %47.
And this is the code I have been using to access the parameter.
      else if (funcName.contains("test")) {
        Value *op = CI->getOperand(0);
        if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(op))
          // get the first function parameter
          op = GEP->getPointerOperand();
      }

The very suprising finding is that I just cannot find something like "get return value" or so in the document: http://llvm.org/doxygen/classllvm_1_1CallInst.html
Could anyone shed some lights here? Thanks a lot.

A: CI (The call instruction) is its return value. It has a type that inherits Value.
If you want to do 1 + %47, just as an example, you make an add like this: Value * Add = BinaryOperation::Create(Instruction::Add, CI, ConstantInt::get(i256, 1), ...); The add instruction, in turn, is its result, and Add->getType() == i256 since it is the sum of two values that both have type i256.

A: As a different answer in case you need the string of the "return value" name, you can use inst.getName() or inst.getNameOrAsOperand() on the Instruction object, which is derived from the Value class.


text:
Q: Field  in , with long text, crushing the table I have a table, in  I have some inputs and selects. And when <option> in <select> has a long text - it expands , so it crushing the table. As usual in table td = th content length, and min width of td = length of biggest word in th. If I make width to td or th - it's not working, just width to select. But I have dynamic content in options so it will be bad to make static width for it. How can I make that select have not expands td and be equally th widh? Plnkr example

A: Since table elements grow by their content you need to give them a width, so if you update your CSS like this it will work
table {
  width: 100%;
  border-collapse: collapse;
}
td {
  width: 25%;
}
td select {
  width: 100%;
}

Sample snippet

table th, table td {
  border:1px solid grey;
}
table {
  width: 100%;
  border-collapse: collapse;
}
td {
  width: 25%;
}
td select {
  width: 100%;
}

          Group Name
          Members
          Genre
          From

            <select>
              <option>Red Hot Chili Peppers</option>
              <option>Depeche Mode</option>
              <option>very-very-very long text, it will be crush the table</option>
            </select>

            <select>
              <option>4</option>
              <option>3</option>
              <option>very-very-very long text, it will be crush the table</option>
            </select>

            <select>
              <option>funk-rock/rock/alternative</option>
              <option>Synthpop/new-wave</option>
              <option>very-very-very long text, it will be crush the table</option>
            </select>

            <select>
              <option>USA</option>
              <option>UK</option>
              <option>very-very-very long text, it will be crush the table</option>
            </select>

A: Apply width to select element too:
<select style="width:50px;"></select>


text:
Q: How to sort the list according to the condition? I have two tables, in the first I store companies, and in the second orders of these companies, but that if you create an order for a specific company and then remove the company from the list of companies, then there will be an error.
How to display only those orders that coincide with existing companies, that is, if there is no company, then there is no order.
Now I'm trying to do something like this, but I can't understand what's next ...

import React from "react";
import "./styles.css";

export default function App() {
  const arr1 = {
    company: [
      {
        id: "random1",
        companyName: "Apple"
      }
    ]
  };

  const arr2 = {
    projects: [
      {
        id: "random1",
        companyName: "Apple",
        descProjects: "Desc1"
      },
      {
        id: "random2",
        companyName: "Samsung",
        descProjects: "Desc2"
      }
    ]
  };

  const blockCreate = () => {
    return arr1.company.map(item => {
      const projects = arr2.projects.filter(i => {
        return i.companyName === item.companyName;
      });

      return (

          ID {item.id} -

          {item.companyName}

      );
    });
  };

  return (

{blockCreate()}

  );
}

A: You have to filter your second array before mapping it.
You can try something like this:
const companies = arr1.company.map(company => company.companyName); // ["Apple", "Microsoft", ...]
const projects = arr2.projects.filter(project => companies.includes(project.companyName));

projects.map(project => (

     ID {project.id} -

     {project.companyName}

))


text:
Q: How can we cut a loop with Tikz-Feynman? If we want to apply Cutkosky rule, how can we draw a cutting line like the dashed line in the figure (quickly made with paint)?

\documentclass[12pt]{book}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[a4paper,left=2.5cm,right=2.5cm,top=2.8cm,bottom=2.8cm]{geometry}
\usepackage[frenchb]{babel}
\usepackage{libertine}
\usepackage{luatex85}
\def\pgfsysdriver{pgfsys-pdftex.def}
\usepackage{lmodern}
\usepackage{xcolor}
\usepackage{tikz}
\usepackage{pgfkeys}
\usepackage[compat=1.1.0]{tikz-feynman}
\usepackage{tikz-feynman, contour}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage[absolute,overlay]{textpos}
\newcommand{\autofontsize}[1]{\fontsize{#1}{\dimexpr #1*12/10}}
\usepackage{setspace}
\usepackage{pgfplots}
\usepackage{xparse}

\usetikzlibrary{positioning,arrows,patterns}
\usetikzlibrary{decorations.markings}
\usetikzlibrary{calc}

\tikzset{
photon/.style={decorate, decoration={snake}, draw=black},
fermion/.style={draw=black, postaction={decorate},decoration={markings,mark=at position .55 with {\arrow{>}}}},
vertex/.style={draw,shape=circle,fill=black,minimum size=3pt,inner sep=0pt},
}

\NewDocumentCommand\semiloop{O{black}mmmO{}O{above}}
{%
\draw[#1] let \p1 = ($(#3)-(#2)$) in (#3) arc (#4:({#4+180}):({0.5*veclen(\x1,\y1)})node[midway, #6] {#5};)
}
%% Syntax
%\semiloop[fermion][<draw options>]{<first node>}{<second node>}{<angle>}[<label>][<below, default: above>];

\begin{document}

\begin{center}
\scalebox{2}{
\fontsize{0.35714em}{0.35714em}
\feynmandiagram [horizontal=a to b] {
i1 -- [fermion, arrow size=0.8pt] a  [label=${\mu}$]-- [fermion, arrow size=0.8pt] i2 ,
a -- [photon] b
-- [fermion, half left, looseness=1.6, arrow size=0.8pt] c
-- [fermion, half left, looseness=1.6, arrow size=0.8pt] b,
c -- [photon] d,
f1  -- [fermion, arrow size=0.8pt] d -- [fermion, arrow size=0.8pt] f2,
};
}
\end{center}
\end{document}

A: TikZ-Feynman (CTAN) provides \feynmandiagram command to draw single diagrams only without having to create a full {tikzpicture} environment; however, it is possible to use the {feynman} environment within a {tikzpicture} which allows you to access all the commands from TikZ.
By putting everything inside a {tikzpicture} and {feynman} environment, I can first draw the diagram and then, in later commands, access the location of vertices in order to place new vertices.  In this instance, I calculate the mipoint to be halfway between (b) and (c), and then draw a line going from 2 units above (midpoint) to 2 units below (midpoint).
\RequirePackage{luatex85}
\documentclass{standalone}
\usepackage[compat=1.1.0]{tikz-feynman}

\begin{document}
\begin{tikzpicture}
  \begin{feynman}
    \diagram [horizontal=a to b] {
      i1
        -- [fermion] a
        -- [fermion] i2 ,
      a -- [photon] b
        -- [fermion, half left] c
        -- [fermion, half left] b,
      c -- [photon] d,
      f1
        -- [fermion] d
        -- [fermion] f2,
    };

    %% Find the midpoint, which is halfway between b and c.
    \coordinate (midpoint) at ($(b)!0.5!(c)$);
    %% Draw a line starting 2 units above the midpoint, and ending 2 units below
    %% the midpoint.
    \draw [dashed] ($(midpoint) + (0, 2)$) -- ($(midpoint) + (0, -2)$);
  \end{feynman}
\end{tikzpicture}
\end{document}

Note that I had to greatly simplified you minimal example.  None of the packages included are relevant other than TikZ-Feynman (which you also happen to import twice...).  The use luatex85 is due to a bug with the standalone class, but shouldn't be needed with most other classes.


text:
Q: Catch block wrapping a function that throws inside a setTimeout not executed Experienced something strange recently, none of the catch blocks get executed:
function funcWillThrow() {
  try {
    setTimeout(() => {
      throw "Has thrown";
    }, 3000);
  } catch (error) {
    console.log(error)
  }
}

function caller() {
  funcWillThrow();
}

caller();

and
function funcWillThrow() {
    setTimeout(() => {
      throw "Has thrown";
    }, 3000);
}

function caller() {
  funcWillThrow();
}

try {
  caller();
} catch (error) {
  console.log(error);
}

And according to the mdn docs

Execution of the current function will stop (the statements after
throw won't be executed), and control will be passed to the first
catch block in the call stack. If no catch block exists among caller
functions, the program will terminate.

My guess is that something is happening with the callstack as stated in the docs. Any ideas as to what might be happening.

A: setTimeout calls the supplied function at a later time (3 seconds later in your specific code), and by then the function which called setTimeout has long since terminated.
To catch the exception in your later function, put the error handling in that function:
function funcWillThrow() {
  setTimeout(() => {
    try {
      throw "Has thrown";
    } catch (error) {
      console.log(error);
    }
  }, 3000);
}

Based on your comment below, you may be looking for Promises.  Since the operation is asynchronous and happens outside of the stack which invoked it, in order to catch the error in that stack you'd need to await the operation.  Ideally you'd make use of the reject functionality of the Promise.  Something like this:

function funcWillThrow() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject("Has thrown");
    }, 3000);
  });
}

(async () => {
  try {
    await funcWillThrow();
  } catch (err) {
    console.log(err);
  }
})();

If you specifically need to be able to throw from within the setTimeout callback, you'd either need to catch there as well:

function funcWillThrow() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      try {
        throw "Has thrown";
      } catch (error) {
        reject(error);
      }
    }, 3000);
  });
}

(async () => {
  try {
    await funcWillThrow();
  } catch (err) {
    console.log(err);
  }
})();

Or customize setTimeout itself as a Promise and use normal error handling with that:

function myTimeout(ms) {
  return new Promise(function(resolve) {
    setTimeout(resolve, ms);
  });
}

(async () => {
  try {
    await myTimeout(3000).then(() => {
      throw "Has thrown";
    });
  } catch (err) {
    console.log(err);
  }
})();


text:
Q: SkSpriteNode has no member center I have an SKSpritenode named "Ghost" and I am trying to add a pulsing look to the outside of the image. However I am getting an error saying it has no center, I am not sure how fix this please help.
func addPulse(){
        let pulse = Pulsing(numberOfPulses: .infinity , radius: 110, position: Ghost.center)
        pulse.animationDuration = 1.0
        pulse.backgroundColor = UIColor.blue.cgColor

        self.view.layer.insertSublayer(pulse, below: Ghost.layer)
    }

A: SKSpriteNode extends SKNode. Neither has a center property. However, there is frame and position. Use either of those properties instead of center.
let pulse = Pulsing(numberOfPulses: .infinity , radius: 110, position: Ghost.position)


text:
Q: send calls via an endpoint to a GenServer Given a running GenServer, is there a known way to send synchronous/asynchronous calls to the pid via an endpoint, without using the Phoenix framework?
Here's an example call (using python's requests library) that maps the reply term to JSON:
iex> give_genserver_endpoint(pid, 'http://mygenserverendpoint/api')
iex> {:ok, 'http://mygenserverendpoint/api'}

>>> requests.get(url='http://mygenserverendpoint/getfood/fruits/colour/red')
>>> '{ "hits" : ["apple", "plum"]}'

A: You can write a complete elixir http server using cowboy and plug:
Application Module
defmodule MyApp do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec

    children = [
      worker(MyGenServer, []),
      Plug.Adapters.Cowboy.child_spec(:http, MyRouter, [], [port: 4001])
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

Router Module
defmodule MyRouter do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/mygenserverendpoint/getfood/fruits/colour/:colour" do
    response_body = MyGenServer.get_fruit_by_colour(colour)
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(conn, 200, Poison.encode(response_body))
  end

  match _ do
    send_resp(conn, 404, "oops")
  end
end

GenServer module
defmodule MyGenServer do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def get_fruit_by_colour(colour) do
    GenServer.call(__MODULE__, {:get_by_colour, colour})
  end

  def handle_call({:get_by_colour, colour}, _from, state) do
    {:reply,  %{"hits" : ["apple", "plum"]}, state}
  end
end


text:
Q: Redirect browser http request to local server I have now the following flow.
example.com => https://example-example.mycompany.com => myproxy => someServer

I am right now developing myproxy and it changes the answers that the clients of the website example.com are receiving.
In order to test this, I thought that the best idea I could come up with was changing my local machine (in which I have an instance of myproxy running on the port 8080) redirect the requests that example-example.mycompany.com does to localhost:8080
I have tried with nginx adding the following configurationbut I was unable... and also changing /etc/hosts didn't help me.
Question
Is there any way to change the call of example-example.mycompany.com JUST for my computer, so that while I am testing there is no client of example.com affected by the bugs that might appear?
Trials
Nginx setup
docker run --name my-custom-nginx-container -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro -p 80:80 -p 3000:8080 --rm -d nginx
nginx.conf
server {
            listen   80;
            server_name example-example.mycompany.com;

            location / {
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header Host $host;
                    proxy_set_header X-NginX-Proxy true;
                    proxy_pass http://localhost:3000/;
                    proxy_redirect http://localhost:3000/ https://$server_name/;
            }
    }

/etc/hosts (not added at the same time as the nginx setup)
127.0.0.1    example-example.mycompany.com


text:
Q: How to create an Icecast client like Butt I need to create an Icecast client in C#. The main objective of this it's to send the incoming audio from two audio devices to be broadcast via Icecast.
When I was searching for some solution already made, I found Butt which was exactly what I needed but I also needed to send to the Icecast two audio devices individually.
I'm already getting the audio input from the two microphones and save them in a folder (one audio file for each microphone).
Now I need to broadcast individually the two microphone to Icecast.
All this is because I need to broadcast the two microphones like a radio station (one station for each microphone).
The main solution it's something like this:

*

*Microphone 1 => Broadcast to Icecast like Source Micro1 => Save audio
like micro1.mp3 format (working).

*Microphone 2 => Broadcast to
Icecast like Source Micro2 => Save audio like micro2.mp3 format
(working).

I need to know how can I broadcast to icecast, i'm using NAudio library to get the audio input and save it.
EDIT:
I'm communicating with Icecast from C#, this is my code:
public static void commIcecast(string url)
    {
        WebClient client = new WebClient();

        client.Headers.Add("content-type", "audio/mpeg");
        client.Headers.Add("Authorization", "Basic c291cmNlOmhhY2ttZQ==");
        client.Headers.Add("ice-name", "This is my server name");
        client.Headers.Add("ice-url", "http://www.google.com");
        client.Headers.Add("ice-genre", "Rock");
        client.Headers.Add("ice-description", "This is my server description");
        client.Headers.Add("ice-audio-info", "ice-samplerate=44100;ice-bitrate=128;ice-channels=2");

        Stream data = client.OpenRead(url);
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        Console.WriteLine(s);
        data.Close();
        reader.Close();
    }

But i'm just reciving this answer from the Icecast server:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Icecast Streaming Media Server</title>
<link rel="stylesheet" type="text/css" href="style.css">

Icecast2 Status

AdministrationServer StatusVersion

Support icecast development at www.icecast.org

I've tried to send the "SOURCE /mp3test ICE/1.0" but the Headers.Add method don't allow me to do that.
EDIT: I'm sending this via tcp to Icecast, but i can't recibe the response, i just need to know if this way to send it , if it's right now i'll have to move the post to tcp issues.
I'm not reciving any response of the Icecast server using this method of sending.
            System.Net.IPAddress address = System.Net.IPAddress.Parse(url);

            socketServer = new TcpClient(url, port);
            NetworkStream networkStream = socketServer.GetStream();

            data = Encoding.ASCII.GetBytes("SOURCE /csharp ICE/1.0");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("content-type: audio/mpeg");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("Authorization: Basic c291cmNlOmhhY2ttZQ==");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("ice-name: lala");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("ice-url: localhost");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("ice-genre: Rock");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("ice-bitrate: 128");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("ice-private: 0");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("ice-public: 1");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("ice-description: This is my server description");
            networkStream.Write(data, 0, data.Length);

            data = Encoding.ASCII.GetBytes("ice-audio-info: ice-samplerate=44100;ice-bitrate=128;ice-channels=2");
            networkStream.Write(data, 0, data.Length);

            StreamReader reader = new StreamReader(networkStream);
            Console.WriteLine(reader.ReadToEnd());

With this i can connect to the Icecast server, at least the number of clients connected increase in the global statistics in Icecast, but then the connection it's lost and i can't get any response.

A: First, you need to encode your captured audio with a codec.  MP3 is popular and well supported.  aacPlus is well supported (but not quite as much as MP3), and gives a better compression ratio in most cases.
I do not believe NAudio supports encoding (please correct me if I am wrong).  You will need to look at something like FFMPEG (wide variety of codecs available) or LAME (quality MP3 codec).  As a bonus, if you go with FFMPEG, it is able to capture from DirectShow sources for you, so you only need to write code to get data from STDOUT.  (Note that there are potential licensing issues here, both with the source code of the libraries and with patents on the codecs.)
Now that you have encoded audio data, you need to implement the Icecast source protocol.  To do that, see my answer here:  https://stackoverflow.com/a/9985297/362536

A: To solve my problem I used Edcast.
This is the url https://code.google.com/p/edcast-reborn/
Basically I used two instances of edcast, each one pointing a different audio input and they were connecting to the Icecast server.
With this configuration you can see the two edcast instances and listen the different audio inputs by accessing the Icecast server.
Thank you all for your help.


text:
Q: How do make this regex lazy I have this string:
XXXX:  150: some texxt: long text

I need to obtain only the digits between :: like :150: in this case.
    echo "$LINE" |sed -n 's/^.*\XXXX:\(.*\)\:.*/\1/p'

gets me  150:  some texxt
How do I make it lazy and stop at the first match

A: $ LINE='XXXX:  150: some texxt: long text'

$ echo "$LINE" | sed -r 's@^[^:]+:([^:]+):.*@\1@g'
 150

or
$ echo "$LINE" | perl -pe 's@.*?:([^:]+):.*@\1@g'
 150

EXPLANATIONS

*

*[^x] means : exclude the x character

A: I'm not sure if this will work in your case, but this regex will find all numbers between : characters.
:\s*(\d+)\s*:

You will find the number in Capture Group 1.
Another similar approach where you don't need to look at capture groups and simply use the whole match would be (looks like this one doesn't work in Perl though):
(?<=:\s*)\d+(?=\s*:)

A: The term is "non greedy":
^.*?\XXXX:\(.*\)\:.*

It is achieved by adding a ? after .*