text:
Q: Is it possible to alter the behavior of toString() methods generated for Kotlin data classes? E.g.:
data class Key(
    val id:          Int,
    val secret:      String,
    val description: String?
)

To exclude or mask special properties like passwords or credit card numbers:
Key(
    id          = 1,
    secret      = "foo",
    description = "bar"
).toString()
// Key(id=1, description=bar)
// or
// Key(id=1, secret=********, description=bar)

Or to ignore properties with nulls to make the resulting string more readable:
Key(
    id          = ...,
    secret      = ...,
    description = null
).toString()
// Key(id=...)
// or
// Key(id=..., secret=...)

Implementing toString() each time may be very tedious and error-prone, especially if you have too many properties in the class.
Is there any (upcoming) solution for this problem (e.g. like Lombok for Java)?

A: I reworked previous response by Andrii Vdovychenko as follows:
data class Key(val id: Int, val secret: String, val description: String?){
    override fun toString() = kotlinToString(target = this, properties = arrayOf(prop(Key::id), prop(Key::description), prop(Key::secret)))
}

fun <T>prop(kp : KProperty1<T, Any?>) : KProperty1<Any, Any?> {
    return kp as KProperty1<Any, Any?>
}

fun kotlinToString(target: Any, properties : Array<KProperty1<Any, Any?>>) : String {
    return properties
            .map { kp -> Pair(kp.name, kp.get(target)) }
            .filter { p -> p.second != null }
            .map { p -> "${p.first}: ${p.second}" }
            .joinToString(", ")
}

You can test mi implementation using the following main function:
fun main(args : Array<String>) {
    println(Key(1, "aa", "bbb").toString())
    println(Key(1, "aa", null).toString())
}

which output is
id: 1, description: bbb, secret: aa
id: 1, secret: aa

May be you can change kotlinToString implementation in order to include a per-class prefix in the output string, perhaps passing it as parameter to kotlinToString, but I hope this can helpo you!

A: You can try something like this:
data class Key(val id: Int, val secret: String, val description: String?){
    override fun toString() = kotlinToString(properties = arrayOf(Key::id, Key::description)
}

Example output:

A: The answer of Andrii Vdovychenko seems incomplete but inspired me to do this:
fun <T> kotlinToString(target: T, properties: Array<KProperty1<T, Any?>>): String {
    return properties
        .map { kp -> Pair(kp.name, kp.get(target)) }
        .filter { p -> p.second != null }
        .joinToString(", ") { p -> "${p.first}: ${p.second}" }
}

which seems to be a little clearer and can be used like this:
data class Key(val id: Int, val secret: String, val description: String?){
    override fun toString() = kotlinToString(target = this, properties = arrayOf(Key::id, Key::description, Key::secret))
}

Another Version could be using varargs which saves the "arrayOf" in the call:
fun <T> kotlinToString(target: T, vararg properties: KProperty1<T, Any?>): String {
    return properties
        .map { kp -> Pair(kp.name, kp.get(target)) }
        .filter { p -> p.second != null }
        .joinToString(", ") { p -> "${p.first}: ${p.second}" }
}


text:
Q: How to change FileReferenceList browse title? I am using FileReferenceList browse method. the window opened shows the following title:
"Select file(s) to upload by ".
I would like to change this title - how can i do that?

A: The only things you can change in this window are the file filters/types to be uploaded. All the other elements are OS dependent. Sorry.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix this regex so it replaces * properly (between words)? I'm practicing regex. I thought of creating regex that turn * into , just like with Markdown:
el = el.replace(/\*\b/g, '')
el = el.replace(/\b\*|(\.|\,|\?|\!|\*|---|\.\.\.\s)\*/g, '$1')

This works in most cases. However, things gets messy if you apply that regex to this:
Chicken teriy*ai*ki, r*ai*men noodles, spaghetti a la moneg*ai*sque.

It produces this:
Chicken teriyaiki, raimen noodles, spaghetti a la monegaisque. And wait for me, often falling asleep.

How to modify this regex so it produces something like this:
 Chicken teriyaiki, raimen noodles, spaghetti a la monegaisque. And wait for me, often falling asleep.

A: You can merge the two branches in your second regex since both end with \* pattern, like (\b|\.|,|\?|!|\*|---|\.{3}\s)\* (you may even merge the \.|,|\?|!|\* single char alternatives into [.,?!*]), and then use

var s = "Chicken teriy*ai*ki, r*ai*men noodles, spaghetti a la moneg*ai*sque.";
console.log(
  s.replace(/\*\b([^]*?)(\b|[.,?!*]|---|\.{3}\s)\*/g, '$1$2')
)

Details

*

*\*\b - a * that is followed with a word char (letter, digit or _)

*([^]*?) - Group 1: any 0+ chars, as few as possible (may be replaced with a [\s\S] / [\d\D] / [\w\W] if you need more portability), up to the leftmost occurrence of

*(\b|[.,?!*]|---|\.{3}\s) - word boundary,  ., ,, ?, !, *, ---, ... + whitespace

*\* - a * char.

A: Use regex \*([\w ^?.]*?)\*
Replace with $1<\em>
el = el.replace(/\*([\w ^?.]*?)\*/g, '$1<\em>')
Regex

A: This should work, it will wrap the characters between * signs into em tags, NOTE: this applies globally on the string provided.
 const str = "something that has words surrounded with * signs"
 str.replace(/\*(\w+)\*/g, "$1")


text:
Q: Why a n-th order linear homogeneous ODE has exactly n linearly independent solutions? After some research I cannot find an answer that satisfies me for the question above. I know about the Cauchy criterion but I don't think that it proves the fact that there are exactly n linearly independent solutions to an n-th order linear homogeneous ODE.
Is it a dimension problem ? (like maybe we could construct an isomorphism from the ODE to Rn prove that ?)

A: Consider the n-th order linear ODE for $t \in \mathbb{R}$
$$y^{(n)}(t) + a_{n-1}(t) y^{(n-1)}(t)+ \ldots +a_1(t) y'(t) + a_0(t)y(t) =0.$$
Introducing the function $\mathbf{y} : \mathbb{R} \to \mathbb{R}^n$,
$$\mathbf{y} = (y,y',y'', \ldots, y^{(n-2)}, y^{(n-1)}) = (y_1,y_2,y_3, \ldots , y_{n-1}, y_{n})$$ the ODE is equivalent to a system $\mathbf{y}' = A \, \mathbf{y}$ where component by component we have
$$y_1'(t) = y_2(t) \\ y_2'(t) = y_3'(t) \\ \cdots \\ y_n'(t) = - a_{n-1}(t)y_{n}(t) + \ldots +a_0(t) y_1(t)$$
Given the standard basis vectors $\mathbf{e}_1 = (1,0, \ldots, 0), \ldots , \mathbf{e}_n = (0,0, \ldots ,1)$ for $\mathbb{R}^n$, the existence-uniqueness theorem for homogeneous linear ODEs guarantees the existence of $n$ solutions $\mathbf{y}_{1}, \ldots , \mathbf{y}_{n}$ satisfying the initial conditions
$$\mathbf{y}_{k}(0) = \mathbf{e}_k, \quad \text{for } k = 1,2,\ldots ,n.$$
Forming a matrix using the $n$ solutions as columns $[\mathbf{y}_1^T(t), \ldots, \mathbf{y}_n^T(t)]$ we can show that the determinant (called the Wronskian) $W(t) = \det\, [\mathbf{y}_1^T(t), \ldots, \mathbf{y}_n^T(t)]$ satisfies the differential equation
$$W'(t) = -a_{n-1}(t) W(t)$$
and, obviously, the initial condition
$$W(0) = \det\, [\mathbf{e}_1^T, \ldots, \mathbf{e}_n^T] = \det\, I =1.$$
The solution is $W(t) = \exp\left(- \int_0^t a_{n-1}(s) \, ds \right) \neq 0$.  Since the determinant never vanishes, there exists a set of $n$ linearly independent solutions $\{\mathbf{y}_1(t), \ldots, \mathbf{y}_n(t)\}$. Solution of the ODE for any set of initial conditions is always some linear combination of this set.


text:
Q: replace image in header, OpenXML I am hoping that someone can assist with this issue. I am using OpenXMl to search and replace for text in the header, body and footer of a word document using Open XML. The text is working fine. But the image is not replacing as I would expect it to. The image (@"C:\temp\pic\Logo.gif") does exist at the source. But never shows up in the word document correctly. You can see in the region below (#region "Modify Header Logo")
Can anyone assist? Thank you!
Word Error
       public void SearchAndReplace(string templateFileNameTemplate, string targetFileName, ProjectModel project)
    {

        //copy template file
        if (File.Exists(targetFileName) == true)
        {
            File.Delete(targetFileName);
        }

        File.Copy(templateFileNameTemplate, targetFileName);

        string searchText = "", replaceText = "", headerLogo = "", headerText = "";
        bool replace = false;

        //open file
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(targetFileName, true))
        {

            //Gets all the headers
            foreach (var headerPart in wordDoc.MainDocumentPart.HeaderParts)
            {
                //Gets the text in headers
                foreach (var currentText in headerPart.RootElement.Descendants<Text>())
                {
                    replace = false;

                    switch (currentText.Text)
                    {
                        case "<COMPANY NAME>":
                            replace = true;
                            replaceText = project.ClientName;
                            searchText = currentText.Text;
                            break;
                        **case "<INSERT YOUR LOGO HERE>":
                            headerLogo = @"C:\temp\pic\Logo.gif";//project.ClientLogo;**
                            headerText = currentText.Text;
                            break;
                        case "<ISSUE DATE>":
                            replace = true;
                            replaceText = project.AssignedDate.ToShortDateString();
                            searchText = currentText.Text;
                            break;
                        case "<REVIEW DATE>":
                            replace = true;
                            replaceText = project.ClientDueDate.ToShortDateString();
                            searchText = currentText.Text;
                            break;
                        default:
                            break;
                    }
                    if(searchText.Length>0 && replace==true)
                        currentText.Text = currentText.Text.Replace(searchText, replaceText);
                }
            }
            //Gets all the footers
            foreach (var footerPart in wordDoc.MainDocumentPart.FooterParts)
            {
                //Gets the text in headers
                foreach (var currentText in footerPart.RootElement.Descendants<Text>())
                {
                    replace = false;
                    switch (currentText.Text)
                    {
                        case "<COMPANY NAME>":
                            replace = true;
                            replaceText = project.ClientName;
                            searchText = currentText.Text;
                            break;
                        default:
                            break;
                    }

                    if (searchText.Length > 0 && replace == true)
                        currentText.Text = currentText.Text.Replace(searchText, replaceText);
                }
            }
            #region "Modify Header Logo"
            if(headerLogo != string.Empty)
            {
                ImagePart imagePart = wordDoc.MainDocumentPart.AddImagePart(ImagePartType.Png);
                using (FileStream stream = new FileStream(headerLogo, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }
                searchText = headerText;
                Text textPlaceHolder = null;
                // Insert image (the image created with your function) after text place holder.
                // Search for text holder
                //Gets all the headers
                foreach (var headerPart in wordDoc.MainDocumentPart.HeaderParts)
                {
                    //Gets the text in headers
                    foreach (var currentText in headerPart.RootElement.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>())
                    {
                        textPlaceHolder = headerPart.RootElement.Descendants<Text>()
                            .Where((x) => x.Text == searchText).First();
                    }
                }

                if (textPlaceHolder != null)
                {
                    var parent = textPlaceHolder.Parent;

                    if (parent is Run)  // Parent should be a run element.
                    {
                        //add image
                        Drawing imageElement = GetImageElement(
                            wordDoc.MainDocumentPart.GetIdOfPart(imagePart),
                            headerLogo,
                            "my image",
                            475,
                            245);
                        // Insert image (the image created with your function) after text place holder.
                        textPlaceHolder.Parent.InsertAfter<Drawing>(imageElement, textPlaceHolder);
                        // Remove text place holder.
                        textPlaceHolder.Remove();
                    }
                }
            }

            #endregion
            string docText = null;
            using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
            {
                docText = sr.ReadToEnd();
            }

            Regex regexText = new Regex("<COMPANY NAME>");
            docText = regexText.Replace(docText, project.ClientName);

            //regexText = new Regex("<COMPANY NAME>");
            //docText = regexText.Replace(docText, project.ClientName);

            using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
            {
                sw.Write(docText);
            }

            //wordDoc.SaveAs(targetFileName).Close();
        }
    }

        private static Drawing GetImageElement(
        string imagePartId,
        string fileName,
        string pictureName,
        double width,
        double height)
    {
        double englishMetricUnitsPerInch = 914400;
        double pixelsPerInch = 96;

        //calculate size in emu
        double emuWidth = width * englishMetricUnitsPerInch / pixelsPerInch;
        double emuHeight = height * englishMetricUnitsPerInch / pixelsPerInch;

        var element = new Drawing(
            new A.Wordprocessing.Inline(
                new A.Wordprocessing.Extent { Cx = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight },
                new A.Wordprocessing.EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
                new A.Wordprocessing.DocProperties { Id = (UInt32Value)1U, Name = pictureName },
                new A.Wordprocessing.NonVisualGraphicFrameDrawingProperties(
                new A.GraphicFrameLocks { NoChangeAspect = true }),
                new A.Graphic(
                    new A.GraphicData(
                        new A.Pictures.Picture(
                            new A.Pictures.NonVisualPictureProperties(
                                new A.Pictures.NonVisualDrawingProperties { Id = (UInt32Value)0U, Name = fileName },
                                new A.Pictures.NonVisualPictureDrawingProperties()),
                            new A.Pictures.BlipFill(
                                new A.Blip(
                                    new A.BlipExtensionList(
                                        new A.BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }))
                                {
                                    Embed = imagePartId,
                                    CompressionState = A.BlipCompressionValues.Print
                                },
                                        new A.Stretch(new A.FillRectangle())),
                            new A.Pictures.ShapeProperties(
                                new A.Transform2D(
                                    new A.Offset { X = 0L, Y = 0L },
                                    new A.Extents { Cx = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight }),
                                new A.PresetGeometry(
                                    new A.AdjustValueList())
                                { Preset = A.ShapeTypeValues.Rectangle })))
                    {
                        Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
                    }))
            {
                DistanceFromTop = (UInt32Value)0U,
                DistanceFromBottom = (UInt32Value)0U,
                DistanceFromLeft = (UInt32Value)0U,
                DistanceFromRight = (UInt32Value)0U,
                EditId = "50D07946"
            });
        return element;
    }

A: Firstly, here's the markup for an image (Picture.png) that I manually inserted in a Word document. Did you check the markup created by your code against markup created by Microsoft Word when inserting the same image manually? This often helps spot errors in the markup (not always, though, because there are multiple "ways to Rome" and the same thing can often be expressed in multiple ways). You could use the Open XML Productivity Tool to compare the two documents, for example, and look at the differences in markup and the code required to create the correct markup.
    <w:r>
      <w:rPr>
        <w:noProof/>
      </w:rPr>
      <w:drawing>
        <wp:inline distT="0" distB="0" distL="0" distR="0" wp14:anchorId="787F9556" wp14:editId="6F9F029A">
          <wp:extent cx="4026107" cy="4019757"/>
          <wp:effectExtent l="0" t="0" r="0" b="0"/>
          <wp:docPr id="2" name="Picture 2" descr="A close up of a sign

Description automatically generated"/>
          <wp:cNvGraphicFramePr>
            <a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/>
          </wp:cNvGraphicFramePr>
          <a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
            <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
              <pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
                <pic:nvPicPr>
                  <pic:cNvPr id="2" name="Picture.png"/>
                  <pic:cNvPicPr/>
                </pic:nvPicPr>
                <pic:blipFill>
                  <a:blip r:embed="rId1">
                    <a:extLst>
                      <a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}">
                        <a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0"/>
                      </a:ext>
                    </a:extLst>
                  </a:blip>
                  <a:stretch>
                    <a:fillRect/>
                  </a:stretch>
                </pic:blipFill>
                <pic:spPr>
                  <a:xfrm>
                    <a:off x="0" y="0"/>
                    <a:ext cx="4026107" cy="4019757"/>
                  </a:xfrm>
                  <a:prstGeom prst="rect">
                    <a:avLst/>
                  </a:prstGeom>
                </pic:spPr>
              </pic:pic>
            </a:graphicData>
          </a:graphic>
        </wp:inline>
      </w:drawing>
    </w:r>

Secondly, the following code does not make a lot of sense, because you don't need the foreach loop. That loop takes all w:t descendants of w:hdr but never uses currentText in the body of the loop.
foreach (var currentText in headerPart.RootElement.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>())
{
    textPlaceHolder = headerPart.RootElement.Descendants<Text>()
       .Where((x) => x.Text == searchText).First();
}

The body of the loop is sufficient. I'd just use FirstOrDefault and check for null, unless you are 100% sure that the text will exist in all (!) headers.


text:
Q: Adjusting the width of a table view dynamically in iPhone Im getting a json response from the server and displaying it in the table view.I have displayed the data by creating a custom cell.
In  app now i want to adjust the width of a table view from the app.
ie for example just like we adjust the width of a cell in microsoft excel sheet.

Can anyone please help me to do this.Thanks in advance

A: try putting your data into multiple lines,
or you can put a text view onto cell, and put the data in that

A: As everyone says, you should look for a better option.
Anyway if it's really what you want to do, I would suggest to create a tableview as large as you need and then embed it in a scrollView.
Notify the tableView that it shouldn't scroll (the scrollView will do the job).
Set the contentSize of the scrollView to the size of the tableView and its frame to the size of the screen.
If you want to tap on the tableViewCell, you may need to add a gestureRecognizer (search on StackOverflow for the method)

A: First, you can change the UITableView's width
when it finished to change the width, reload it with new Cells with new width.


text:
Q: How to use statusChanged in WebView ( QtQuick 2.0 and QtWebKit 3)? In QtQuick 1.0 and QtWebKit 1.0 i could do onLoadFinished to execute function after page was ready. How to do it in versions 2 and 3 respectively?
There is a statusChanged in docuements. Id don't understand how to use it.
Previously i  had:
import QtQuick 2.0
import QtWebKit 3.0

WebView {
    width: 700
    height: 800

    url:"http://www.yahoo.com"
    settings.developerExtrasEnabled : true

    id: webView
    objectName: "myWebView"

    onLoadFinished: evaluateJavaScript("window.setTimeout('window.location.reload()',5000);")

}

but it shows error:
Cannot assign to non-existent property "onLoadFinished"

A: You have to use the onLoadingChanged signal and loadRequest object to check the exact status:
http://qt-project.org/doc/qt-5.0/qtwebkit/qml-qtwebkit3-webview.html#onLoadingChanged-signal
import QtQuick 2.0
import QtWebKit 3.0

WebView {
    width: 700
    height: 800

    url:"http://google.com"

    id: webView
    objectName: "myWebView"

    onLoadingChanged: {
        console.log("onLoadingChanged: status=" + loadRequest.status);
        if (loadRequest.status == WebView.LoadStartedStatus)
            console.log("Loading started...");
        if (loadRequest.status == WebView.LoadFailedStatus) {
           console.log("Load failed! Error code: " + loadRequest.errorCode);
           if (loadRequest.errorCode === NetworkReply.OperationCanceledError)
               console.log("Load cancelled by user");
        }
        if (loadRequest.status == WebView.LoadSucceededStatus)
            console.log("Page loaded!");
    }

}

The onLoadingChanged signal occurs when any page load begins, ends, or fails. Various read-only parameters are available on the loadRequest:

*

*url: the location of the resource that is loading.

*status: Reflects one of three load states: LoadStartedStatus, LoadSucceededStatus, or LoadFailedStatus. See WebView::LoadStatus.

*errorString: description of load error.

*errorCode: HTTP error code.

*errorDomain: high-level error types, one of NetworkErrorDomain, HttpErrorDomain, InternalErrorDomain, DownloadErrorDomain, or NoErrorDomain. See WebView::ErrorDomain.


text:
Q: Need Help with ASP.NET (3.5) ScriptManager to call WCF JSON Data via AJAX I am trying to get ASP.NET (Framework 3.5), AJAX, and JSON to work. I have two questions along those lines. This first is, when I add the below tag as required by ASP.NET:
[AspNetCompatibilityRequirements(RequirementsMode =
      AspNetCompatibilityRequirementsMode.Allowed)]

I find that I cannot add it above an interface declaration, only a class. I want this code to be an interface. Can somebody tell me what I am doing wrong? The error is as follows:

Attribute
  AspNetCompatibilityRequirements is not
  valid on this declaration type. It is
  only valid on 'class' declarations.

    [ServiceContract(Namespace = "API.Trade")]
    [AspNetCompatibilityRequirements(RequirementsMode =
        AspNetCompatibilityRequirementsMode.Allowed)]
    public interface ITradeService
    {
        [OperationContract(Name = "GetAllCategories")]
        string GetCategories(string itemtype, string keywordstring);

        [OperationContract(Name = "GetCategoryByNodeLevel")]
        string GetCategories(int NodeLevel);

        [OperationContract]
        int GetTrades(string KeywordString, string TradeType);
    }

THE SECOND question is, in the ASPX ScriptManager tag:
 <asp:ScriptManager ID="ScriptManager1" runat="server">
 <Services>
 <asp:ServiceReference Path="?" />
 </Services>
 </asp:ScriptManager>

I notice that the Path= attribute should be pointing to a .SVC file. So far, I have
successfully been using a WCF Class Library to accomplish what I need. The Class Library
has the Trade.cs, TradeService.cs, and ITradeService.cs files which I compile and then
reference as my Web Service in my Web project.
So, what should "Path=" be pointing to? Or, what do I need to add?
I am learning as I go and I appreciate your patience. Thanks in advance.

A: With respect to the first question. The attribute is defined to be only applicable to a class, so you can't declare it on anything else.
The path should point to the endpoint where your service is listening (e.g. /services/myserivce).

A: The path ought to be the service endpoint for an HTTP service: http://host.example.com/tradeservice.svc/method.
You can only apply the attribute to an implementation of the interface (a class) not the interface itself.

A: As for your second answer.  I believe the path needs to point to a actual webservice endpoint (.svc or the old one.. I forget off the top my head, sorry).
What you can do is create a WebService, TradeService.svc, and implement the ITradeService interface.  As a private variable on the service create a instance of TradeService, and use it as a proxy... like so
private TradeService _proxy;

public string MyMethod(){
    _proxy.MyMethod();
}

make sence.

A: *

*AspNetCompatibilityRequirementsAttribute.RequirementsMode is not a required attribute  and can be used for setting the hosting mode programmatically Or you can do the same
in webconfig by using serviceHostingEnvironment tag:

    <system.serviceModel>
    <serviceHostingEnvironment ..>
    </serviceHostingEnvironment>
    </system.serviceModel>

Reference : http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.aspnetcompatibilityrequirementsattribute.requirementsmode(v=vs.110).aspx

*

*You should add a service host(.svc) in your project by manually adding
TradeService.svc. You can also do same by adding new item > WCF
Service but that will override your service cs files. Once you have
your svc file added then you can add following line:

     &lt%@ ServiceHost Language="C#" Debug="true" Service="TradeService" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>

Note that WebScriptServiceHostFactory will automatically add ASP.NET Ajax endpoint to your service. Finally point your "path" attribute to this newly created "TradeService.svc".
You can test your service by visiting http://localhost.me/TradeService.svc
And Ajax support can be tested at http://localhost.me/TradeService.svc/jsdebug
Reference : http://berniecook.wordpress.com/2012/01/08/consuming-a-wcf-service-with-jquery-or-scriptmanager/
SourceCode : https://docs.google.com/open?id=0Bz2usIBCcor0NDQxZDc2ODYtNTUzMi00OTRlLTlhOGMtMGI4Y2RhNGIzYWNj


text:
Q: Flot Multi Axes Bar Chart with orderbars and categories plugins I've created a bar chart with Flot that uses two sets of data on one chart. Each set has it's own y-axis. I want the bars to be placed side-by-side, however when the chart is drawn, they overlap.

I tried using the orderbars plugin like so
{ data: d1, bars: {order: 1}, label: "Merchant Vol",  },
{ data: d2, bars: {order: 2}, label: "Residual Pmt", yaxis: 2}

but this results in the bars not rendering. I also use the categories mode / plugin.
I suspect it's a problem with using two y-axes. Is there a way to plot bar charts with multiple axes without the bars overlapping? Fiddle with code here.

A: The orderbars plugin is not compatible with the categories plugin. It works by moving each bar a little from its original position (e.g. the bar at x value 1 is shifted to 0.9 for one data series and to 1.1 for the other). That doesn't work when you have Jun-16 as x value.
The solution is to remove the categories plugin, use numeric x values and set the x axis ticks yourself. See the updated fiddle here.


text:
Q: SQL Server Libraries for Java I'm curious to find what SQL Server libraries are available for Java.
At present we are using the com.microsoft.jdbc.sqlserver.SQLServerDriver driver.  I think this was downloaded from the Microsoft site a while ago.
What alternative libraries are available?
Many thanks,
Andez

A: DataDirect is a well known alternative (used by many vendors) but also others such as

*

*connx

*attunity

*i-net

*Easysoft
JTDS is an open source alternative
NB: I have only used the MS driver, DataDirect and the i-net drivers suceccfully in production, mostly prior to the MS JDBC driver release.

A: Seconding the open source jTDS Driver.  It also works perfectly with Hibernate.


text:
Q: How can I get rdp to maximise to just one of my monitor when already logged in as mstsc /span? I have 2 monitors at work and 2 monitors at home.
When I log into work from home using mstsc /span, my work desktop appears correctly spread across my 2 home monitors.
Then I want to open another RDP session on my work machine. When I maximise that window, it now fills both of my home monitors. How can I make it just fill the monitor it is on - like it would if I was at work and NOT using mstsc /span?

A: The solution is to edit the file "default.rdp" created in your Documents forder.. You need to add a setting for "selectedmonitors:s:x,y,z,*".
If you want to know which number is your monitor, execute "mstsc /l" in ms-doc command.
As seen on
https://remotedesktop.uservoice.com/forums/266795-remote-desktop-services/suggestions/18010924-allow-ability-to-choose-subset-of-local-monitors-f
Scott Hanselman also answered inside a comment with his own blog. his solution is very detailed:
https://www.hanselman.com/blog/HowToRemoteDesktopFullscreenRDPWithJustSOMEOfYourMultipleMonitors.aspx

A: This is an old question but I'll suggest an answer now anyway in case someone lands up here.
It seems to me that to solve this problem there is no need for selectedmonitors in the RDP file. Instead of using /span to connect to work you should be using /multimon.
/span creates one big "screen" across your two home monitors. So when you go "fullscreen" in your work session it goes across them.
/multimon makes your work computer aware of your two-monitor setup. When you maximise a window or go full-screen it will do so in the way you'd expect.
As I have found recently, selectedmonitors could be useful if your primary monitor at home is not the one which you want to consider the primary in your work session.


text:
Q: How to hide a table row that has no unique id How to hide a table row  that has no unique id,  but row just contains TD with a specific text,
note that I cannot adjust the classnames or add ID's there either. Its nested TR.
eg.

            DO not hide this row

          100,39

            yes hide this row

          100,39

A: $("tr.SeparateRow:contains('something to find')").hide();

working example --> http://jsfiddle.net/ukJxH/1/


text:
Q: How to use JvisualVM to profile Spark on Yarn cluster? I know how to do this work on single executor host, just export JMX port.
But some potential performance issue only can be happened in large cluster, if we add JMX options to "spark.executor.extraJavaOptions", listen address of multiple executors on a host will conflict.
I also tried to start a jstatd daemon, but the visualvm can't do cpu profiling in this way(it has message on UI).
Is there way to profiling Spark application in large scale cluster especially pinpoint what does each thread do in some time and cpu cost profiling? Not considering commercial tools.


text:
Q: Inverse Mappings Saying right now: Yes, this is homework.  I'm not asking for an answer, but I would love any help into a general direction to look at this problem at.  I've been working on it now for hours and have not made any real progress.
Can a function, with a well defined inverse, be implemented to map 32 bit integers to 64 bit integers.  Do all functions from 32bit to 64bit integers have well defined inverses?

A: Of course not.
Take the identity function for example. All 32-bit values have an identity in the 64-bit value space (just use 0 in the top 32 bits, using only the bottom 32 bits for the value). However, any 64-bit value where the top 32 bits is not 0, will not have a corresponding value in the 32-bit value space.
The above is a layman's explanation, and is probably not rigorous enough as a homework solution (as intended). You'd do well to read up on the pigeonhole principle.


text:
Q: Pivot the SQL Server table and also merge two columns simultaneously I have following table named as 'TABLE'.

and My desired output should be as following.

A: The following query will return your expected result:
SELECT  Model,
        MAX(CASE WHEN Number = 1 THEN Series + '-' + Code ELSE '' END) AS SeriesCode1,
        MAX(CASE WHEN Number = 2 THEN Series + '-' + Code ELSE '' END) AS SeriesCode2
FROM TestTable
GROUP BY Model

Demo with sample data:
DECLARE @TestTable TABLE (Model VARCHAR (10), Series VARCHAR (10), Code VARCHAR (10), Number INT);

INSERT INTO @TestTable (Model, Series, Code, Number) VALUES
('AB708', 'D07', '2015-01', 1),
('AB708', 'D07', '2014-11', 2),
('CB708', 'ED07', '2011-08', 1),
('CB708', 'ED07', '2012-10', 2);

SELECT  Model,
        MAX(CASE WHEN Number = 1 THEN Series + '-' + Code ELSE '' END) AS SeriesCode1,
        MAX(CASE WHEN Number = 2 THEN Series + '-' + Code ELSE '' END) AS SeriesCode2
FROM @TestTable
GROUP BY Model

Output:
Model   SeriesCode1     SeriesCode2
--------------------------------------
AB708   D07-2015-01     D07-2014-11
CB708   ED07-2011-08    ED07-2012-10


text:
Q: How to unlock the boot partition in GParted First of I am a total noob in Ubuntu and have never used a Linux-based system before.
Just to give you an image of how little knowledge I have:
I am at the point where I am trying to understand the "Terminal" concept. I've used it to install programs and type in certain commands.
To the question:
I bought a Notebook that had Ubuntu installed and right now I am trying to create a Windows partition. I got GParted running, but unfortunately my boot partition is somehow locked (there's a key symbol in front of the name). I'd like to unlock it and format it to NTFS.
The 3 installed partitions are:

*

*dev/sda1 ... FAT32 ... 10GiB ... hiden,lba..............unlocked->I could format this one

*dev/sda2 ... EXT4 ... 452.16GiB ... boot.................locked-> this one I'd like to format to NTFS

*dev/sda3 ... linux-swap ... 3.6 GiB

I tried to format it from the Windows CD, but the "format" option was locked.
I treid the command line:
umount /dev/sda2

as root, but only got back:
umount: /: device is busy.
        (In some cases useful info about processes that use
         the device is found by lsof(8) or fuser(1))

Thx 4 the help!

A: *

*There is no reason for boot to be NTFS if you want both Ubuntu and Windows. The problem you face is that Microsoft wants the Windows operating system as the FIRST operating system on the disc.

The easiest method to fix this is to format all discs, make 2 partitions where the 1st one is NTFS and the 2nd one EXT4 and then install Windows on the 1st and Ubuntu on the 2nd.
This will get you a GRUB with both Ubuntu and Windows in the menu.

*

*If you do want boot to be NTFS you will also want GRUB4DOS. So you will need to install that 1st. But this will NOT fix your problem of installing Windows. Grub demands support for permissions and symolic links and NTFS does not provide that so it is not possible for boot to be NTFS when using GRUB.


text:
Q: Cauchy sequences are bounded in every metric space A few days laid out an example, and asked for help, and @ shadow10 replied, his answer the question of can I find the
https://math.stackexchange.com/questions/879662/every-Cauchy-sequence-is-bounded
but please someone help me in relation to this question:
as would seem replies @ shadow10 in a space of arbitrary metric.
I know only that we should place absolute value $d (x, y)$.
Please help. Previously thank you

A: Let $(X,d)$ a metric space and $(x_n)_n$ a Cauchy sequence, and $a\in X$.
$\epsilon=1$. There is a $N$ such that $\forall m,n\ge N$
$$d(x_m,x_n)<1$$
by triangular inequality we have  $d(x_n,a)\leq d(x_n,x_N)+d(x_N,a)$, then for $n\geq N$ we obtain $d(x_n,a)\leq 1+d(x_N,a)=C$.
Then If we take $M=\max\{d(x_0,a),\dots,d(x_{N-1},a),C\}$.
Then $d(x_n,a)\le M\;\forall\,n\in \mathbb{N}$.


text:
Q: Password strengthening script - how to capitalise first letter and append list of integers to end of text in file and list it repeatedly Im currently writing a basic python script that is meant to do the following:

*

*Take a file of passwords as input

*Perform the following transformation on each password and write to a new file:

reverse it (e.g. password becomes drowssap)
substitute all 'o' for '0', 'a' for '4' and 's' for '5' (e.g. password becomes p455w0rd
makes the first character uppercase (e.g password becomes Password)
appends all years from 1900 to 2014 to the password, e.g. password1900, password1901,…,password2014

The "passwordlist.txt" in my example contains one line of text being "password".
My code so far is:
reading_file = open("passwordlist.txt", "r")

new_file_content = ""
for line in reading_file:
    stripped_line = line.strip()
    new_line = stripped_line.replace("a", "4").replace("o", "0").replace("s", "5").replace("d", "D")
    new_file_content += "\n" + new_line
reading_file.close()

writing_file = open("hashedpasslist.txt", "w")
years = map(str, range(1900, 2014))
writing_file.write(new_file_content[::-1])
writing_file.close()

I need assistance in making the first character of the output file uppercase, is you can see ive only managed to swap 'd' for 'D'. And lastly I'd like to append all years from 1900 to 2014 to the password, so the output should be e.g. Dr0w554p1900, Dr0w554p,…,Dr0w554p2014 preferably in a listed format.

A: You can uppercase the first character with the following snippet
string[0].upper() + string[1:]
Which in your code would be:
reading_file = open("passwordlist.txt", "r")

new_file_content = ""
for line in reading_file:
    stripped_line = line.strip()
    new_line = stripped_line.replace("a", "4").replace("o", "0").replace("s", "5")
    new_line = new_line[0].upper() + new_line[1:]
    new_file_content += "\n" + new_line
reading_file.close()

writing_file = open("hashedpasslist.txt", "w")
years = map(str, range(1900, 2014))
writing_file.write(new_file_content[::-1])
writing_file.close()

As for the years, you will want to iterate through each year, append it to the string and output it to a list.
eg.
output = []
for year in range(1900, 2015):
    appended_line = new_line + str(year)
    output.append(appended_line)

Your final code would look like this:
reading_file = open("passwordlist.txt", "r")
writing_file = open("hashedpasslist.txt", "w")

new_file_content = ""
for line in reading_file:
    reversed_line = line[::-1]
    stripped_line = reversed_line.strip()
    new_line = stripped_line.replace("a", "4").replace("o", "0").replace("s", "5").replace("d", "D")
    for year in range(1900, 2015):
        appended_line = new_line + str(year)
        new_file_content += "\n" + appended_line
        writing_file.write(new_file_content)

reading_file.close()
writing_file.close()

I made a couple changes. Firstly, the string is reversed at the start (I forgot, you can't reverse a string with reversed(), oops). Then, you'll see that for each password it loops through all the years, appends it to the password and finally writes it to the file.


text:
Q: Video Stream / Hosting Our client wants us to update their web application by adding video capabilities.
It's kind of like YouTube, but with accounts and video privacy. It should be able to stream videos, both live and recorded.
Instead of developing a custom application, we just decided to get a out of the box application. It can be open source, but we're willing to try out licensed offerings. Do you guys have any suggestions as to what we can use?
The web application is in .Net 2.0 by the way.

A: Yep - the easiest way to do this in all honesty is with the Flash Media Server - or a compatible piece of software. You can then use a Flash/Flex application to utilize the media itself. There are several similar packages to the FMS which are compatible, though I can't pull a name out of my head tonight (Google will help you.)
This is pretty standard and you'll find a wealth of tutorials to help you online.

A: you could consider
http://www.kyte.com/
http://influxis.com/applications/
http://www.uvault.com/
thanks

A: To stream both live and recorded videos, live video streaming with flash media server or wowza server would be the best option. These software brings out the streaming with multiple playback clients and devices too.

A: Windows baed? Windows Media Services can do that for the last 15 years or so, part of the windows oeprating system anyway.


text:
Q: How to reload the page in asp? I have 2 dropdown list boxes in my asp page where I need to select category and sub-category.
Sub-category dropdown list will be populated based on the category dropdown list box selection.
The problem is the sub-category list box is not loading accordingly when i select an item in category list box.
So I am going to previous page and click on the button to get the current page(where cateory & sub category list boxes are located) and selecting the sub category details(now sub category list box got loaded).
Is there any way to stay on the current page and get the sub category list box loaded for selection at first time itself.
Please any one help..

A: Set AutoPostBack=true and handle ChangeItem event at category dropDown.

A: @Kanchana: This should help get you started -- http://www.satya-weblog.com/2009/08/jquery-ajax-example-of-select-values.html


text:
Q: php mysql error when empty result is returned I am using the code below to check the password. Its working fine while the user name i enter into form is in database. but if the username is not available then foreach throws error.
   <?php
    $u=$_REQUEST['loginname'];
    $P=$_REQUEST['loginpass'];
    $pas=md5($P);
    $server="localhost:3306";
    $user="root";
    $pass="prabhs226";
    $database="sugar";
    $conn=mysqli_connect($server,$user,$pass);
    mysqli_select_db($conn,$database);
    $sql=("select b_pass from ub_per where b_id='$u' or b_email= '$u';");
    $res = mysqli_query($conn,$sql);

    $row = mysqli_fetch_array($res,MYSQLI_ASSOC);

    foreach($row as $value){
    $value;}

    if($value==$pas){
    echo "password matched";
    }
    else{echo"not matched";}
    ?>

I am getting this error:

PHP Warning:  Invalid argument supplied for foreach() in E:\noname\name\logged.php on line 19
      PHP Notice:  Undefined variable: value in E:\noname\name\logged.php on line 22.

plus i want to know if there is any way to define DB credentials ony once for compelete website.

A: $storeVal = '';
    if(!empty($row))
       foreach($row as $value){
        $storeVal = $value;
}
if($storeVal==$pas){
    echo "password matched";
    }
    else{echo"not matched";}

Store value on scope variable, $value scope within foreach loop

A: The problem is your $value attribute is just laying there, echo it or store it somewhere:
Print it
foreach($row as $value){
    echo $value;
}

Or Store it
foreach($row as $value){
    $valueStore = $value;
}

A: I agree with Luthando Loot. Also if you want to define DB credentials ony once for compelete website. You can make a constant file with the credentials and include that to a function file where you make connection to the database. After that include the connection function in your script. this way you dont have to write a script to connect everytime you need the database. Just include it and its good to go.
EXAMPLE
constants.php
/**
 * Database Constants - these constants are required
 * in order for there to be a successful connection
 * to the MySQL database. Make sure the information is
 * correct.
 */
define("DB_SERVER", "localhost");
define("DB_USER", "User_db");//enter your database username
define("DB_PASS", 'Pass_db');//databse password
define("DB_NAME", "Name_db");//database name

database.php
/**
 * Database.php
 *
 * The Database class is meant to simplify the task of accessing
 * information from the website's database.
 */
include("constants.php");

try {
    $db = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USER, DB_PASS); //Initiates connection
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Sets error mode
}
catch (PDOException $e) {
    file_put_contents("log/dberror.log", "Date: " . date('M j Y - G:i:s') . " ---- Error: " . $e->getMessage() . PHP_EOL, FILE_APPEND);
    die($e->getMessage()); // Log and display error in the event that there is an issue connecting
}

Keep in mind that this is a PDO connection not a mysqli. This is just an example of how to work with constants so it could be used for the whole site.

A: Try this.
<?php
    $u=$_REQUEST['loginname'];
    $P=$_REQUEST['loginpass'];
    $pas=md5($P);
    $server="localhost:3306";
    $user="root";
    $pass="prabhs226";
    $database="sugar";
    $conn=mysqli_connect($server,$user,$pass);
    mysqli_select_db($conn,$database);
    $sql=("select b_pass from ub_per where b_id='$u' or b_email= '$u';");
    $res = mysqli_query($conn,$sql);

    if($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) {
        if($row['b_pass'] == $pas){
            echo "password matched";
        }
        else{
            echo"not matched";
        }
    }
    else{
        echo"not matched";
    }
?>

A: Im using PDO
<?php    $u=$_REQUEST['loginname'];
 $P=$_REQUEST['loginpass'];
 $pas=md5($P);
 $db = new PDO('mysql:host=localhost;dbname=sugar', 'root' , 'prabhs226');
 $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
 $stmt=$db->prepare("select b_pass from ub_per where b_id= :id or b_email= :email;");
 $stmt->bindParam(':id', $id, PDO::PARAM_INT);
 $stmt->bindParam(':email', $email, PDO::PARAM_STR);
 $stmt->execute();
 $row = $stmt->fetch();
 if($row){
   $row['b_pass']=$value;
 }
 else{
   echo "invalid user name ";
 }
 if($value==$pas){
   echo "password matched";
 }
 else{
   echo "not matched";
 }
?>


text:
Q: Most efficient endless loop in C# (carousel) Assuming a list of objects, each with an ID, what's the most efficient way of building a carousel, so that each object knows what its previous and next item is. The Last Item's previousId will link to the first item. The first item's previousId will link to the last.
I need the ID of the previous and the ID of the next, as this will be used to populate next and previous buttons on a web page.
I know I could iterate over them, adding placeholders for _next and _prev id, but what's the most efficient way to do this?
I figure my object should look like this:
class Item {
    public int Id { get; set; }
    public string ItemName { get; set; }
    public int Next { get; set; }
    public int Prev { get; set; }
}

SO, if I have a List<Item> items how can I most efficiently add the previous and next IDs to each item?
    int _prev = items.LastOrDefault().id;
    int _next = items.Count > 1 ? items[1].id : _prev;
    foreach (var i in items) {
        i.prev = _prev;
        i.next = (_next <
        _prev = i.id;
        //_next = ???
    }

I think I'm looking at this wrong way. Is there a better way of doing this?

A: If you don't want to use LinkedList and willing to use indexes instead of foreach as Marc Gravel suggested:
int count = items.Length;
for(int index = 0; index < count; index ++)
{
  item.Next = items[(index + 1) % count];
  item.Prev = items[(index - 1 + count) % count];
}

A: Use a LinkedList to hold your objects.


text:
Q: JavaScript tag system: show only the divs that have all the classes listed in an array, else hide Please explain how to do this!
I want to be able to hide/show a div based on its classes and an array.
If something is in an array, then it will only show divs which have the something class.
If nothing is in an array, every div will be shown.
If something and johnskeet are in the array, then it will only show divs which have both the something and johnskeet classes.

A: At a high level, one option would to have all of the divs hidden by default and then use document.querySelectorAll() to apply an 'unhidden' style to each div that is in the array.
Here is a question that should help with selecting divs with multiple classes that should help as well.
queryselectorAll - find an element with more than one matching class

A: Assuming the elements are initially shown, you only need to hide the undesired ones. You can insert a stylesheet with
var rule = array.map(c => 'div:not(.' + CSS.escape(c) + ')').join()
           + '{display:none}';
sheet.insertRule(rule, 0);

var array = ["something", "johnskeet"];
var rule = array.map(c => 'div:not(.' + CSS.escape(c) + ')').join() + '{display:none}';
var style = document.createElement('style');
document.head.appendChild(style);
var sheet = style.sheet;
sheet.insertRule(rule, 0);

foo

something

something johnskeet

something johnskeet foo bar

However, if some elements may already be hidden, you will need to set the desired display with higher specificity. The problem is that some elements are by default block-level, and some are inline-level. jQuery's toggle can be helpful to detect that:
$('div').each(function() {
  $(this).toggle(array.every(c => this.classList.contains(c)));
});

var array = ["something", "johnskeet"];
$('div').each(function() {
  $(this).toggle(array.every(c => this.classList.contains(c)));
});

foo

something

something johnskeet

something johnskeet foo bar

Another option would be display: revert, but it's not widely supported yet.

A: I would recommend you to dynamically generate appropriate selector from the array, show all the matching elements and hide all other elements by default:
JavaScript
const classes = ['foo', 'bar', 'baz']
     ,selector = classes.map(x => '.' + x).join('')
$(selector).show()

CSS
div {
  display: none;
}

See demo on JS Fiddle.

Alternatively, if you work on a high amount of elements, it would be better to generate appropriate style sheet in JavaScript:
const classes = ['foo', 'bar', 'baz']
     ,selector = classes.map(x => '.' + x).join('')
     ,$style = $(`<style>div {display: none;} div${selector} {display: block;}</style>`)

$('head').append($style)

To revert that, simply remove the


text:
Q: Сортировка в yii2 Мне нужно сделать сортировку.
Средствами yii2, согласно документации делается так .
function actionIndex()
{
    $sort = new Sort([
        'attributes' => [
            'age',
            'name' => [
                'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
                'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Name',
            ],
        ],
    ]);

    $models = Article::find()
        ->where(['status' => 1])
        ->orderBy($sort->orders)
        ->all();

    return $this->render('index', [
         'models' => $models,
         'sort' => $sort,
    ]);
}

Работает нормально. Но , мне нужно немного сложнее запрос сделать.
Вот такой запрос
SELECT * , (object_info.price / ( SELECT price_type.course FROM price_type WHERE price_type.id = object_info.price_type_id)) AS real_price FROM object_info ORDER BY real_price

Так вот как его туда прописать строкой запроса ??
Пытался вот так
$query = ObjectInfo::find();
        $sort = new Sort([
            'attributes' => [
                'created_at',
                'price' => [
                    $query->select(['*', 'real_price' => 'SELECT * ,
                    (object_info.price / ( SELECT price_type.course FROM price_type WHERE price_type.id = object_info.price_type_id))
                    AS real_price
                    FROM object_info
                    ORDER BY real_price']),
                    'asc' => ['real_price' => SORT_ASC],
                ],
            ],
        ]);

Не работает, пишет что real_price не найдет в таблице. Все так, вот такому определению просто имя задано
(object_info.price / ( SELECT price_type.course FROM price_type WHERE price_type.id = object_info)) AS real_price

Как тогда сделать?

A: Укажите select в конструкторе запроса, класс yii\data\Sort не поддерживает каких либо конструкций с запросами.
$sort = new Sort([
    'attributes' => [
        'created_at',
        'price' => [
            'asc' => ['real_price' => SORT_ASC],
        ],
    ],
]);

$query = ObjectInfo::find()
     ->select(['*', 'real_price' => 'object_info.price / ( SELECT price_type.course FROM price_type WHERE price_type.id = object_info.price_type_id)')
     ->orderBy($sort->orders);

$models = $query->all();


text:
Q: Making multiple queries to posgresql database through R shiny UI I am building a Shiny dashboard that will allow me to select certain data from my postgresql database. I am new to shiny and postgresql so I appreciate your input on this. I am aiming at having a dynamic input from User, say click to select a  name, a type, then the location for a certain data. And that the user can select it from a 3 selectinput widgets. The process of selecting the items will allow query of the data in the database. Lets say I have 7 names, 2 types and 3 locations.. so selecting a name, then a type, then a location will give me a part of the data.
This is what my initial code looks like, but it does not give me any data showing up. I checked the connection and its working, it just doesn't can not find the data I am looking for plotting and displaying so I get an empty dashboard with no table or plot. Any idea how to go about this?

library(shiny)
library(shinydashboard)
library(RColorBrewer)
library(leaflet)
library(dplyr)
library(ggplot2)
library(tidyverse)
library(fpp)
library(plotly)
library(sp)
library(RPostgreSQL)
library(DBI)
library(pool)

#####

pool <- dbPool(drv = dbDriver("PostgreSQL", max.con = 100), user = "user", password = "pswd", host = "localhost", port = 5432, dbname = "people", idleTimeout = 3600000)

##list of people names
All<-tbl(pool, "table")
All%>%group_by(name)
names_All<- dbGetQuery(pool, "SELECT name FROM table GROUP BY name") ## list of names another way
type_grouped<- dbGetQuery(pool, "SELECT type FROM table GROUP BY type")
loc_grouped<- dbGetQuery(pool, "SELECT location FROM table GROUP BY location")

####

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput(
        inputId = "name",
        label = " name",
        choices = names_All,
        selected = 1,
      ),
      selectInput(
        inputId = "type",
        label = " type",
        choices = type_grouped,
        selected = 1,

      ),
      selectInput(
        inputId = "location",
        label = " location",
        choices = loc_grouped,
        selected = 1,
      )
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("graph", plotOutput("plot")),
        tabPanel("Table", dataTableOutput("table"))
      )
    )
)
)

server <- function(input, output, session) {

  selectedData <- reactive({
    req(input$name)
    req(input$type)
    req(input$location)
    query <- glue::glue_sql(
      "SELECT * FROM table
       WHERE name IN ({name*})
       AND type IN ({type*})
       AND location IN ({location*});",
      name = input$name,
      type = input$type,
      location=input$location,
      .con = pool)
    outp <- as.data.frame(dbGetQuery(pool, query))
    outp

  })

  output$table <- DT::renderDataTable({
    DT::datatable(  data = selectedData(),
                   options = list(pageLength = 14),
                    rownames = FALSE)

  output$plot <- renderPlot({
    ggplot( data = selectedData(), aes(x = date, y = name )) + geom_point()
  })

}

shinyApp(ui = ui, server = server)

App running result

A: Consider integrating a submit button to trigger processing of server code via an eventReactive call. This even helps user understand the flow of form controls and processing. Also, right now you use SQL's IN redundantly since input choices are only single values. But use multiple=TRUE argument in selectInput() to adjust that (with note to user).
User Interface
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput(
        inputId = "name",
        label = " name",
        choices = names_All,
        selected = 1
      ),
      selectInput(
        inputId = "type",
        label = " type",
        choices = type_grouped,
        selected = 1
      ),
      selectInput(
        inputId = "location",
        label = " location",
        choices = loc_grouped,
        selected = 1
      ),
      actionButton("submit", "Submit")        # NEW SUBMIT BUTTON
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("graph", plotOutput("plot")),
        tabPanel("Table", dataTableOutput("table"))
      )
    )
  )
)

Server Function
server <- function(input, output, session) {

  name_pick <- reactive({ req(input$name) })
  type_pick <- reactive({ req(input$type) })
  location_pick <- reactive({ req(input$location) })

  selectedData <- eventReactive(input$submit, { # INITIATE ON submit
    query <- "SELECT *
              FROM table
              WHERE name = ?name
                AND type = ?type
                AND location = ?location;"

    stmt <- DBI::sqlInterpolate(pool,
                                query,
                                name = name_pick(),
                                type = type_pick(),
                                location = location_pick())

    outp <- dbGetQuery(pool, stmt)
  })

  output$table <- DT::renderDataTable({
    DT::datatable(data = selectedData(),
                  options = list(pageLength = 14),
                  rownames = FALSE)
  })

  output$plot <- renderPlot({
    ggplot(data = selectedData(), aes(x = date, y = name )) +
       geom_point()
  })

}

Also, try avoiding SELECT * and explicitly define needed table and graph columns in specific order to control output of your Shiny result. Plus, it helps with readability and maintainability of code.


text:
Q: Is irqbalance a bad thing? I am using cpufreq gnome extension and it give's me warning irqbalance detected. Is that something to worry about? And if I somehow stop irqbalance will that affect the processor?

A: this FAQ explains what it is. It balances load on the cores, which is good for servers. On desktop that means you cannot get 100 proc on any core because allready used for other processes.

A: IRQ stands for Interrupt Request and basically is where the CPU can expect a particular device to interrupt it when a device sends the computer signals about its operation. For example, when a printer has finished printing, it sends an interrupt signal to the computer.
IRQBalance is a Linux daemon that distributes interrupts over among the processors and cores in your computer system. It's mostly used in a server configuration where multiple devices like network cards, hard drives and whatnot will be competing for CPU's attention and it helps distribute hardware interrupts across processors on a multiprocessor system in order to increase performance.
For a workstation or laptop, cpufreq's author recommends uninstalling irqbalance and states his reasons:

*

*irqbalance doesn't support fully all kernel features to an example a turning on/off core threads supported by the extension. If you have installed irqbalance package and turn off some cores you can get freezes or not working devices like wi-fi, bluetooth, video cards, sound cards…

*irqbalance is not a part of the Linux kernel.

*It designed for special server configurations with many RAID/HDD/SDD controllers.

*Only Debian Flowers have the irqbalance installed because Debian is very Server oriented. Red Hat doesn't have installed irqbalance by default but it doesn't make Red Hat less server OS.

*It keeps all Linux core threads working so its not good for power saving, especially for laptops.

*Any user-space application (like games, compilation…) can not get 100% of CPU resources on any thread because it's always sharing this resources with IO tasks.

I'll add on top of that two more reasons on when one should not use IRQBalance:

*

*Manually pinning apps/IRQ's to specific cores for a very good reason (low latency, realtime requirements, etc.)

*Virtual Guests. It does not really make sense because unless you are pinning the guest to specific CPUs and IRQs and dedicated net/storage hardware, you will likely not see the benefits you would on bare metal.

TL/DR: to uninstall it, just sudo apt-get remove irqbalance and reboot your machine.


text:
Q: code is running twice after click a href I have on main_forum.php:
hello

this goes to page process.php where is:
if ($page=="forum"){
    if($page_1=="view"){
        include "view_topic.php";
    }
    else{
        include "main_forum.php";
    }
}

on page view_topic.php is:
$s_id=$page_2;
$sql="SELECT view FROM forum_question WHERE id='$s_id'";
$result=mysqli_query($db_handle2, $sql);
$rows=mysqli_fetch_array($result);
$viewer=$rows['view'];
...
$viewer++;
$sql="UPDATE forum_question SET view='$viewer' WHERE id='$s_id'";
$result=mysqli_query($db_handle2, $sql);

My problem is, when I click on a href hello SQL UPDATE should rise 1 in view column. However it rise 2. It looks the whole code runs twice.
when I change:
hello

and
$s_id=$_GET['id'];

SQL UPDATE rise 1 in view column. It is rised only once.

A: You can simple run update query to increasing count as:
$sql="UPDATE forum_question SET view=view+1 WHERE id='$s_id'";

This will work 100%. I've tested myself.


text:
Q: Conversion failing from string to float/double I have issue with my conversion from string to double/float. It is so strange when I run application on my local machine it working great. But when I run it on Hosting4Real hosting it making so much decimals.
E.g.
code
$number = "5.30";
$convNum  = (float)$number;
echo $convNum;

output
5.29999999999999982236431605997495353221893310546875

I have tried number_format() and it works but it's converting to string, I have tried with round and nothing happens.
It's so strange and logic wired that I can't understand why it doesn't work.

A: Instead of casting, I'd use floatval().
$number = "5.30";
$convNum = floatval($number);
echo $convNum; // 5.3

If you're wanting to retain decimal point precision, you can use number_format() in conjunction.
$number = "5.30";
$convNum = number_format(floatval($number), 2); // 2 dp
echo $convNum; // 5.30


text:
Q: jsPDF: How to render Ä Ü Ö? I am using jsPDF to create a pdf file from a webpage. I like to add a text but if use ä ö ü it won't be rendered correctly.
I tried to add Unicode characters to my pdf using the documentation, but the docs they have added for the library related to the Unicode part doesn't include any examples. It would be great if you could provide an example.
This is my code:
function doDocData(doc) {
    var number_of_pages = doc.internal.getNumberOfPages()
    var pdf_pages = doc.internal.pages

    doc.setFontStyle('normal');//optional
    for (var i = 1; i < pdf_pages.length; i++) {
        doc.setPage(i)

        var strl = 'I like to add Ä Ü Ö';
        doc.setFontSize(10);// optional
        doc.text(strl, 20, doc.internal.pageSize.height - 10);//key is the interal pageSize

        var str = 'Seite ' + i  + ' von ' +  number_of_pages;
        doc.setFontSize(10);// optional
        doc.text(str, doc.internal.pageSize.width - 80, doc.internal.pageSize.height - 10);//key is the interal pageSize
    }
}

A: For utf-8 encoded Characters like Ä, Ö, Ü you need to include a font, that is utf-8 encoded (like it is stated in the Documentary: Use of Unicode Characters / UTF-8) since jsPDF by default contains only ASCII font.
A font like this (ARIAL utf-8 ATTENTION: opens download of arialuni.ttf) can be converted by jsPDF own fontconverter.
You can find a code example how to include the converted font here: setFont in jsPDF


text:
Q: reading and writing to s3 node js I have a problem but I don't know how to solve it.
I reading a file from s3, then I save it to a folder(downloads). After that, I read the file that I saved in the folder (that I saved in downloads) and re-size it + save it in a different folder with a different name (resized).
Then, I want to read again this file in order to upload it again in its the new size but when I try to do that it throws an error that there is no such file in this directory but when I check it in my folder it dose.
My guess it's trying to read before the image is written in the new folder (resized)
How can I fix it?
update
so accroding to commits this is what I did but it disen't print out anything in fs.readFileAsync.
Why?
var image = new ImageResize(__dirname +'/../downloads/'+ hash + '.png');
  image.smartResizeDown({
    width: 200,
    height: 200
  }).then(function () {
    image.stream(function (err, stdout, stderr) {
        var writeStream = fs.createWriteStream(__dirname +'/../resized/'+ hash + 'resize.png');
        stdout.pipe(writeStream);

}).then(function(){
  fs.readFileAsync('C:/Users/user/Desktop/cloud/new/resized/'+hash+'resize.png', function(error, buf){

    if(error)
      console.log(error);
    else
      console.log('yay');
});
});

});

A:

var image = new ImageResize(__dirname +'/../downloads/'+ hash + '.png');

image.smartResizeDown({
    width: 200,
    height: 200
})
.then(function () {
    return new Promise(function(resolve, reject) {
        image.stream(function (err, stdout, stderr) {
            var writeStream = fs.createWriteStream(__dirname +'/../resized/'+ hash + 'resize.png');
            stdout.pipe(writeStream);

            resolve();
        })
    });
})
.then(function(){
    fs.readFileAsync('C:/Users/user/Desktop/cloud/new/resized/'+hash+'resize.png', function(error, buf) {
        if(error)
          console.log(error);
        else
          console.log('yay');
    });
    return null;
});

Assuming bluebird object is in Promise named variable.


text:
Q: I checked out to a previous commit in git repo. Did some changes and made a commit there. Pushing changes to master branch says everything up to date I checked out to a previous commit in my master branch. Then did some changes and made a commit there itself. Now I wish to push the changes to master branch. But it says everything up-to-date.
In short I did this,

*

*git checkout 573789f3 (a previous commit in master branch)

*Made some changes there and commited them there itself.
git add .
git commit -m "message"

*Now when I do git push origin master, I get Everything up-to-date
Also, I want this commit to be the HEAD of the master branch

A: The problem is that once you checkout a commit, you are no longer on master. So when you push master it's up to date because it's unchanged!
Am I right that you want to remove the latest commit, and add a commit of your own.
I would suggest you do it like
git checkout master # if you didn't do it already
git reset --hard 573789f3  # Or HEAD~
<do your changes>
git commit -am 'message'
git push --force # The --force will be necessary as you are obliterating the previous HEAD commit


text:
Q: CSS Divider/Text Positioning I am having a bit of dilemma here with a CSS divider. Take a look: http://jsfiddle.net/fVxC6/1/
.div-line {
    border-bottom: 1px solid #f0f0f0;
    border-top: 1px solid #f0f0f0;
    width: 100%;
    float: left;
    height: 1px;
    display: inline-block;
    margin: -14px 0 25px 0;
}

What i am trying to achieve is to have the text in the middle and a padding of say, 5px applied to it.
I have tried centering the text and applying a border-right and border-left but that didn't work (and that wouldn't have been the actual desired result as shown on demo, i have 2 lines which are actually the border-top and border-bottom properties).
I am almost sure there has to be a better solution than applying the border-top & bottom and without using images but i couldn't find it..
UPDATE: That is somewhat near what i tried to achieve but not exactly, probably i was not clear enough. I want the text to be positioned in the center - what is achieved with your code, but i also want it to "push" those borders, like 5 pixels to the left and 5px to the right, so a gap is created between them where the actual centered text is positioned

A: I took a different route then you since you to my reasoning you have to look at all elements as text and hence display them inline.
.div {
    width:960px;
    text-align:center;
}

.divider {
    font-size: 16px;
    font-weight: 400;
    background-color: #fff;
    padding-right: 10px;
        display: inline-block;
    width:10%;
    padding: 0 3px;
    vertical-align: middle;
}

.div-line {
    border-bottom: 1px solid #f0f0f0;
    border-top: 1px solid #f0f0f0;
    width: 40%;
    height: 1px;
    display: inline-block;
    vertical-align: middle;
}

Here's a fiddle


text:
Q: I'm having an Issue with a simple HTML/jQuery page I have been working on this problem for 3 days, and I still have no answer to this problem I'm facing, it must be simple I just can't figure it out.
I'm using HTML and jQuery for a simple jQuery/HTML page to navigate 3 pages.
the problem is that when I swipe between pages I have kind of layout flash, for the first second after I swipe I see the page resizing and showing the first page for a flash second, and then the page would be normal again.
Here is my code :
JS FIDDLE LIVE DEMO

var newsnum=10;
var i=1;
 $("body").on("swipeleft",function(){
 if (i<newsnum) {
   i++;
   $.mobile.changePage('#p'+i, {
      allowSamePageTransition :true,
            transition: "fade"});
   }});
   $("body").on("swiperight",function(){
    if (i>1) {
      i--;
      $.mobile.changePage('#p'+i, {
        allowSamePageTransition :true,
        transition: "fade",
        reverse: true });
     }
   });

 111111111

 Touchée à la cheville droite la semaine passée, la milieu de terrain Sandie Toletti (Montpellier) ne sera pas opérationnelle pour la Coupe du Monde au Canada (6 juin au 5 juillet). C'est sa coéquipière au MHSC Marina Makanza qui la remplace.

Communiqué de la FFF\
Dimanche 3 mai dernier, lors du match de D1 féminine entre Juvisy et Montpellier, Sandie Toletti s'est blessée à la cheville droite.

Les staffs médicaux du HSC Montpellier et de l'Equipe de France féminine ont constaté son indisponibilité pour une longue durée. D'un commun accord, ils ont laissé la milieu de terrain à la disposition de son club.
Retenue parmi les sept réservistes pour la prochaine Coupe du Monde féminine (6 juin - 5 juillet au Canada), elle est remplacée par Marina Makanza (HSC Montpellier).

À l'exception des joueuses du Paris SG, qui disputeront jeudi la finale de la Ligue des Champions, les Tricolores entameront demain (lundi) au Centre National du Football (CNF) à Clairefontaine (Yvelines) leur préparation pour la Coupe du Monde de la FIFA.

        Touchée à la cheville droite la semaine passée, la milieu de terrain Sandie Toletti (Montpellier) ne sera pas opérationnelle pour la Coupe du Monde au Canada (6 juin au 5 juillet). C'est sa coéquipière au MHSC Marina Makanza qui la remplace.

Communiqué de la FFF\
Dimanche 3 mai dernier, lors du match de D1 féminine entre Juvisy et Montpellier, Sandie Toletti s'est blessée à la cheville droite.

Les staffs médicaux du HSC Montpellier et de l'Equipe de France féminine ont constaté son indisponibilité pour une longue durée. D'un commun accord, ils ont laissé la milieu de terrain à la disposition de son club.
Retenue parmi les sept réservistes pour la prochaine Coupe du Monde féminine (6 juin - 5 juillet au Canada), elle est remplacée par Marina Makanza (HSC Montpellier).

À l'exception des joueuses du Paris SG, qui disputeront jeudi la finale de la Ligue des Champions, les Tricolores entameront demain (lundi) au Centre National du Football (CNF) à Clairefontaine (Yvelines) leur préparation pour la Coupe du Monde de la FIFA.

 2222222222

 Touchée à la cheville droite la semaine passée, la milieu de terrain Sandie Toletti (Montpellier) ne sera pas opérationnelle pour la Coupe du Monde au Canada (6 juin au 5 juillet). C'est sa coéquipière au MHSC Marina Makanza qui la remplace.

Communiqué de la FFF\
Dimanche 3 mai dernier, lors du match de D1 féminine entre Juvisy et Montpellier, Sandie Toletti s'est blessée à la cheville droite.

Les staffs médicaux du HSC Montpellier et de l'Equipe de France féminine ont constaté son indisponibilité pour une longue durée.res entameront demain (lundi) au Centre National du Football (CNF) à Clairefontaine (Yvelines) leur préparation pour la Coupe du Monde de la FIFA.

        Touchée à la cheville droite la semaine passée, la milieu de terrain Sandie Toletti (Montpellier) ne sera pas opérationnelle pour la Coupe du Monde au Canada (6 juin au 5 juillet). C'est sa coéquipière au MHSC Marina Makanza qui la remplace.

Communiqué de la FFF\
Dimanche 3 mai dernier, lors du match de D1 féminine entre Juvisy et Montpellier, Sandie Toletti s'est blessée à la cheville droite.

Les staffs médicaux du HSC Montpellier et de l'Equipe de France féminine ont constaté son indisponibilité pour une longue durée. D'un commun accord, ils ont laissé la milieu de terrain à la disposition de son club.
Retenue parmi les sept réservistes pour la prochaine Coupe du Monde féminine (6 juin - 5 juillet au Canada), elle est remplacée par Marina Makanza (HSC Montpellier).

À l'exception des joueuses du Paris SG, qui disputeront jeudi la finale de la Ligue des Champions, les Tricolores entameront demain (lundi) au Centre National du Football (CNF) à Clairefontaine (Yvelines) leur préparation pour la Coupe du Monde de la FIFA.

 3333333333

 Dimitri Payet affichait un grand soulagement après la victoire de son équipe à l'arraché face à Monaco. Le meneur de jeu de l'OM a avoué qu'à un moment de la rencontre, il se demandait même comment Marseille pourrait ne serait-ce que prendre un point.

« Honnêtement, à un moment, on a senti que ça allait être très compliqué, même d'égaliser, avouait le meneur de jeu de l'OM Dimitri Payet sur Canal Plus après la victoire renversante de son équipe face à Monaco dimanche soir (2-1, 36eme journée de L1). Mais contrairement à d'autres matchs où on dominait et où on se faisait contrer à la fin, là, on n'a peut-être pas été beaux à voir jouer mais on a su être efficaces. On ne va pas faire la fine bouche, on va savourer, parce que si on n'avait pas gagné ce soir, on pouvait dire adieu au podium. Eux (les supporters), on n'a rien à leur reprocher. On dit que c'est un public difficile, mais, cette année, malgré beaucoup de faux-pas de notre part, ils ont toujours été là. Ce soir encore, c'était plein. Et quand ça pousse comme ça, ça donne de l'énergie. »\
« On dépend encore de Monaco »\
« Les changements ? C'est le coach, c'est lui qui décide, nous on essaye de s'adapter au mieux, poursuivait l'ancien Stéphanois. Il y a eu beaucoup de critiques sur ça. Ce soir, ça marche et ça paye. On va savourer car c'est une victoire très importante. Malheureusement, on n'a pas encore notre destin entre les mains, on dépend encore de Monaco. On revient à la hauteur de Saint-Etienne, les derniers matchs vont être très importants, ça va être chaud.


text:
Q: Messenger requires secure callback url When creating a Messenger chat bot you must force people to subscribe to your page before they can use it.
To do this you need a Secure Callback URL, a standard http:// address won't do, it must be https://
I don't have a Secure Callback URL to my disposal. Can anyone recommend a site/way for me to get one?

A: You can configure your domain name with cloudflare to use it as a proxy between the user & your webserver.
You can enable their flexible SSL which is free of charge and very easy to configure. You can find more details here and here. I've recently configured my FB Chatbot webhook with cloudflare free SSL and it works pretty well.


text:
Q: Output Export in Mathematica I have a command line that generates lists as output and is running in a loop, so generates, multiple long lists. Each list is to be exported as a .txt file. How can I automate the name generation of the output files. I intend to use the same name as the input file but with the .txt extension in output of course.
For[
  i = 1,i < 3,i++,
  outdata = ReadList[ test[[i]], Record, RecordSeparators -> {{">"},{" "}} ];
  Print[outdata]
  ]

How can I automate the export?

A: Something like the following should do:
For[i = 1, i < 3, i++,
  outdata = ReadList[test[[i]], Record, RecordSeparators -> {{">"}, {" "}}];
  Export[FileBaseName[test[[i]]] <> IntegerString[3, 10, i] <> ".txt", outdata,"List"]
];

FileBaseName strips the file name in test[[i]] from its extension (if it has any). IntegerString[3, 10, i] generates strings of the form "001", "002", "003" etc. and <> (StringJoin) glues the substrings together.
There is a number of output formats you could use in Export. I chose "List" but you may want to examine the BasicFormats guide page for more.


text:
Q: About client/server Peachtree Accountant software We plan to setup client and server for peachtree accounting system.
currently, we have software Sage Peachtree Quantum 2010 Accountant, so could we use this
software for making client and server?
Do you have any ideas regarding this issue?

A: If the Quantum still uses the pervasive database, it uses the server side database to lock the files, and is very active. Depending upon your latency of connection it may or may not work out.  We used Peachtree Compete 2004 and were successful in connecting by VPN, with a mapped drive to the datapath, nut it was very slow, albeit the connections were very slow back then.  So this is a no answer answer, just an encouragement to setup a VPN and give it a try.  Our last current version is Peachtree apremium, and it will not run this way, nor will it run under terminal services, which is an alternate solution.  However, I am told that the latest versions will run under terminal services, as we are considering upgrading to such.   Sage's tech support is junk, so do not look directly to them for much help, however there are a lot of good VAR support companies that vary in competence and may be good for some assistance.  Good luck.


text:
Q: Imaginary part of a triple intragral I'm only an introductory calculus student(I just finished my high school AP calculus BC course) so I apologize if these questions seem a bit elementary.
I'm using Mathematica to perform a triple integration(that I do not know how to perform myself). The integration I am trying to perform is:
$$
GM  \sigma \int_a^b  2 \int_0^\frac{L}{2} 2 \int_0^\frac{W}{2} (  \frac{-1}{ \sqrt{x^{2}+ y^{2}      +z^{2} } } dx dy dz.
$$
Where G, M, and Sigma are constants. (Gravitational constant, Mass of object 1, and the density of object 2)
This integration represents the integration of the gravitational potential equation, over an area in 3-space. However, when calculating this integration using Mathematica, There is an imaginary component (which always seems to have a net sum of 0)
the input is
Integrate[ -1/Sqrt[x^2 + y^2 + z^2] , {z, a, b},
       {x, 0, L/2}, {y, 0, W/2},
       Assumptions -> {L > 0, W > 0 , z > 0, a > 0, b > 0 , b > a}] // AbsoluteTiming

the result is

My question is, where does this imaginary part come from? Also, Is there a way to simplify this equation (or create a more simple function which estimates the value with a high level of accuracy, similar to polynomial estimation for single variable functions)


text:
Q: Conflico entre SAP y Referencia Microsoft Outlook 15.0 Object Library en Macro Excel VBA Tengo un conflicto en mi macro, al añadir la referencia de Microsoft Outlook 15.0 Object Library en VBA, todas las demás macros relacionadas con SAP no funcionan en la línea de código de acceso a la transacción.
¿Alguno sabe a qué puede ser debido?
Este es el código que estoy utilizando:
'Rutina de inicio, llama a SAP
 If Not IsObject(Appli) Then
    Set SapGuiAuto = GetObject("SAPGUI")
    Set Appli = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
    Set Connection = Appli.Children(0)
End If
If Not IsObject(session) Then
    Set session = Connection.Children(0)
End If
'Elegimos la transación esta es la línea donde me da el ERROR
session.findById("wnd[0]/tbar[0]/okcd").Text = "ME5A"

El error que recibo es:

Error '438' en tiempo de ejecución: El objeto no admite esta propiedad o método.

A: Uno de los motivos por los cuales puede estar fallando es que el nombre de las variables podría entrar en conflicto con otras variables de VBA de Outlook.
Mi sugerencia:
 Set SapGuiAuto = GetObject("SAPGUI")
 Set Appli = SapGuiAuto.GetScriptingEngine
 Set SAPConnection = Appli.Children(0)
 Set SAPsession = SAPConnection.Children(0)
 SAPsession.findById("wnd[0]/tbar[0]/okcd").Text = "ME5A"


text:
Q: Trouble opening a file in linux I am trying to print running processes on a linux system, but I am getting a segmentation fault when trying to do so.  Here is my code:
FILE *ps;
char line[256];
char * command = "ps";
ps = fopen(command, "r");
if(ps == NULL){
    perror("Error");
}
while(fgets(line, sizeof(line), ps)){
    printf("%s", line);
}
fclose(ps);

The odd thing is that when I use the same code but replace "ps" with "/proc/meminfo" or other files, it will correctly output.  Thanks in advance for the help.

A: Try to use popen and pclose for running command rather than fopen and fclose
char line[256];
FILE *ps = popen("ps", "r");
if(ps == NULL){
    perror("Error");
}

while(fgets(line, sizeof(line), ps)){
    printf("%s", line);
}

pclose(ps);


text:
Q: alignment of elements in a button I have a bootstrap drop down and on the button, I have a text and an icon. What I want is to align the text all the way to the left and align the icon all the way to the right without having to grid the button with other elements. Thanks in advance.

.dropdown {
  display: flex;
  width: 40%;
  height: 10vh;
  border: none;
}

.dropdown button {
  font-size: 1.8vw;
  color: #ffffff;
  width: 100%;
  height: 100%;
  border: none;
}

.dropdown button i {
  font-size: 1.8vw;
  margin: auto;
}

.dropdown button::after {
  display: none;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v6.0.0/css/all.css" integrity="sha384-3B6NwesSXE7YJlcLI9RpRqGf2p/EgVH8BgoKTaUrmKNDkHPStTQ3EyoYjCGXaOTS" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
        drop me

    </button>

Action

Another action

Something else here

A: Most of your CSS are not needed, you can use some of bootstrap's utility classes to achieve the expected result.

*

*You don't have to use .dropdown button::after{} to remove bootstrap's default dropdown caret. Just remove .dropdown-toggle from the button.

*You can then use this d-flex justify-content-between align-items-center class to align the text and the icon.

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v6.0.0/css/all.css" integrity="sha384-3B6NwesSXE7YJlcLI9RpRqGf2p/EgVH8BgoKTaUrmKNDkHPStTQ3EyoYjCGXaOTS" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <button class="btn btn-secondary w-100 d-flex justify-content-between align-items-center" type="button" data-bs-toggle="dropdown">
        drop me

    </button>

Action

Another action

Something else here


text:
Q: TINKER Molecular Modeling Troubleshooting I am a student doing undergraduate research. I am using TINKER for modeling (Link: https://dasher.wustl.edu/tinker/). I am new to Linux and to this program and was wondering if anyone here could help me troubleshoot or help me find a place that will help me troubleshoot.
I currently have the program installed and can open it up using the path command in the Linux terminal (I have set this up this way). It asks me for my coordinates file and I enter the name of the file I want to test. This then prompts me with the same question. I keep entering the file name and get the same results, the program asking me to enter the coordinate files. Even someone who just knows about Linux programs. Could this be an issue with how I set it up? Thanks guys for the help in advance.

A: Not knowing how to use the program will make it very difficult!
I downloaded TINKER and the example files, and if I use a totally bogus filename, TINKER just prompts for another filename. Not having error messages makes the program a little unfriendly to beginners.
If I specify a filename by path, eg. ~/tinker/fulldist/tinker/example/hexanes.xyz I get a little blurb about hexanes, then prompted for another filename.  So, I don't think you have a setup issue, but you should probably find a fellow student who uses the program and ask for a short tutorial.


text:
Q: javascript / canvas5 error from simple code Error: uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMCanvasRenderingContext2D.drawImage]"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: http://127.0.11.1/test/canvas5_b.php :: setup :: line 27"  data: no]
function setup() {

    var e = document.getElementById("mycanvas");
    var ctx = e.getContext('2d');

    var meter = new Image();
    meter.src = "meter.jpg";
    var meter_bar = new Image();
    meter_bar.src = "meter_bar.jpg";
    //alert(meter);

    ctx.beginPath();/////////LINE 27////////////
    ctx.drawImage(meter, 50, 100);
    //ctx.globalCompositeOperation = "lighter";
    ctx.drawImage(meter_bar, 68, 123);
    ctx.closePath();

}

window.onload = setup;

Both the images are in the right folder. The thing that gets me is that it works if you put a alert(meter); before line 27. Its as if it is not loaded, but I have it running on window.onload, so I dont see how that is.
edit : It is an issue of when the image is loaded (ty rob). It appears best to globally declare and set the image src, and then call window.onload = setup, like this : (correct me if this is bad)
var img1, img2;
img1 = new Image();
img2 = new Image();
//declare and set the images src
img1.src = "meter.jpg";
img2.src = "meter_bar.jpg";

var canvasHeight, canvasWidth;
canvasHeight = 300;
canvasWidth= 600;

var ctx;

function setup() {
    var e = document.getElementById("mycanvas");
    ctx = e.getContext('2d');
    draw();
}

function draw() {
    ctx.clearRect(0,0,canvasWidth, canvasHeight);
    ctx.beginPath();
    ctx.drawImage(img1, 50, 100);
    ctx.drawImage(img2, 68, 123);
    ctx.closePath();
}

window.onload = setup;

A: Make sure the images are loaded first.  For instance:
 var img = new Image();
 img.onload = function(){
    ctx.drawImage(img,0,0);
    }

 // put this after onload, otherwise onload may
 // not be called if image is in cache
 img.src = 'whatev.png';

A: It's likely that the delay introduced by alert is enough to allow the image to load, but without alert, the images have not loaded in time. Try drawing the images onto the canvas only once they have loaded:
function setup() {

    function maybeDraw() {
        this.loaded = true;
        if(meter.loaded && meter_bar.loaded) {
            ctx.beginPath();
            ctx.drawImage(meter, 50, 100);
            //ctx.globalCompositeOperation = "lighter";
            ctx.drawImage(meter_bar, 68, 123);
            ctx.closePath();
        }
    }

    var e = document.getElementById("mycanvas");
    var ctx = e.getContext('2d');

    var meter = new Image();
    var meter_bar = new Image();
    meter.onload = maybeDraw;
    meter_bar.onload = maybeDraw;
    meter.src = "meter.jpg";
    meter_bar.src = "meter_bar.jpg";

}

window.onload = setup;


text:
Q: ruby system command failed inside of my code, but works outside of my code independently The following is my code of system command call. It works well if I execute it independently outside of my codes, but it does not work if I put it inside of codes. Is there some thing wrong with my code?
dakota_file=Plugin.dir + "Dakota_EnergyPlus_cygwin.in"
begin
run_dakota_thread = Thread.new { system("Dakota","#{dakota_file}") }
rescue =>e
UI.messagebox("Thread raised #{e.class}: #{e.message}")
end

dakota_file is the path of input file and Dakota is the program I'd like to call.


text:
Q: Making a BrainF*ck Interpreter, trouble with Loops Here is my code http://pastebin.com/itL26LW6 http://pastebin.com/index/fvx3Tc65
In particular this is the part that is supposed to control the [ and ]
 case Token.LEFT:
                    if (tape[datapointer] == 0 ){
                            int i =1;
                            while (i > 0) {
                                    char c2 = (char) c[++charpointer];
                                    if (c2 == Token.LEFT)
                                            i++;
                                    else if (c2 == Token.RIGHT)
                                            i--;
                            }
                    }
                    break;
            case Token.RIGHT:
                    int i = 1;
                    while ( i > 0 ) {
                            char c2 = (char) c[--charpointer];
                            if (c2 == Token.LEFT)
                                    i--;
                            else if (c2 == Token.RIGHT)
                                    i++;
                    }
                    charpointer--;
                    break;

            }

}
The program is supposed to read in a brainf*ck program in a file called file.txt. The problem is, I tested with hello world and my program doesn't do anything. I can't figure out the problem with the above code algorithm.

A: One problem is that after a [ token your charpointer is not incremented.
This means that if the value under the current datapointer is non-zero, your program gets stuck on the [ symbol because ++charpointer isn't executed even once.
And if datapointer is pointing to a zero, it jumps onto the corresponding ], causing an infinite loop.
Also, after a ] token the charpointer should not be decremented, otherwise your program jumps onto the token before the ], which is wrong.
Here's the corrected code:
case Token.LEFT:
  if (tape[datapointer] == 0) {
    int i = 1;
    while (i > 0) {
      char c2 = (char) c[++charpointer];
      if (c2 == Token.LEFT)
        i++;
      else if (c2 == Token.RIGHT)
        i--;
    }
  }
  charpointer ++;
  break;
case Token.RIGHT:
  int i = 1;
  while ( i > 0 ) {
    char c2 = (char) c[--charpointer];
    if (c2 == Token.LEFT)
      i--;
    else if (c2 == Token.RIGHT)
      i++;
  }
  break;


text:
Q: Disable System Beeps over SSH I have disabled system beeps locally by adding set bell-style none to my local .inputrc file; however, when remote ssh to machines I will still get system beeps for using TAB for autocomplete, which I do a lot. I know I can modify the remote machine's .inputrc file or the remote accounts .bashrc file, but that is intrusive on machines I do not own. Is there a way to fix this locally.
I am using Windows 10 Ubuntu Bash.
The beeps are slowing driving me insane.

A: You can set readline variables at any time using the bind command, without needing to read an .inputrc file. For example, after you login type
bind 'set bell-style none'

Note how the command has to be a single string.  If you want to do this automatically each time you could use a simple expect script taking the remote hostname as argument.
#!/usr/bin/expect -f
spawn ssh [lindex $argv 0]
expect {$ }
send "bind 'set bell-style none'\n"
expect {$ }
interact

A: Here's a workaround, first, create a file .inputrc.mine in the home directory of your remote user with line
set bell-style none

then log in to the server using
ssh -t user@server 'export INPUTRC=~/.inputrc.mine; /bin/bash'

Without -t your bash would not work (input/output redirected to the previous command).


text:
Q: Port mapping is not working for docker on mac I am trying to run docker container for spring boot application however I am not able to access the application.
I am using docker on mac with the following version
Mac OS Mojave version
10.14.3 (18D109)

Docker version on mac:
anhs-MBP:spring-boot-with-fargate anhtrang$ docker --version
Docker version 18.09.2, build 6247962

I have checked the container logs and spring boot application started normally
Container logs:
019-08-12 01:08:42.885  INFO 6 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2019-08-12 01:08:43.026  INFO 6 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2019-08-12 01:08:43.045  INFO 6 --- [           main] c.e.s.SpringBootWithFargateApplication   : Started SpringBootWithFargateApplication in 8.06 seconds (JVM running for 9.107)

Command to start docker container:
anhs-MBP:spring-boot-with-fargate anhtrang$ docker run -d -p 8080:8080 anhtrang/spring-boot-with-farget:0.0.1-SNAPSHOT

I also tried starting the spring boot application outside of container it's working perfectly. I just don't understand why its not able to expose the port
My GitHub repo:
https://github.com/anhtv08/spring-boot-with-fargate
Appreciate for any quick help


text:
Q: Apply a border to background image I have some divs, and they have their backgrounds set as images using this:
background:url(myimage.jpg);

Now what I'm looking to do is set a border on that image that is set to the background.
I don't want to set a border on the div as this does not give the desired result, it must be a border on the image.
Not sure if this is possible, is it?

A: You could try using multiple backgrounds, by setting your base bg image and a second one as a border.
#container {
background-image: url(Main-bg), url(Border-img.png);
background-position: center center, left bottom; /* border bottom in this case */
background-repeat: no-repeat;
}

A: It is not possible to do it precisely as you've mentioned.  Since the background image is styling, rather than content, no additional styling can be added to it.
The best option would be to create a different image file to serve the bolder border.


text:
Q: Elementary "binomial theorem" in English In German schools, the identitiy $(a+b)^2 = a^2 + 2ab + b^2$ is called the first binomial formula (literally translated). However, it seems to me this English term only refers to the more general binomial theorem which involves the former as a special case, but is much more powerful and complex, or to formulas involving the binomial.
Is there special terminology taught in schools for this kind of formula? What would be the best way to describe the process of creating a square (similar to completing the square) as in $x^2 + 2x + 1 = (x+1)^2$?

A: I might say of the folowing

*

*the simplest case of the binomial theorem.

*binomial theorem where the exponent is 2.

*binomial theorem where n = 2

A: You want to start with $4x^2+4x+1$ and come up with $(2x+1)^2$ ... for that I might say $4x^2+4x+1$ is a perfect square.

A: In my experience the usual school terminology treats it simply as a special case of factor(is)ing, alongside the distributive law, $a^2-b^2=(a+b)(a-b)$ and sometimes
$$a^3\pm b^3=(a\pm b)(a^2\mp ab+b^2)\;.$$
I've seen it called square of a binomial, but this name doesn't seem to be as widespread as difference of (two) squares or even difference/sum of (two) cubes.


text:
Q: spring data jpa repository: update only certain columns or all non null columns So I have an entity:
public class Test extends BaseEntity {
    private String title;
    private Double passMark;

    @Convert(converter = DurationToStringConverter.class)
    private Duration duration;

    @ManyToOne
    private User createdBy;

    @ManyToOne
    private User updatedBy;

    @ManyToMany(fetch = FetchType.LAZY)
    private List<Question> questions;
    ...
}

And I have a small form which allows to modify title, passmark and duration.
When this form is submitted I want to only update these fields.
Is there a way to do it without @Query annotation, i.e. only using Spring Data Repository's magic interface methods?


text:
Q: Tracking down Twitter retweets... a fuzzy approach i know that tracking retweets in this fashion:
Source -> User1 -> User2
is not possible as Twitter only gives you the original tweet and not any retweet of a retweet. Based on this.. do you think it might be possible to track down retweets based on followers of the originator of the tweet? For example, what I want to do is to get a retweet, find all users that have retweeted it and then find how those users are related to the person that had originally tweeted it. If B is not a follower of the originator but have retweeted a tweet… could it be that a person B that he follows is a follower of the originator of the tweet and B retweeted it so A eventually saw it?
Thanks in advance for any feedback.

A: I am currently looking at how a user interacts with their timeline, and this is a problem I have considered as well. The problem is that retweets are not always a result of a tweet appearing on a user's timeline. The user could frequently retweet tweets found in the public stream, trending topics, or the "explore" tab.
I think it is possible that your approach could work, but you would need to apply some filters to the kinds of users you look at. You would have to limit the amount of followers you look at, as many retweets come from very popular users. Crawling 10,000 users simply to track one retweet isn't really an option considering the limits of the API.
A more viable option may be to track a retweet from some user that retweeted it. For example, say you have User A, who retweeted a tweet that originated from User B. You can look at all of the users that User A follows, find any candidates that have retweeted User B's tweet (including User B itself), and then search the users they follow, etc, until you reach User B. It would resemble a depth-first-search (or breadth-first, depending on the implementation details). However, you could run into a problem if any retweeting user along the search is private. In this case, you will not see their information and the path of retweets is broken.
I know this isn't a black-and-white answer, but hopefully this helps a little. It's an interesting question.