text:
Q: GetLength() method does not work as expected on an array Here is a C# code.
It outputs the following text :
tab.Length = 6
tab.Rank = 2
Length of dim 0 of tab : 0
Length of dim 1 of tab : 1

I expected the following text :
tab.Length = 6
tab.Rank = 2
Length of dim 0 of tab : 2
Length of dim 1 of tab : 3

Why not? Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TableTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] tab = new int[2, 3];

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    tab[i, j] = 2 * i + j;
                }
            }
            Console.WriteLine("tab.Length = {0}", tab.Length);
            Console.WriteLine("tab.Rank = {0}", tab.Rank);
            for (int i = 0; i < tab.Rank; i++)
            {
                Console.WriteLine("Length of dim {0} of tab : {0} ", i, tab.GetLength(i));
            }

        }
    }
}

A: Wild guess: your last format string is wrong:
Console.WriteLine("Length of dim {0} of tab: {0} ", i, tab.GetLength(i));

You're using {0} twice, so you're outputting the value of i in both placeholders.
Use this instead:
Console.WriteLine("Length of dim {0} of tab: {1} ", i, tab.GetLength(i));

A: Your format string is wrong.
Replace "Length of dim {0} of tab : {0} " by "Length of dim {0} of tab : {1} ".
Your code was actually putting i, and not tab.GetLenght(i)

A: Do you simply need to access the second parameter passed to the Console.WriteLine? Try this:
Console.WriteLine("Length of dim {0} of tab : {1} ", i, tab.GetLength(i));


text:
Q: Third syntax version of LogitModelFit: unexpected result of "BestFit" The third listed syntax version of LogitModelFit allows one to specify input in a simple way: Only a design matrix (with a row of values of the explanatory input variables for each of the output values) and a response vector are needed. The following example is straight from the LogitModelFit help page:
dm = {{1, 1}, {1, 2}, {1, 3}, {1, 4}};
resp = {0, 1, 0, 1};
model = LogitModelFit[{dm, resp}]

As usual in these types of fits, Mathematica returns an object that can be interrogated with various methods. In this case, I just want to have the best fit:
model["BestFit"]

I noted something here that I feel is strange. Although this looks like a pure function (which is what I expected, given no formal variable names are specified in this syntax), it really isn't, since the required & at the end is missing. Hence, a construction like model["BestFit"][1,2] doesn't work.
Is this a bug, or is this useful in some way and am I missing something?
I note that neither the "Function" method of LogitModelFit nor something like model//Normal yields anything useful. The former generates an error which suggests to me that there is indeed a bug in this syntax variant. The latter returns the same as "BestFit".
My workaround for now is to use:
mod = model["BestFit"] // Evaluate // Function;

(Evaluate because of the HoldAll attribute of function)
mod[1, 2]

0.3883882668

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS passing to directive heavy JSON file Well, i think i located the problem of chart not showing up, and the problem is probably that i'm loading heavy JSON object from RESTful server and passing it to directive where i'm generating chart but json is not still not downloaded completly.
JSON file is almost 1mb, which i'm getting in this way:
In Controller:
dataArchive.get().then(function(result){
    $scope.getData = result;
});

And HTML:
<divng-controller="archiveCtrl">
    <data-graph get-archive-data="getData"></data-graph>

And in directive:
var chart = function(data){
     var createchart = new AmCharts.makeChart("chartdiv", {
          //
     });
}

var linker = function(scope, element, attrs){
    scope.$watch('data', function(){
        chart(scope.data);
    });
}

directives.directive('dataGraph', function(){
    return {
        restrict: 'E',
        replace: false,
        scope: {
            data: '=getArchiveData'
        },
        template: '

',
        link: linker
    };
});

Probably because of this, directive template will be created empty, and chart will not be generated.
How can i workaround this problem?

A: You are correctly using $watch which should re-trigger the charting function, but I suggest you try a few other approaches to see which helps.
Firstly, the watch function will trigger on initial directive linking even if data is not there yet -- it will just return undefined, so the first time it will call the chart function with undefined, therefore, I imagine, rendering an empty chart. Then, when the data is downloaded, it will trigger $watch again, but perhaps your charting function will not work if called multiple times..? How about the following check:
scope.$watch('data', function(){
  if (!scope.data) return
  chart(scope.data);
});

Another approach which works for me when I need to wait for the resolution of some variable is using $observe, and not adding the variable into the scope of the directive:
<data-graph get-archive-data="{{ getData }}"></data-graph>

var linker = function(scope, element, attrs){
  attrs.$observe('getArchiveData', function(data){
    if (!data) return;
    chart(data);
  });
}

directives.directive('dataGraph', function(){
  return {
    restrict: 'E',
    replace: false,
    // Remove below
    //scope: {
    //    data: '=getArchiveData'
    //},
    template: '

',
    link: linker
  };
});


text:
Q: Optimal way to move in a grid to find a random walker Consider an $n$ times $n$ grid. Assume there are two agents $A$ and $B$.
At time $t_0$, agent $A$ is at square  $(n,n)$ and $B$ is at random square. At time $t+1$, agent $B$ has moved one square from his current position to an adjacent square, one left, right, above or below, provided he isn't at the edge. At the same time, $A$ can also move one square in similar fashion or stay put.
Assume that $A$ tries to find $B$, ie. be at time $t$ at the same square $B$ is.
What is the optimal way for $A$ to move?
To me, two strategies strategies come to mind. One is for $A$ to stay in the same square all the time, for the random walked will certainly intercept him at some point. Other would be for $A$ to go on a random walk too. (If this would be human "game", psychologically the second sounds more appealing)


text:
Q: Selenium Testing For Element Existence Failure Back again with another Selenium question!...
Here is what I have so far
public static void mobileAssessmentPage() {
    List<WebElement> elements = SeleniumCommands.findElementsByCss(ASSESSMENTANSWER);
    List<WebElement> pageTitle;

    for (WebElement element : elements) element.click();

    SeleniumCommands.waitClickById(ASSESSMENTNEXTPAGEBUTTON);
    try { Thread.sleep(500); } catch (InterruptedException ie) { ie.getMessage(); }
    pageTitle = SeleniumCommands.findElementsByXpath(PAGETITLE);
    try { Thread.sleep(500); } catch (InterruptedException ie) { ie.getMessage(); }
    System.out.println(pageTitle.get(0));
    if (pageTitle.size() > 0) {
        if (pageTitle.get(0).getText().equals("Assessment"))
            mobileAssessmentPage();
    }
}

For some reason, on the page where I know it should return an empty list (since the page title should not be found), the two exceptions I keep getting are "StaleElementReferenceException" (or something like that) or "Element is no longer attached to the DOM".  Is there a better way to go about this?
I am trying to make the method dynamic by calling itself for every page where it is needed; unfortunately, the Selenium methods don't make this convenient since they return an error if they can't find an element instead of a Boolean or -1 or even a null WebElement or something logical.

A: From the selenium docs:

A stale element reference exception is thrown in one of two cases, the
  first being more common than the second:
The element has been deleted entirely. The element is no longer
  attached to the DOM.

The latter include cases where an element is deleted and replaced by a new one with almost the same attributes and DOM location. Any JS library might be doing that in reaction to clicking one of the elements, so the rest of the elements get "stale".
How can you avoid this?
One solution that I used is to not keep a reference to each of the elements but find each of the single elements just before clicking it. As the elements share a selector, you can first get the count and then get them by subindex. Adapting your example:
public static void mobileAssessmentPage() {
    int q = SeleniumCommands.findElementsByCss(ASSESSMENTANSWER).count();

    List<WebElement> pageTitle;

    for (int i = 0; i < q; i++) {
        WebElement element = SeleniumCommands.findElementsByCss(ASSESSMENTANSWER)[i];
        element.click();
    }

    SeleniumCommands.waitClickById(ASSESSMENTNEXTPAGEBUTTON);
    try { Thread.sleep(500); } catch (InterruptedException ie) { ie.getMessage(); }
    pageTitle = SeleniumCommands.findElementsByXpath(PAGETITLE);
    try { Thread.sleep(500); } catch (InterruptedException ie) { ie.getMessage(); }
    System.out.println(pageTitle.get(0));
    if (pageTitle.size() > 0)
        if (pageTitle.get(0).getText().equals("Assessment"))
            mobileAssessmentPage();
}

If that's not enough (and many times it's not), you might want to use some waiting or retry in that for, something like:
    for (int i = 0; i < q; i++) {
        WebElement element = SeleniumCommands.findElementsByCss(ASSESSMENTANSWER)[i];
        element.click();
        Thread.sleep(200);
    }

or:
    for (int i = 0; i < q; i++) {
        try {
            WebElement element = SeleniumCommands.findElementsByCss(ASSESSMENTANSWER)[i];
            element.click();
        } catch (StaleElementReferenceException e) {
            Thread.sleep(200); // optional, but just to be safe...
            WebElement element = SeleniumCommands.findElementsByCss(ASSESSMENTANSWER)[i];
            element.click();
        }
    }

A: First of all you should not use Thread sleep! This bad practice for production tests. You should also use page-object pattern (it's very useful).
About your actual question: Elements need some time for attaching to parent elements.  For example: when a developer used animation, or an application generates difficult user interfaces, then this process need some time for rendering.  Otherwise the element will be attached whenever the application  completes some task(s). You just need to wait when element will be attached. Webdriver has special classes and methods for this cases:
 WebElement webElement = new WebDriverWait(driver(), 3).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("some css celector"))); //this code wait untill element will be attached about 3 seconds
webElement.click() //now you clicking on element

You can use many useful methods in the ExpectedConditions class.  Remember, you should use Thread.sleep() very seldom, and only if you don't have another option. Good luck.


text:
Q: TableView DidSelectRowAt() latency Hello I actually use a tableview in my app. I have this lines of code which switch from a VC to a mother and it work fine everywhere :
 let vue = MAINSTORYBOARD.instantiateViewController(withIdentifier: "accueil") as! Accueil
self.present(vue, animated: true, completion: nil)

In my tableView I use the function DidSelectRowAt ( this execute when I click on a row/cell) to do this (switch of VC)
But you've already understood when I click it work but with latency.
This latency can is sometimes 1-2s sometimes up to 12s it's random. That's weird.
I specify the function above work instantly with buttons and others.
 this is the code (I write only important things) :
class Horaire: ViewController, UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vue = MAINSTORYBOARD.instantiateViewController(withIdentifier: "accueil") as! Accueil
        self.present(vue, animated: true, completion: nil)

}

and the other class :
class Accueil: ViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("viewDidLoad executed")
    }
}

So when I click on a cell of my tableview it immediately print "viewDidLoad executed" but VC switch is done only after some random seconds.
Why does I have this latency and how to fix it ? it don't use segue

A: The first thing that came to my mind was to put the block in the main queue. I know didSelectRowAt is supposed to run in the UI thread, but I saw on the internet a couple complaints about this very same thing. Looks like a bug to me.
class Horaire: ViewController, UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        DispatchQueue.main.async{
        let vue = MAINSTORYBOARD.instantiateViewController(withIdentifier: "accueil") as! Accueil
        self.present(vue, animated: true, completion: nil)
        }
    }
}

You can see for some odd reason this seemed to work for these people:
https://github.com/HeroTransitions/Hero/issues/79


text:
Q: ConcurrentModificationException when trying delete some items from list in android I have method for filter brands:
class GetBrandsUseCase @Inject constructor(private val getProductsRepository: ProductsRepository,
                                           private val getMenuBrandsUseCase: GetMenuBrandsUseCase) : SingleNoParamUseCase<List<String>> {
    override fun run(): Single<List<String>> {
        val listOfBrand = mutableListOf<String>()
        return getProductsRepository.getProductsFromMemory()
                .doOnError {  }
                .map {
                    it.map { productModel ->
                        if (!listOfBrand.contains(productModel.attributes.brand) && productModel.attributes.brand.isNotBlank())
                            listOfBrand.add(productModel.attributes.brand)
                    }
                    listOfBrand
                }.flatMap {
                    getMenuBrandsUseCase.run()
                }.map { list ->
                    if (list.isNotEmpty())
                        listOfBrand.removeIf {
                            !list.contains(it)
                        }
                    listOfBrand
                }
    }
}

this method works, but sometimes I get error:
FATAL EXCEPTION: RxCachedThreadScheduler-4
Process: de.greeneye.eva.debug, PID: 7379
io.reactivex.exceptions.OnErrorNotImplementedException: The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | java.util.ConcurrentModificationException
    at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
    at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
    at io.reactivex.internal.observers.ConsumerSingleObserver.onError(ConsumerSingleObserver.java:46)
    at io.reactivex.internal.operators.single.SingleSubscribeOn$SubscribeOnObserver.onError(SingleSubscribeOn.java:73)
    at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onError(SingleMap.java:69)
    at io.reactivex.internal.operators.single.SingleFlatMap$SingleFlatMapCallback.onError(SingleFlatMap.java:90)
    at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onError(SingleMap.java:69)
    at io.reactivex.internal.operators.single.SingleMap$MapSingleObserver.onSuccess(SingleMap.java:60)
    at io.reactivex.internal.operators.single.SingleDoOnError$DoOnError.onSuccess(SingleDoOnError.java:52)
    at io.reactivex.internal.operators.single.SingleJust.subscribeActual(SingleJust.java:30)
    at io.reactivex.Single.subscribe(Single.java:3495)
    at io.reactivex.internal.operators.single.SingleDoOnError.subscribeActual(SingleDoOnError.java:35)
    at io.reactivex.Single.subscribe(Single.java:3495)
    at io.reactivex.internal.operators.single.SingleMap.subscribeActual(SingleMap.java:34)
    at io.reactivex.Single.subscribe(Single.java:3495)
    at io.reactivex.internal.operators.single.SingleFlatMap.subscribeActual(SingleFlatMap.java:36)
    at io.reactivex.Single.subscribe(Single.java:3495)
    at io.reactivex.internal.operators.single.SingleMap.subscribeActual(SingleMap.java:34)
    at io.reactivex.Single.subscribe(Single.java:3495)
    at io.reactivex.internal.operators.single.SingleSubscribeOn$SubscribeOnObserver.run(SingleSubscribeOn.java:89)
    at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:578)
    at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
    at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:762)
 Caused by: java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at de.greeneye.domain.filters.GetBrandsUseCase$run$2.apply(GetBrandsUseCase.kt:33)
    at de.greeneye.domain.filters.GetBrandsUseCase$run$2.apply(GetBrandsUseCase.kt:9)

any ideas how fix this?


text:
Q: Could someone help me with Regex? I need to check if all the "B" to the right and the "A" to the left. No matter the position of the "#", as long as all "B" are all on one side and "A" on the other. For example:
-Correct-
BBAA#
BBA#A
BBBB#AAAA
B#BBAAA
#BBAA

-Incorrect-
AAA#BBB
AAB#ABB
B#AAB
BAA#B
#ABAB
BABA#
ABBB#AA

Someone could help me .... I already tried but I could not
thanks
code:
    #include <iostream>
#include<regex>
using namespace std;

auto check = [](string &rp)->bool {
    regex reg("^(B)*(A)*");
    return regex_match(rp, reg);
};

int main()
{
    string rp;
    do{
       system("cls");
       cout<<"RP: ";
       getline(cin, rp);

    }while (!check(rp));

    cout<<"\n valid"<< rp<<endl;

    return 0;
}

A: Regex won't move the text for you it will just tell you if the pattern is correct or not. You're going to need another tool alongside regex.
Edit: this regex should work for you. It matches 0 or more #s followed by zero or more Bs 0 or more times followed by 0 or more #s followed by 0 or more As zero or more times. ^ and $ denote the beginning and end of the string.
^(#*B*)*(#*A*)*$


text:
Q: requirejs - d3.sankey is not a function I'm trying to create a basic sankey diagram using d3 libraries loaded from requirejs. In the past I've used the core d3 library and rendered everything fine, however in trying to load d3-sankey in this instance it doesn't seem to be registering. I've also tinkered around with the shim but I can't seem to figure out where the issue is specifically. Every time I try to load the attached code I get the error 'Uncaught TypeError: d3.sankey is not a function'.
I'm assuming the issue is the sequencing of libraries being loaded, but again I'm not sure how to resolve this. Can anyone help?
Codepen - https://codepen.io/quirkules/pen/wYoXxQ
// define URLs
require.config({
  paths: {
    cloudflare: 'https://cdnjs.cloudflare.com/ajax/libs'
  },
  map: {
    '*': {
      'd3': 'cloudflare/d3/4.8.0/d3',
      'd3-timer': 'cloudflare/d3-timer/1.0.5/d3-timer',
      'd3-array': 'cloudflare/d3-array/1.2.2/d3-array',
      'd3-collection': 'cloudflare/d3-collection/1.0.5/d3-collection',
      'd3-interpolate': 'cloudflare/d3-interpolate/1.3.0/d3-interpolate',
      'd3-color': 'cloudflare/d3-color/1.2.1/d3-color',
      'd3-shape': 'cloudflare/d3-shape/1.2.0/d3-shape',
      'd3-path': 'cloudflare/d3-path/1.0.5/d3-path',
      'd3-sankey': 'cloudflare/d3-sankey/0.7.1/d3-sankey'
    }
  },
  shim : {
    d3 : {
      exports : 'd3'
    },
    'd3-sankey' : {
      deps: ['d3']
    }
  }
});

// load d3
require(['d3', 'd3-timer', 'd3-array', 'd3-collection', 'd3-interpolate', 'd3-color', 'd3-shape', 'd3-sankey'], function(d3) {
  //****** CREATE DIVS ******//

  // Add the divs to the DOM
  $(document.body)
    .append('

')
    .append('

')
    .append('

');
  //add text to the divs
  document.getElementById("header").innerHTML = 'Title';

  // set the dimensions and margins of the graph
  var margin = { top: 20, right: 20, bottom: 40, left: 50 },
    width = d3.select('#chart').node().getBoundingClientRect().width - margin.left - margin.right,
    height = d3.select('#chart').node().getBoundingClientRect().height - margin.top - margin.bottom;

  //
  var svg = d3.select("#chart")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);
  var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var graph = d3.sankey()
    .nodeWidth(15)
    .nodePadding(10)
    .size([width, height]);

  var path = graph.link();

  var freqCounter = 1;

  //****** END CREATE CHART ******//
});

A: Why use require?
If I load the following 2 scripts it fails at the line var path = graph.link();, so d3.sankey is known and a function.
Undo all use of require and add

d3.js already contains most of the other modules, it does not contain d3-sankey. For some reason d3.js does not register the individual modules it contains with require(), that's why require tries to load the modules d3-array, d3-collection, d3-shape, d3-path
Maybe you have a version problem, how do you know which version of the individual modules belong to d3.v4.8.0.
Edit
If I load d3-sankey after the other modules, the error disappears but if it works later on I don't know. (There are no links because there is no data processed by sankey.
require(['d3-selection', 'd3-timer', 'd3-array', 'd3-collection', 'd3-interpolate', 'd3-color', 'd3-shape'], function(d3) {
require(['d3-sankey'], function(dsankey) {
  //****** CREATE DIVS ******//
  // .....
  var graph = dsankey.sankey()
    .nodeWidth(15)
    .nodePadding(10)
    .size([width, height]);
  //****** END CREATE CHART ******//
});
});


text:
Q: Leaflet.js: Linking Activities to Map Markers I am using Leaflet.js to display markers on the map using latlng coordinates pulled in from the database using php.
I have a list of activities on the left sidebar to which I would like to link these with the map markers together.
I am having difficulty with this:
If you were to hover/click on an activity on the sidebar, the correct marker would then do something, such as the popup or a nice animation.
http://meteaydin.co.uk/tourism/itinerary.php
Here is a link where you can see what I have.
If you could lend me a hand to possibly achieving this, I would greatly appreciate it.
Thanks

A: You can leave references to your markers in your links and visa versa. Check the following example:
Create a marker and a link:
var marker = new L.Marker([0, 0]).bindPopup('My popup').addTo(map);
    link = L.DomUtil.create('a', 'my-link', document.body);

link.href = '#';
link.textContent = 'My link';

Create references to each other:
link.marker = marker;
marker.link = link;

Then add events to your link and use the marker reference in the handlers:
L.DomEvent.addListener(link, 'mouseover', function () {
    this.marker.openPopup();
});

L.DomEvent.addListener(link, 'mouseout', function () {
    this.marker.closePopup();
});

And it also works the otherway around, attach handlers to the marker and use the referenced link to do something:
marker.on('mouseover', function () {
    L.DomUtil.addClass(this.link, 'hover');
});

marker.on('mouseout', function () {
    L.DomUtil.removeClass(this.link, 'hover');
});

Here's an example: http://plnkr.co/edit/gInjWxd84RhPsbIIW4ct?p=preview


text:
Q: Whats the best way to Programmatically Process New Email Messages and Store Attachments I have several clients/vendors that distribute reports to me via email. Some of these files are enormous, and need to be removed from email and saved on a file share for processing, as well as to control mailbox size.
Can anyone provide guidance on their recommended method of automatically downloading and saving attachments.
I am in a MS Windows Environment (Client & Server Computers). Emails are on an Microsoft Exchange 2003 Email Server.
Preferred use of Microsoft Technology for consistency across solutions (C#), however I am open to any suggestions, be it C#, VBScript, Perl, Java, Components I should purchase, etc..
Scenario
Each Day bob@whysendmereportsbyemail.com sends an email with the subject "Activity Report for YYYY-MM-DD" to me at
john@myemailaddress.com
Each Email has an attachment named "ActivityReport-YYYY-MM-DD-HH-MI-SS.xls" which I need to save on my filesystem at
"C:\FilesFromBob\ActivityReport-YYYY-MM-DD-HH-MI-SS.xls"
Thanks in advance for any assistance.

A: Exchange 2003 provides a WebDav API which you can use to access emails, contacts etc.. from a user's account.
There's a few answers about accessing a user's Exchange inbox on SO already.  I've previously used this approach for almost exactly the situation you outline, and once you work out the WebDav API model and the structure of the requests and responses, it's not too difficult to extract emails and their attachments.
There are other ways to interact with Exchange 2003 (outlined on SO here), but I've only tried the WebDav approach because it seemed the most reliable.

A: I finally wrote the code to store messages from Outlook
Unfortunately this code runs from within Outlook, so Outlook has to be open.
I did not yet investigate how to schedule the run, but now its easy to do
Sub SaveOutlookFileAttachments()

Dim oStores As Outlook.Stores
Dim oStore As Outlook.Store
Dim oFolders As Outlook.Folders
Dim oFolder As Outlook.Folder
Dim destFolder As String
Dim oItems As Outlook.Items
Dim oMsg As Outlook.MailItem
Dim oAttachments As Outlook.Attachments
Dim oAttachment As Outlook.Attachment
Dim oExplorer As Outlook.Explorer

destFolder = "\\NetworkShare\OrderDetailReport\"

On Error Resume Next
Set oStores = Application.Session.Stores

For Each oStore In oStores
    If oStore.DisplayName = "Inbox" Then
        oFolders = oStore.GetSearchFolders
        For Each oFolder In oFolders
        oItems = oFolder.Items
            For Each oMsg In oItems
                oAttachments = oMsg.Attachments
                For Each oAttachment In oAttachments
                    If InStr(1, oAttachment.FileName, "orderdetail_", vbTextCompare) Then
                        'MsgBox ("This File Needs to be Saved: " & oAttachment.FileName)
                        oAttachment.SaveAsFile (destFolder & oAtch.DisplayName)
                    End If
                Next
            Next

        Next

    End If

Next

End Sub


text:
Q: Return just the number of item in cart Woocommerce I'm working on a Woocommerce theme and I need to grab just the number of items in my cart without any totals or other markup. I've tried using
  <?php echo WC()->cart->get_cart_contents_count(); ?>

But it returns two spans span.amount and span.count and inside span.count it has the string "items" as well
Is there a way to return just the number of items in my cart, preferably as an int?

UPDATE:
So when using the following code:
 <a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>">
    <?php echo WC()->cart->get_cart_contents_count(); ?>

The extra markup above was returned but, by commenting out the anchor tags like so:

    <?php echo WC()->cart->get_cart_contents_count(); ?>

Only an int was returned.
Why is that?


text:
Q: Different behavior when Binding TimePicker and CalendarDatePicker UWP This question is more of a curiosity, as I have already found a workaround, but I would still like to understand the difference. I have a simple ContentDialog derived class which allows to select two dates and times, using CalendarDatePicker and TimePicker respectively. I have bound their Date and Time properties as follows:
        <StackPanel Orientation="Vertical" Grid.Column="0" Grid.Row="0">
            <TextBlock>From</TextBlock>
            <CalendarDatePicker  Date="{x:Bind DateFromDate, Mode=TwoWay}" />
            <TimePicker Time="{x:Bind DateFromTime, Mode=TwoWay}" />
        </StackPanel>

        <StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="0">
            <TextBlock>To</TextBlock>
            <CalendarDatePicker  Date="{x:Bind DateToDate, Mode=TwoWay}" />
            <TimePicker Time="{x:Bind DateToTime, Mode=TwoWay}" />
        </StackPanel>

with the following Code Behind:
    private DateTimeOffset _dateFromDate;
    private TimeSpan _dateFromTime;
    private DateTimeOffset _dateToDate;
    private TimeSpan _dateToTime;

    private DateTimeOffset DateFromDate
    {
        get => _dateFromDate;
        set
        {
            _dateFromDate = value;
            NotifyPropertyChanged();
        }
    }
    private TimeSpan DateFromTime
    {
        get => _dateFromTime;
        set
        {
            if (value != _dateFromTime)
            {
                _dateFromTime = value;
                NotifyPropertyChanged();
            }
        }
    }

    private DateTimeOffset DateToDate
    {
        get => _dateToDate;
        set
        {
            _dateToDate = value;
            NotifyPropertyChanged();
        }
    }
    private TimeSpan DateToTime {
        get => _dateToTime;
        set
        {
            if(value != _dateToTime)
            {
                _dateToTime = value;
                NotifyPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") =>  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

You might notice that in the TimeSpan properties bound to the TimePickers, there is a check whether the property was changed. If I remove this, and leave it as in the DateTimeOffset properties, a StackOverflowException is raised every time I set those properties. If you google for that, you will reach questions such as this, where a quite obvious infinite recursion is occurring. If I debug it, the setter gets indeed called again and again, so my theory is that somewhere in the Code Behind of TimePicker, when it receives the Notification, it not only gets the property, but also sets it. Any ideas?

A:
here a quite obvious infinite recursion is occurring. If I debug it, the setter gets indeed called again and again

I could reproduce this issue, it looks x:Bind TwoWay model make the binding circular, I can sure it is not by design. Currently there are many workarounds for solving this.
Use Binding to replace x:Bind.
public TimeSpan DateToTime
{
    get => _dateToTime;

    set
    {

        _dateToTime = value;
        OnPropertyChanged();

    }
}

<TimePicker Time="{Binding DateToTime, Mode=TwoWay}" />

Modify TwoWay to OneWay.
<TimePicker Time="{x:Bind DateFromTime, Mode=OneWay}" />

And the latest one is your mentioned  that use condition statement to stop this loop.
Please feel free report this with windows feed back hub app. And I will keep going to track this problem.
Update
Please note that the documentation for NotifyPropertyChanged clearly states to only trigger the NotifyPropertyChanged event when the value actually changes.
Note that the behavior is undefined when not following the documentation. Therefore when the documentation isn't followed, you cannot make assumptions that the behavior in the bad scenarios will be consistent since both behaviors are undefined.
Here's the doc on INotifyPropertyChanged.
The issue only reproduces when the property's setter does not guard against triggerting PropertyChanged when the value is equal to previous value. Therefore, regardless of difference in behavior, they're both undefined behavior. If you don't follow the documentation, you should expect things to break in weird ways, again because the behavior is undefined.

why DatePicker could work without value is equal to previous value?

An undefined behavior might happen to line up with expectations in some scenario, but given it's not following documentation, it would be risky since it could change at any point in time with no warning.


text:
Q: Can I update to iTunes 9 with a Jailbroken iPhone? I have an iPhone with 3.0.1 firmware that has been Jailbroken, can I update iTunes to version 9 or will 'badness' happen?

A: I think it'll still be fine. What you won't be able to do is install OS 3.1 and keep your cracked apps.

A: I've upgraded to iTunes 9, and haven't had any problems. When prompted to download and upgrade the iPhone to OS 3.1, don't do so.
(I have an iPhone 3G on OS 3.0, Jailbroken & unlocked)

A: You will probably want to follow the Dev-Team blog: when the jailbreak for 3.1 (or any other version) is available, it's posted there...


text:
Q: Firebase Callable function result always null in client despite successful execution I am trying to execute a Callable function from android.

*

*Functions execution Log in console shows calls are received and    executed without any error.

*Callable task in client receives the result after function execution,    no exception reported.

*However, the received result is null.

Here is the function code-
const Translate = require('@google-cloud/translate');
const projectId = functions.config().firebase;

const translate = new Translate({
  projectId: projectId,
});

exports.translateMessage = functions.https.onCall((data, context) => {

  let text = data.text;
  let targetLanguage = data.target_language;
  let uid = context.auth.uid;

  console.log("incoming text: " + text)
  console.log("incoming uid: " + uid)
  console.log("incoming target: " + targetLanguage)

  //In future, check if uid or custom claim has quota
  if(!uid)
    return text;

  translate
  .translate(text, targetLanguage)
  .then(results => {
    const translation = results[0];

    console.log("translated text: " + translation)
    return Promise.resolve(translation);
    //also tried returning json like: return {translationText: translation};
  })
  .catch(err => {
    console.log(err)
    return Promise.reject(err);
  });
});

Here is the console log-

As you'll see, right before returning the promise with translated text, it was logged to console successfully. I also tested by returning the translated text itself instead of a promise. Still null in client.
And here is the client code-
private Task<String> translateMessage(String text, String targetLanguage) {
    // Create the arguments to the callable function.
    Map<String, Object> data = new HashMap<>();
    data.put("text", text);
    data.put("target_language", targetLanguage);

    FirebaseFunctions mFunctions = FirebaseFunctions.getInstance();

    return mFunctions
            .getHttpsCallable("translateMessage")
            .call(data)
            .continueWith(new Continuation<HttpsCallableResult, String>() {
                @Override
                public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                    String result = (String) task.getResult().getData();
                    Log.d(TAG, "Result in callable callback: " + result);
                    return result;
                }
            });
}

The result in callable callback is always null.
Any idea how to get the actual response?

A: I have figured out a solution, my Javascript naivety is to blame.
Looks like only if I use two return statements, then the actual string is sent back to client. The return keyword in front of the actual promise was missing...
return translate
  .translate(text, targetLanguage)
  .then(results => {
    const translation = results[0];

    console.log("translated text: " + translation)
    return Promise.resolve(translation);
  })
  .catch(err => {
    console.log(err)
    return Promise.reject(err);
  });


text:
Q: Dimension of free submodule of a free module over a PID Let $M$ be a (not necessarily finitely generated) free module over a PID $R$. Let $X$ be its basis and let $Y$ be a proper subset of $X$. Let $N$ be a submodule of $R$ and let $N_Y = \langle Y \rangle\cap N$. If $N_Y$ is free with a basis $B$, can we conclude that $|B| \leq |Y|$?
Grillet (the textbook Abstract Algebra) implicitly uses this result in his proof that every submodule of a free module $M$ over PID is free with the dimension less or equal to that of $M$.

A: Hint: comsider $K$ the field of fraction of $R$. denote $M_K$ the $K$-vector space associated to $M$ (the localization of $M$). $dim_KM_K=dim_RM$, since the result is true for $K$, it is true for $R$.


text:
Q: Google maps application open directly on place details screen I'm creating hybrid mobile application in ionic framework and need to use google maps application to display google place details. I'm wondering wheter is it possible to display place details directly from code (to display directly image2 instead of image1 - image to is displayed when clicked on place name at bottom):
here's a code sample how I am calling google maps app:
url = "geo:?q=" + encodeURIComponent(placeName);
window.open(url, "_system", 'location=no');
//url = geo:?q=Crveni%20pevac

image1:

image2

A: This looks like an implementation of Google Place Details and Google Place Photos which are mentioned in this Google Doc. There's also a sample app on Github to get you started.


text:
Q: In bash how to move row field to column in a text file I have a .txt file with this record:
field_1        value01a value01b value01c
field_2        value02
field_3        value03a value03b value03c

field_1        value11
field_2        value12a value12b
field_3        value13

field_1        value21
field_2        value22
field_3        value23

...

field_1        valuen1
field_2        valuen2
field_3        valuen3

I would like to convert them like that:
field1                      field2            field3
value01a value01b value01c  valu02            value03a value03b value03c
value11                     value12a value12b value13
value21                     value22           value23
...
valuen1                     valuen2           valuen3

I have tried something like:
awk '{for (i = 1; i <NR; i ++) FNR == i {print i, $ (i + 1)}}' filename

or like
awk '
{
   for (i=1; i<=NF; i++)  {
     a[NR,i] = $i
   }
}
NF>p { p = NF }
END {
    for(j=1; j<=p; j++) {
       str=a[1,j]
       for(i=2; i<=NR; i++){
            str=str" "a[i,j]
       }
       print str
    }
 }'

but i can't get it to work
I would like the values to be transposed and that each tuple of values associated with a specific field is aligned with the others
Any suggestions?
Thank you in advance

A: I have downloaded your bigger sample file. And here is what I have come up with:
awk -v OFS='\t' -v RS= '
((n = split($0, a, / {2,}| *\n/)) % 2) == 0 {
   # print header
   if (NR==1)
      for (i=1; i<=n; i+=2)
         printf "%s", a[i] (i < n-1 ? OFS : ORS)
   # print all records
   for (i=2; i<=n; i+=2)
      printf "%s", a[i] (i < n ? OFS : ORS)
}' reclamiTestFile.txt | column -t -s $'\t'

Code Demo

A: Could you please try following, written and tested with shown samples in GNU awk.
awk '
{
  first=$1
  $1=""
  sub(/^ +/,"")
  if(!arr[first]++){
    ++indArr
    counter[indArr]=first
  }
  ++count[first]
  arr[first OFS count[first]]=$0
}
END{
  for(j=1;j<=indArr;j++){
    printf("%s\t%s",counter[j],j==indArr?ORS:"\t")
  }
  for(i=1;i<=FNR;i++){
     for(j=1;j<=indArr;j++){
       if(arr[counter[j] OFS i]){
          printf("%s\t%s",arr[counter[j] OFS i],j==indArr?ORS:"\t")
       }
     }
  }
}' Input_file | column -t -s $'\t'

column command is taken from @anubhava sir's answer here.


text:
Q: How to see which class (controller, method..) call Model saving, updating, creating I have several classes where I update the model. In the model I have created boot methods where I call some logic and in this logic I want to know which class is the initiator of the Model being updating or creating.
How can I find out this?


text:
Q: When I use onkeyup in HTML for a JS function why does console say my function is not defined? I am trying to make a registration form which has a textbox for confirming your password.

<!DOCTYPE html>

  <title>Register</title>

Register

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

    <input type="text" name="username">

 Email Addres:

    <input type="text" name="email">

 Password:

    <input type="text" name="password">

 Confirm Password:

    <input type="text" name="passwordconf" onkeyup="passVal()">

    <input type="submit" value="Submit">
  </form>

The intent is that whenever a key is released (onkeyup), a function runs which checks to see if the contents of the textboxes are equal (passVal). When I run it add text to both of the password boxes, errors show up in the console saying that passVal is not defined.
I tried making passval equal to a variable
var variableExample = passVal;

and using onkeyup to call the variable, but this made no difference. Except, that now the console said variableExample was not defined instead of passVal. I have no clue why this is not working. Anyone know how I might fix this?

A:

<!DOCTYPE html>

  <title>Register</title>

Register

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

    <input type="text" name="username">

 Email Addres:

    <input type="text" name="email">

 Password:

    <input type="text" name="password">

 Confirm Password:

    <input type="text" name="passwordconf" onkeyup="passVal()">

    <input type="submit" value="Submit">
  </form>

If you query by .getElementsByName(), you'll get an array of elements, as does .getElementsByTagName(). Notice that "Element" is plural.
If you only want one element, just use .getElementsById().

A: getElementsByName return an array of elements,
You should use id instead or get the fist element of array (pass[0])

A: The first thing you need to fix here is how you are getting the element value which is by using
var pass = document.getElementsByName("passwordconf")

which returns an array of all the elements with the name passwordconf.
Adding .value to variable pass will then return undefined because you did not define which element in the array are you trying to get. You can add [0] to get the first element in the array (array indexing always starts count with 0) like this:
pass[0].value;

Note that by doing this, you will not get the passVal is not defined error.


text:
Q: Python y√x how to do this? I'm not looking for the squared root. That is numpy.sqrt(). I'd like to figure out how to calculate y√x, where y is the nth root of x (I'm sorry I can't show it better). For example, say y is 3 and x is 64: 3√64 = 4. I'm not looking solely for the cube of x. I'm looking for nth, where n can be anything.
Thank you!

A: The n-th root is the same as the (1/n)-th power.  So to find the n-th root of x, do x**(1/n).  (Make sure to do from __future__ import division if using Python 2.)

A: Using simple math
>>> a = 8
>>> a**(1./3.)
2.0

3. can be replaced with nth element.


text:
Q: dlatrs subroutine deallocates counter in calling subroutine I've been trying to debug a segfault/sigabort that crashes my simulation software. I've been able to track this to a certain LAPACK subroutine changing a (or actually deallocating, I think) a grid counter in a subroutine that (through a few other subroutines) calls this LAPACK subroutine. Here is my gdb debug session tracking this bug:
(gdb) break trifactorize
Breakpoint 1 at 0x44ad28: file /home/nspeelman/chem1d/src/solver.f, line 925.
(gdb) run
Starting program: /home/nspeelman/chem1d/bin/chem1d

(gdb) watch k
Hardware watchpoint 2: k
(gdb) c
Continuing.
Hardware watchpoint 2: k

Old value = 4
New value = 1
0x000000000044ad48 in trifactorize (lsing=@0x7fffffffdedc) at /home/nspeelman/chem1d/src/solver.f:927
927           DO k = 1, Npoint
(gdb) c
Continuing.
Hardware watchpoint 2: k

Old value = 1
New value = -214061846
dlatrs (uplo=@0x4ffea4, trans=@0x4ffe98, diag=@0x4ffe94, normin=@0x7fffffffbeab, n=@0x3043664, a=0x16867060,
    lda=@0x4fcda4, x=0x7fffffffcf90, scale=@0x7fffffffbe98, cnorm=0x7fffffffd910, info=@0x7fffffffdc2c, _uplo=5,
    _trans=12, _diag=4, _normin=1) at /home/nspeelman/chem1d/src/lapack/src/dlatrs.f:334
334                 DO 20 J = 1, N - 1
(gdb) c
Continuing.

Program received signal SIGABRT, Aborted.
0x00002aaaab480265 in raise () from /lib64/libc.so.6

And the backtrace:
(gdb) bt
#0  0x00002aaaab480265 in raise () from /lib64/libc.so.6
#1  0x00002aaaab481d10 in abort () from /lib64/libc.so.6
#2  0x00002aaaaad88c9e in internal_unpack (d=0x62e9, s=0x62e9)
    at ../../../gcc-4.3.4/libgfortran/runtime/in_unpack_generic.c:104
#3  0x000000000044b41c in trifactorize (lsing=@0x7fffffffdedc) at /home/nspeelman/chem1d/src/solver.f:940
#4  0x3f68b52055ec1bbd in ?? ()
#5  0x3f62d2224f8b7801 in ?? ()
#6  0x3f62e59e02e2572f in ?? ()
#7  0x3f70bab1bd0628c7 in ?? ()
#8  0x3f70cdc893daf1cf in ?? ()
#9  0x3f5a3418697ab4dc in ?? ()
#10 0x3f6b117db1893c97 in ?? ()
#11 0x3f6e0dd1b55652b4 in ?? ()
#12 0x3f6864101f64d2f0 in ?? ()
#13 0x3f7359216186a4dc in ?? ()
#14 0x3f527ee1ff8feb69 in ?? ()
#15 0x3f672c7c504a10f8 in ?? ()
#16 0x3f68f2c8e0ee6963 in ?? ()
#17 0x3f54726715d81583 in ?? ()
#18 0x3f68f2c8e0ee6963 in ?? ()
#19 0x3f6df6a7d0f5e9a5 in ?? ()
#20 0x3f5ef57fdf747822 in ?? ()
#21 0x3f56ef95d71519b0 in ?? ()
#22 0x3f6b736cc1c1feb4 in ?? ()
#23 0x3f60fb91d9400ca4 in ?? ()
#24 0x3f56ef95d71519b0 in ?? ()
#25 0x3f4b4753f00f24d5 in ?? ()
#26 0x3f5a8b9cc465a316 in ?? ()
#27 0x3f3855b423b18a6b in ?? ()
#28 0x3f568360294ec05f in ?? ()
#29 0x3f3679d6e42a4759 in ?? ()
#30 0x3f228fe18a3e97ab in ?? ()
#31 0x3f50df603cf17c50 in ?? ()
#32 0x3f5d0cea5690c8f8 in ?? ()
#33 0x3f550552679170e1 in ?? ()
#34 0x3f3d0ebaa18f7a6f in ?? ()
#35 0x3f66a1b9ef4a7dc4 in ?? ()
#36 0x3f345e9bec8a3d7a in ?? ()
#37 0x3f43854a676ff7cb in ?? ()
#38 0x3f4acbe712d1ba00 in ?? ()
#39 0x3f191497deb0cd86 in ?? ()
#40 0x3f48e220ec5df7ee in ?? ()
#41 0x3f4326498a95447b in ?? ()
#42 0x3f2e05ee4edaa6ff in ?? ()
#43 0x3f285f8e79fe6b92 in ?? ()
#44 0x3f58240bec575a1d in ?? ()
#45 0x3f47c79be94754f7 in ?? ()
#46 0x3f5cf356ce58b75a in ?? ()
#47 0x3f28c2a87c82305d in ?? ()
#48 0x3f35fca48157c9e4 in ?? ()
#49 0x3f41c924b53cdbae in ?? ()
#50 0x3f477c6c115fb520 in ?? ()
#51 0x0000000000000000 in ?? ()

I've been able to reproduce with Ubuntu 11.10 with gfortran 4.6.1, Ubuntu 12.04 with gfortran 4.6.3, Scientific Linux 5.6 with gfortran 4.3.4 and Microsoft Windows with gfortran 4.5.0-1. When I use the Intel Compiler on the Linux boxes I cannot reproduce this error, but I cannot use ifort on Windows, because I'm on an academic license. But I need to fix this with gfortran, because I need to have a Windows version for some students. I'm using compiler flags -funroll-all-loops -fno-f2c -O3 for release versions and flags -fno-f2c -O0 -g3 for debug versions. Both options give these problems.
Also this bug is only reproducable when a large array is used. I'm working with arrays of maximum size (500,Ns) and working arrays of size (Ns,Ns,500). Simulations not crashing use Ns = 53 and when it does crash Ns = 153, but Ns has a declared size of 200.
Finally I'll show the code that crashes:
solver.f, subroutine trifactorize:
      lSing = .FALSE.

      DO k = 1, Npoint
c---- Compute (jacB(k)-jacA(k)*jacC(k-1)). -----------------------------
         SELECT CASE ( k )
            CASE ( 1 )
            CASE DEFAULT
               CALL DGEMM( 'N', 'N', Ns, Ns, Ns, -1.0D0, jacA(:,:,k),
     >                     NsMax, jacC(:,:,k-1), NsMax, 1.0d0,
     >                     jacB(:,:,k), NsMax )
         END SELECT
c---- Factor with Gaussian elimination and estimate condition number.---
         norm = DLANGE( '1', Ns, Ns, jacB(:,:,k), NsMax, Work )
         CALL DGETRF( Ns, Ns, jacB(:,:,k), NsMax, ip(:,k), INFO )
         CALL DGECON( '1', Ns, jacB(:,:,k), NsMax, norm, Condit(k),
     >                Work, IWork, INFO )
c         WRITE(*,*)k,condit(k)
         IF ((1.0d0+condit(k)).EQ.1.0d0 .AND. iLogging.EQ.iDebug) THEN
            Write(line,10) 'Singular Jacobian Matrix'
            CALL ScreenWrite(line, iNormal)

            Write(line,11) 'Gridnumber: ', k
            CALL ScreenWrite(line, iNormal)

            lSing = .TRUE.
            RETURN
         ENDIF

c---- Compute jacC/jacB'-matrix ----------------------------------------
         CALL DGETRS( 'N', Ns, Ns, jacB(:,:,k), NsMax, ip(:,k),
     >                jacC(:,:,k), NsMax, INFO )
      ENDDO

 10   FORMAT(9X,3('-'),1X,9('-'),1X,9('-'),1X,A)
 11   FORMAT(9X,3('-'),1X,9('-'),1X,9('-'),1X,A,i4)

      CALL LogWrite('==> Decompose : Finished', iDebug)

RETURN

dlatrs.f:
*
*           A is lower triangular.
*
            DO 20 J = 1, N - 1
               CNORM( J ) = DASUM( N-J, A( J+1, J ), 1 )
   20       CONTINUE
            CNORM( N ) = ZERO

I've been wondering if I'm using the wrong compiler flags, or if I've stumbled across a rare gfortran bug. Hope somebody knows how to solve this.

A: I've installed gcc 4.7.0 on my Ubuntu machine and on my Windows build slave and this problem disappeared completely in both Windows and Ubuntu. So it seems this bug is fixed with the latest version of gcc.


text:
Q: Linear regression with education as an ordinal variable I wanted to know can I take education as an ordinal variable in my analysis. For example Olevels as 1, A levels as 2, Bachelors as 3, Masters as 4, PHD as 5 and then run a simple linear regression? Is this acceptable and does it make sense? To clarify education is an independent variable

A: There is a very nice summary of what one can do with categorical variables at the UCLA Stats Consulting site.
Breaking it up into dummy variables is probably the most frequently used approach. Here's an answer that gets into the interpretation.


text:
Q: Path messed up for theme assets in Wordpress on RedHat OpenShift I've installed Wordpress on Openshift (free plan). When I go to 'Theme Options' page, the assets path are getting messed up. It's adding the full server path after http://sitename.com/wp-content/ as /var/lib/openshift/54...72a/app-root/data/ resulting in assets paths like this:
https://sitename.com/wp-content//var/lib/openshift/54...72a/app-root/data/themes/lens/wpgrade-core/vendor/redux3/inc/fields/typography/field_typography.css.
I am able to install the theme locally just fine, everything loads perfectly. The site itself loads correctly on OpenShift, only the 'Theme Options' page has this issue.


text:
Q: how to convert a string slice to rune slice how can I convert type []string to []rune?
I know you can do it like this:
[]rune(strings.Join(array,""))
 but is there a better way?

A: I would prefer not to use strings.Join(array,"") for this purpose because it builds one big new string I don't need.  Making a big string I don't need is not space-efficient, and depending on input and hardware it may not be time-efficient.
So instead I would iterate through the array of string values and convert each string to a rune slice, and use the built-in variadic append function to grow my slice of all rune values:
var allRunes []rune
for _, str := range array {
    allRunes = append(allRunes, []rune(str)...)
}


text:
Q: How to create a text field one by one on every click of a button? Here is my task..
How it is working now ?
If i click over the button, I am getting 5 text field one by one. But i want to create a text field on every click of a button.
Eg: First click should create 1st text field
    Second Click should create 2nd text field
    Third Click should create 3rd text field
    Fourth Click should create 4th text field
    Fifth Click should create 5th text field
Here is my code :
- (IBAction)button_click:(id)sender
{
float xaxis = 60;
float yaxis = 130;
for(int i=0;i<5;i++)
{
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(xaxis,yaxis,200,30)];
    textField.tag = i;
    textField.backgroundColor = [UIColor purpleColor];
    [self.view  addSubview:textField];
    yaxis = yaxis+50;
}}

A: You are using for loop on button_click method, which executes five times. So it is adding five text fields.
Remove for loop and this will app one text field on each button click. Also you need to define variables xaxis,yaxis in viewDidLoad method.
Updated code
@interface myController : UIViewController {
   float xaxis;
   float yaxis;
   int i;
}
@end
- (void)viewDidLoad
{
    xaxis = 60;
    yaxis = 130;
    i = 1;
}

- (IBAction)button_click:(id)sender
{
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(xaxis,yaxis,200,30)];
    textField.tag = i;
    textField.backgroundColor = [UIColor purpleColor];
    [self.view  addSubview:textField];
    yaxis = yaxis+50;
    i++;
}

A: First you need to remove the for loop.there is no need of for loop.Instead of that create a variable for count.and initialise it with 0 and create another one variable for Y axis.
For Ex:
var count = 0
var yAxis = 60

Then in the outlet action of button you need to create button programically
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(20,yAxis,200,30)];

Then you need to add this on to your view.
   [self.view  addSubview:textField];

Then you need to increase the height of yAxis.
yAxis = yAxis+60
count = count+1

Remeber to add the if condition for check the count


text:
Q: segment a string to many strings given a pattern in php I'm stuck and I just need a pointer.
I have this string with special characters retrieved from db and i want to segment it to many strings or arrays and in the process i want to exchange those characters with "()".
|p| stands for parent. |c| child.
Example sentence is :
my beautiful car is awesome

*where my , beautiful and car have a parent-child relationship.
The pattern for it :
|p|my|c||p|beautiful|c||c||p|car|p|is|p|awesome

In case you need to see the original array:
Array
(
[0] => Array
    (
        [name] => |p|my
        [parent_id] => 0
        [child] => Array
            (
                [0] => Array
                    (
                        [name] => |c||p|beautiful
                        [parent_id] => 1
                        [child] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => |c||c||p|car
                                        [parent_id] => 2
                                    )

                            )

                    )

            )

    )

[1] => Array
    (
        [name] => |p|is
        [parent_id] => 0
    )

[2] => Array
    (
        [name] => |p|awesome
        [parent_id] => 0
    )

)

The ultimate goal after segmenting and replacement is:
((My(beautiful(car)) (is)(awesome))

A: Since you requested only a pointer I suggest to start with a regex to get an intermediate array:
$str = '|p|my|c||p|beautiful|c||c||p|car|p|is|p|awesome';
$res = preg_split('/((?:\|c\|)*\|p\|)/', $str, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
var_export($res);

/*
array (
  0 => '|p|',
  1 => 'my',
  2 => '|c||p|',
  3 => 'beautiful',
  4 => '|c||c||p|',
  5 => 'car',
  6 => '|p|',
  7 => 'is',
  8 => '|p|',
  9 => 'awesome',
)
*/

A: <?php
$items =
[
    [
        'name'  => 'foo',
        'children' =>
            [
                [
                    'name'  => 'bar',
                    'children' =>
                        [
                            [
                                'name' => 'baz',
                            ]
                        ]
                ]
            ]
    ],
    [
        'name'  => 'bat',
    ],
    [
        'name'  => 'man',
    ]
];

function bracketize($array) {
    $output = '';
    foreach($array as $item) {
        $output .= '(';
        $output .=  $item['name'];
        if(isset($item['children']))
            $output .= bracketize($item['children']);
        $output .= ')';
    }

    return $output;
}

$output = '(' . bracketize($items) . ')';
print $output;

Output:
((foo(bar(baz)))(bat)(man))


text:
Q: asp-all-route-data is appended by asp-route-{value} for all later links in page I'm trying to maintain query string while sometimes appending new parameters, But I will never know the current QS as it's a complex search form.
Trying to wrap my head around why the following happens.

other html...

generates

other html

page=2 being added to the links after the first link is created.
the result should be

other html

Anyone know how I can fix this Or if I have to use a string for href=""? How to get the current url and append new query parameters?
It's easy to do href="domain.com?bla=foo", but if you don't know to add the ? or the &
I can do it the long way. Just wondering if there is an easy way to do this.


text:
Q: How does Redis Makefile include header file prerequisites I was teaching myself GNU Make and thought a look at the Redis Makefile would teach me a thing or two about the tool.
The rule that compiles the source file to the object file is here:
%.o: %.c .make-prerequisites
  $(REDIS_CC) -c $<

Notice that the suffix rule just mentions the C source file (with %.c) as a prerequisite.
But if I add a echo in the middle and run make:
%.o: %.c .make-prerequisites
  echo $^
  $(REDIS_CC) -c $<

Then the first few lines of the output from make is like below:
cd src && make all
make[1]: Entering directory `/home/cltpadmin/code/redis/src'
echo adlist.c .make-prerequisites adlist.h zmalloc.h
adlist.c .make-prerequisites adlist.h zmalloc.h
CC adlist.o

How did make know that adlist.c depends on adlist.h and zmalloc.h?

A: The prerequisites in question come from line one of the Makefile.dep included makefile (included on line 134).
The dep target on line 136 generates that file.
This was a fairly common (though entirely avoidable) step for using the compiler to generate the necessary header file includes. This static method also has issues with conditional header includes I believe.
To clarify, the "avoidable" part of this is that it need not be a separate step and a static dependency file at all. See Advanced Auto-Dependency Generation for details about this idea.


text:
Q: How to detect screen resize events coming from ncurses in QNX? I can not configure to receive events about changing the size of the terminal using ncurses QNX Momentics.
I am using Putyy as a terminal and data is transmitted through the COM port.
My question is how to realize the reception of screen change events when using a remote terminal?
FILE* fcons = fopen("/dev/ser1", "r+");
SCREEN* term = newterm("xterm-r5", fcons, fcons);
int y = 0, x = 0;
//if(y < 24 || x < 80)
//  resizeterm(24, 80);
flushinp();
main_scr = newwin(24, 80, 0, 0);
head_scr = subwin(main_scr, 3, 80, 0, 0);
prompt_scr = subwin(main_scr, 1, 9, 3, 2);
cursor_scr = newwin(1, 60, 3, 6);
output_scr = subwin(main_scr, 18, 76, 5, 2);
keypad(cursor_scr, TRUE);

int f = mousemask(ALL_MOUSE_EVENTS, NULL);

chtype temp_ch = 0;
while(KEY_RESIZE == temp_ch)
   temp_ch = wgetch(cursor_scr);
return 0;

A: A plain serial-port connection like that won't send a SIGWINCH.  In other configurations, e.g., telnet, that's done as a result of NAWS (negotiations about window size--I dont't see a duplicate).  Your application could poll for this by doing what the resize program does, plus a little more, e.g.,

*

*save the cursor-position

*move the cursor to a very-far-off lower-right corner

*ask the terminal where the cursor really is

*wait for the response, to get the actual screensize

*set the terminal's screensize using a system call

*restore the cursor position

*send a SIGWINCH to yourself

Unlike resize, that would be done inside your program, so it would have to save/restore the cursor position (to avoid confusing ncurses).  Keep in mind that ncurses has set the terminal to raw mode, so that part of the initialization would not be needed.


text:
Q: What is the original state in a conflict in git? git config --global merge.conflictstyle diff3

I used this command while setting up my git on my Windows desktop but I don't know what this command does. My course stated that it is used to display the original state of conflict. Can anyone tell what does this mean?

A: This original state you are talking about is what the code looks like in the ancestor node. For example, let's assume you have a git conflict and you didn't enable diff3, it would look something like this:
<<<<<<< HEAD
The changes you made
=======
The changes someone made
>>>>>>> remote

Usually a conflict arises when you change a part of a file and someone else changes the same part resulting in two different changes for the same part. Git can't resolve such conflict and passes control over to you representing the conflict in a way similar to this example. Now it would be helpful if you know what the text was before any edits, so you can compare your changes to the changes that you are merging with. You can do so by enabling the diff3 as you did
<<<<<<< HEAD
The changes you made
|||||||
The original text
=======
The changes someone made
>>>>>>> remote

Now you are able to see what the ancestor node (the original state) had and compare the 3 states.
PS. usually you would want to do some research before asking here because normally you would be answered by either "check the manual" or "do your research first"

A: The diff3 setting alters how merge conflicts are displayed. From the git merge-config man page:

The default [style] is "merge", which shows a <<<<<<< conflict marker, changes made by one side, a ======= marker, changes made by the other side, and then a >>>>>>> marker. An alternate style, "diff3", adds a ||||||| marker and the original text before the ======= marker.


text:
Q: How to save and read special characters in MySql? (Mysqljs & Node) I got a node app that's connected directly to a mysql database v 8.18, charset utf8mb4 and collation utf8mb4_unicode_ci.
I'm trying to save special characters just like ä, ü or ö in some columns but within the database those values are changed into e.g. "Ö" or "ö", which as well results in them not being searchible anymore against the original input.
My connection is setup via the npm package mysqljs as followed:
db = mysql.createConnection({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE,
  port: process.env.DB_PORT,
  charset: "utf8mb4_unicode_ci"
})

while running queries via db.query according to the documentation.
Question now is, what am I doing wrong and what might need to be changed for that to work.
After all I'm mainly creating a db that saves german and english data.
ADDITION:
Saving special characters in the db via UI (e.g. db forge Studio) gets me the following error: Incorrect string value: '\xD6sterr...' for column 'Name_de' at row 1
thanks a bunch for your input :)

A: Checkout this -->
https://medium.com/@haotangio/how-to-properly-setup-mysql-5-7-for-production-on-ubuntu-16-04-dd4088286016
https://mathiasbynens.be/notes/mysql-utf8mb4
problem is utf bytes style used in..
worked for me change from utf8 --> utf8mb4


text:
Q: What constitutes a 'word' in vim? Let's say we have the following in vim atm:
int main () {
    printf("hello");
    return 0;
}

In vim, w moves a word to the right, but what exactly constitutes a 'word'?

For example, if I have the cursor on p of printf, pressing w takes u to ( and pressing another w skips the " and puts the cursor on the h of hello.  Why was the " skipped ?
Pressing another w now takes you to the other " before the ) and pressing another w takes you to the next line.  Why where the ) and ; skipped?
And now the cursor is on the r of return.  Pressing a w takes the cursor on 0 and pressing another w now takes the cursor on the ;.  So in this case, the ; was not skipped unlike in the previous line.  Why is this?

I hope I made my question clear enough but I'm just trying to understand how this all works.

A: From within vim, type
:help word-motions

You will get all the explanation you seek.

A: From :help word:

A word consists of a sequence of letters, digits and underscores, or a
  sequence of other non-blank characters, separated with white space (spaces,
  tabs, ).  This can be changed with the 'iskeyword' option.  An empty line
  is also considered to be a word.

If your use capital W instead:

A WORD consists of a sequence of non-blank characters, separated with white
  space.  An empty line is also considered to be a WORD.

In your example, w treats any sequence of non-keyword letters as a word too.
EDIT: The setting for virtualedit will influence this too: You must have it unset, because line-final punctuation is being skipped by w (add some whitespace to the end of the line to see the difference). If you set virtualedit=onemore the cursor will be able to stop one space beyond the end of the line, and line final punctuation won't ever be skipped.


text:
Q: SELECT list not showing in IE8 due to "height : 75%" CSS I have a webapp that displays a list of names as options in a SELECT block:
<select name="names" .... >
    <option value="Lee">
    <option value="Jamie">
    <option value="Alex">
</select>

I am then applying some CSS to the SELECT block to size it and what not:
width : 100%
height : 75%

This works fine on Chrome and Firefox, but not IE8.  In IE8 the SELECT block doesn't show at all, though it is of course included in the source.  I have tracked it down using the IE8 developer tools to the height attribute being the problem.  If I remove it in the dev tools, the box appears as I would like it.  However, if I take the height attribute completely out, it doesn't appear as I would like in Firefox or Chrome.
Is there anyway I can add a condition to the CSS to say that if the browser is IE to not add the height?  Or is there a better way to solve this problem?
Many thanks.

A: You can use conditional comments.
<!--[if IE 8]>
  <link href="/css/ie_8.css" rel="stylesheet" type="text/css">
<![endif]-->

In the above instance, you are linking to a specific IE8 stylesheet.  This would go in the head of the doc.
You could also just add the style to the page in question.
<!--[if IE 8]>
   <style type="text/css">
       .list{height:100%;}
   </style>
<![endif]-->

A: What are you trying to size it against? The 75% would be "75% of the height of the parent element".
IE doesn't like height to be measured in percent when it doesn't have a fixed height for the parent element. If you give the parent element a fixed height, it should work. But I guess that might break other aspects of your layout.
Depending on the context, you might be able to acheive the effect you're after by using em units instead of percent.
For example, if the container is a single line, you could acheive the same thing by using 0.75em instead of 75%. (not that this would be particularly useful, as it would obscure parts of the select box, but you get the idea)


text:
Q: Problems with my Hangman game (Python) I know this is long, please bear with me. I am taking this online class and our big project is to write code for the game Hangman. After looking online and finding some examples in order to help me get an idea of where to begin and how to go about this, I am almost done with the game. I am having just a few tiny issues that need to be cleaned up which I can't figure out how to fix. The first one deals with the spaces not lining up with the letters. So lets say the computer selects the word BASEBALL it will display _ _ _ _ _ _ _ _ and it will seem to line up correctly. So if I guess B then it will show B _ _ _ B _ _ _ and so on and so fourth, but as I add more and more letters, they don't line up. For instance, I will have BA_EBALL _ _ _ _ when there is really only 1 letter left (the S). I don't know why or how it keeps adding extra blanks at the end. Another thing that I am having trouble with is repeat guesses. I programmed the game to display a message telling you to try again if you guess more than one letter or something that isn't a letter. I have a way to keep track of guessed letters, but for some reason it still allows for repeat guesses. Any help would be greatly appreciated. I apologize for this being so long and the code being longer.
import random
hangManPics = ['''<hangman art omitted>''']

words = 'AMERICAN NATIONAL BASEBALL BASE BALL STRIKE FOUL OUT\
 SINGLE DOUBLE TRIPLE HOMERUN PITCHER CATCHER OUTFIELD INFIELD\
 DIAMOND STADIUM CARDINALS DIAMONDBACKS BRAVES ORIOLES CUBS REDS\
 INDIANS ROCKIES TIGERS ASTROS ROYALS ANGELS DODGERS MARLINS\
 BREWER TWINS METS YANKEES ATHLETICS PHILLIES PIRATES PADRES\
 GIANTS MARINERS RAYS RANGERS NATIONALS STRIKEOUT RUNS FASTBALL\
 SLIDER CURVEBALL STEAL'

##  Select a random word from a word list
def getRandomWord(wordList):
    newWords = words.split()    ##  split the word list
    word = newWords[random.randint(0, len(newWords) - 1)]
    return word

def displayBoard(hangManPics, missedLetters, correctLetters, secretWord):
    print(hangManPics[len(missedLetters)])
    print()

    print("Missed letters:", end = '')
    for letter in missedLetters:
        print(letter, end = '')
    print()

    blanks = '_ ' * len(secretWord)

    for i in range(len(secretWord)):
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i + 1:]

    for letter in blanks:
        print(letter, end = '')
    print()

def getGuess(alreadyGuessed):
    while True:
        guess = input("Please guess a letter. ")
        upperGuess = guess.upper()
        if len(upperGuess) != 1:
            print("Please enter a single letter.\n")
        elif guess in alreadyGuessed:
            print("You have already guessed that letter. Please select another one.\n")
        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
            print("Your guess must be a letter.\n")
        else:
            return upperGuess

def playAgain():
    print("Would you like to play again? (yes or no)")
    return input().upper().startswith('Y')

print("H A N G M A N")
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
endGame = False

while True:
    displayBoard(hangManPics, missedLetters, correctLetters, secretWord)

    guess = getGuess(missedLetters + correctLetters)

    if guess in secretWord:
        correctLetters = correctLetters + guess

        foundAllLetters = True
        for i in range(len(secretWord)):
            if secretWord[i] not in correctLetters:
                foundAllLetters = False
                break
        if foundAllLetters:
            print('''\<ascii art omitted>\n''')
            print("The secret word is", secretWord, ". You have won!\n")
            endGame = True
    else:
        missedLetters = missedLetters + guess

        if len(missedLetters) == len(hangManPics) - 1:
            displayBoard(hangManPics, missedLetters, correctLetters, secretWord)
            print('''<ascii art omitted>''')
            print("You have run out of guesses. The secret word is",\
                  secretWord, ". You lose.\n")
            endGame = True

    if endGame:
        if playAgain():
            missedLetters = ''
            correctLetters = ''
            endGame = False
            secretWord = getRandomWord(words)
        else:
            break

playAgain()

A: Each of your two problems are isolated to one function. In the future, you should debug each function individually:

*

*Copy each function into a separate python file without the rest of the program (except for the very minimal you need to get the function to work)

*Call the function with various example data until you are satisfied that the function is working or not

*If the function is not working, get rid of anything inside the function that is not relevant to the problem. The less code you have, the easier it is to figure out what is wrong

*If you cannot fix the problem yourself, ask a question about each isolated problem with the very minimal code you have created.

Here are answers for the two questions you would have had if you had isolated the problem:
Problem 1: displayBoard function:
The problem is that you forgot you have doubled the length of blanks, because you add a space for each letter: blanks = '_ ' * len(secretWord). For each index i of secretWord, the index is i*2 for blanks. Also, there is no need to print a word letter-by-letter. The fixed version is:
def displayBoard(hangManPics, missedLetters, correctLetters, secretWord):
    blanks = '_ ' * len(secretWord)

    for i in range(len(secretWord)):
        if secretWord[i] in correctLetters:
            blanks = blanks[:i*2] + secretWord[i] + blanks[i*2 + 1:]

    print(blanks)

displayBoard([], ['Z', 'K', 'C'], ['B', 'A', 'E', 'L'], 'BASEBALL')

An index-less way of doing it would be to replace all non-guessed letters with underscores, then insert the spaces between the letters:
from string import ascii_uppercase

def displayBoard(hangManPics, missedLetters, correctLetters, secretWord):
    # print(hangManPics[len(missedLetters)])
    print()

    print("Missed letters: " + ''.join(missedLetters))

    # copy secretWord to blanked
    blanked = secretWord

    # Replace missing letters with blanks
    for letter in ascii_uppercase:
        if letter not in correctLetters:
            blanked = blanked.replace(letter, '_')

    # Add spaces between letters
    blanked = ' '.join(list(blanked))

    print(blanked)

displayBoard([], ['Z', 'K', 'C'], ['B', 'A', 'E', 'L'], 'BASEBALL')

Problem 2: getGuess function:
You make the input letter uppercase with upperGuess = guess.upper(), but then you continue to use the lowercase guess. Corrected version:
def getGuess(alreadyGuessed):
    while True:
        guess = input("Please guess a letter. ")
        upperGuess = guess.upper()
        if len(upperGuess) != 1:
            print("Please enter a single letter.\n")
        elif upperGuess in alreadyGuessed:
            print("You have already guessed that letter. Please select another one.\n")
        elif upperGuess not in 'abcdefghijklmnopqrstuvwxyz'.upper():
            print("Your guess must be a letter.\n")
        else:
            return upperGuess

getGuess(['A', 'B', 'C'])  # Guessing "a" should produce error


text:
Q: how to have wildcards in angular routes
Possible Duplicate:
AngularJS - Route - How to match star (*) as a path

How do I specify wildcards in my routes -
$routeProvider
      .when('/admin/*', {
        templateUrl: 'admin.html',
        controller: 'AdminCtrl'
      })

So the above should work for /admin/users and /admin/users/1 or /admin/org/3. So there could be either one or two levels of path after admin. How do I do it ?

A: Currently AngularJS does not support regular expression in routes.
You can workaround as follows
 app.config(['$routeProvider', function($routeProvider) {
        $routeProvider
                 .when('/admin', {templateUrl: 'admin.html', controller: 'AdminCtrl'})
                 .when('/admin/:type', {templateUrl: 'admin.html', controller: 'AdminCtrl'})
                 .when('/admin/:type/:id', {templateUrl: 'admin.html', controller: 'AdminCtrl'});
 }]);

http://plnkr.co/edit/tBumW2oEqki2sEl1hjSc?p=preview
IMO, it is good idea to have the separate controller for both admin and users, unless otherwise you have some special requirement.


text:
Q: Get primarys keys affected after select, update or insert only using SQL? How to get the primary key (assuming know his name by looking show keys) resulting from an insert into?
How to get the primary keys of rows affected by an update? (as in the previous case, independent of the key name).
How to get the primary keys returned from a select query (in the query even if the key is not one of the fields surveyed).
I need to SQLs commands I run after the inserts, updates and selects in my application to obtain such information, it is possible?
My database is MySQL.
I need only sqls because i am making a logic of cache queries to aplicate in many applications (java and php) and i wish that the logic be independent of language.
example:
select name from people
i need that a query executed after this return the pk of these people

A: SELECT LAST_INSERT_ID();

And seriously, putting "primary key from insert mysql" into Google gets you a Stack Overflow answer as the first result.
EDIT: more discussion based on comments.
If you want to see what rows are affected by an update, just do a SELECT with the same WHERE clause and JOIN criteria as the UPDATE statement, e.g.:
UPDATE foo SET a = 5 WHERE b > 10;

SELECT id FROM foo WHERE b > 10;

If you are INSERTing into a table that does not have an auto-increment primary key, you don't need to do anything special. You already know what the new primary key is, because you set it yourself in the INSERT statement. If you want code that can handle INSERT statements coming from outside of the code that will be tracking PK changes, then you'll either need to parse the INSERT statement, or have the calling code provide information about the primary key.


text:
Q: Jquery on click instead of hover I have this jQuery code that opens an accordeon on hover but i need to make it work each tab on click instead, i've tried to change the "hover" to "click" but no success, could someone here please help me ?
Thanks in advance.
$(function() {
    $('#accordion > li').hover(function() {
        var $this = $(this);
        $this.stop().animate({'width':'480px'},500);
        $('.heading',$this).stop(true,true).fadeOut();
        $('.bgDescription',$this).stop(true,true).slideDown(500);
        $('.description',$this).stop(true,true).fadeIn();
    }, function() {
        var $this = $(this);
        $this.stop().animate({'width':'115px'},1000);
        $('.heading',$this).stop(true,true).fadeIn();
        $('.description',$this).stop(true,true).fadeOut(500);
        $('.bgDescription',$this).stop(true,true).slideUp(700);
    });
});

the idea from Tushar Gupta is the only one that's partially working, it opens the accordeon on click, but if the user clicks another tab while one is open there's a bug...
i make a fiddle with the whole code.
http://jsfiddle.net/C8Kp8/ <-- Tushar Gupta's solution
http://jsfiddle.net/SHmuc/ <-- Original Code
thank you all for your help, its really appreciated.

A: You can use .toggle() or this
    $(function() {
    $('#accordion > li').click(function() {
        var $this = $(this);

        if ($this.hasClass('open')) {
            $this.stop().animate({'width':'480px'},500);
            $('.heading',$this).stop(true,true).fadeOut();
            $('.bgDescription',$this).stop(true,true).slideDown(500);
            $('.description',$this).stop(true,true).fadeIn();
            $this.removeClass('open');
        }
        else {
            $this.stop().animate({'width':'115px'},1000);
            $('.heading',$this).stop(true,true).fadeIn();
            $('.description',$this).stop(true,true).fadeOut(500);
            $('.bgDescription',$this).stop(true,true).slideUp(700);
            $this.addClass('open');
        }
    });
});

A: Take a look at this. @Alex's answer is good but ignores the first click, and doesn't close the open elements when a closed element is clicked. FIDDLE. In this version, the more links in the accordion elements also work.
$(function() {
     $('#accordion li').click(function() {
         var $this = $(this);

         if (!$this.hasClass('open')) {
             // open clicked accordion element
             $this.stop().animate({'width':'480px'},500);
             $('.heading',$this).stop(true,true).fadeOut();
             $('.bgDescription',$this).stop(true,true).slideDown(500);
             $('.description',$this).stop(true,true).fadeIn();

             // close other open accordion element
             $("#accordion li.open").stop().animate({'width':'115px'},1000);
             $("#accordion li.open .heading").stop(true, true).fadeIn();
             $("#accordion li.open .description, #accordion li.open .bgDescription").stop(true, true).fadeOut();
             $("#accordion li.open").removeClass("open");
             $this.addClass('open');
         }
         else {
             // close this accordion element
             $this.stop().animate({'width':'115px'},1000);
             $('.heading',$this).stop(true,true).fadeIn();
             $('.description',$this).stop(true,true).fadeOut(500);
             $('.bgDescription',$this).stop(true,true).slideUp(700);
             $this.removeClass('open');
         }
     });

     $('#accordion > li a').click(function(e){
         e.stopPropagation();
     });
 });


text:
Q: Reading file to disk error, "name and value are required for setHeader()" Trying to allow users to upload image files to the Node.js server in a MEAN Stack application. I am using ng-file-upload for the client side angular directive. That seems to be working good enough. I run into an error when I pass the image to the server.
I use an API route to handle the work on the server side. The server will be responsible for saving the file to disk with node-multiparty module. It seems to hit route but when it tries to emit a close event I get the error. throw new Error('"name" and "value" are required for setHeader().'
The file I want is in my temp folder but it doesn't get saved to the target directory on my server plus I get the header error after the file should have been saved. So I need to stop the error and save the file with fs.rename() to the target image directory.
Here is the code that is breaking.
file api.js
// router to save images
router.route('/img/upload')

.post(function (req, res) {
console.log("image upload hits the router")

var options = {};
var count = 0;
var form = new multiparty.Form(options);

//save file to disk
form.on('file', function (name, file) {
var uploadDirectory = 'img/user/profile/';
var oldPath = file.path;
var newPath = uploadDirectory + file.originalFilename;

fs.rename(oldPath, newPath, function (err) {
if (err) throw err;
console.log('renamed complete');
});
});

// Close emitted after form parsed
form.on('close', function () {
console.log('Upload completed!');
res.setHeader('text/plain'); // Here is the line that gives an error.
res.end('Received ' + count + ' files');
});

// Parse req
form.parse(req);

});

A: So this is what I got to work for me
The actual line that gave me an error was setHeaders. It appears I needed to put the name and value as strings separated by a comma. This works perfectly for me now. I hope it saves everyone time coding.
// post
.post(function (req, res) {

var options = {};
var count = 0;
var form = new multiparty.Form(options);

form.on('error', function (err) {
console.log('Error parsing form: ' + err.stack);
});

//save file to disk
form.on('file', function (name, file) {
var uploadDirectory = '/img/user/profile/';
var oldPath = file.path;
var newPath = uploadDirectory + file.originalFilename;

fs.rename(oldPath, newPath, function (err) {
if (err) throw err;
console.log('renamed complete');
});
});

// Close emitted after form parsed
form.on('close', function () {
console.log('Upload completed!');
res.setHeader('Content-Type', 'text/plain');
res.end('Received ' + count + ' files');
});

// Parse req
form.parse(req);

});


text:
Q: ¿Qué diferencia hay, en memoria, de las siguientes 2 sentencias? String s1 = new String("Hola!");

String s2 = "Hola!";

A: La diferencia consiste en el uso o no del String pool.
Uso de la palabra clave new
Cuando creas un String usando new, se creará un nuevo objeto en el heap en tiempo de ejecución:
String s1 = new String("Hola!"); //Siempre se crea el objeto en el heap

Uso de literales
Cuando creas un String usando un literal, el compilador busca en el String pool un String que tenga el mismo valor. Si lo hay, asigna su valor a tu variable. Si no lo hay, crea un String -que es inmutable- en el String pool y asigna su valor a tu variable:
String s2 = "Hola!" //No existe esta String en el pool, se crea
String s3 = "Hola!" //Ya existe. No se crea otra, se asigna su valor a s3.

¿Qué es el String pool?
El String pool es la forma que tiene Java de implementar la Internalización de Strings (Traducido y resaltado por mi):

En ciencias de la computación, la internalización de strings es una forma de guardar sólo una copia de cada cadena distinta. Esta copia debe ser inmutable

Esto significa que, en nuestro ejemplo, s2y s3 apuntan al mismo objeto. Ésta es la razón por la que cosas como:
if (s2 == s3) {
    //cosas
{

Dan problemas. Esa comparación podría dar true, porque estás comparando exactamente el mismo objeto inmutable, pero siempre es mejor utilizar el método equals() para eso, porque no sabes cómo se crean:
String s1 = "Hola";
String s2 = "Hola";
String s3 = "Adios";
String s4 = new String("Hola");

System.out.println(s1 == s2); //true
System.out.println(s1 == s3); //false
System.out.println(s1 == s4); //false
System.out.println(s1.equals(s4)); //true


text:
Q: orientdb load graph csv of nodes and edges I'm a newbie in Orientdb .
I have a csv file which has both the nodes and the edge and I need to create a graph out of that csv file .
csv file
"p1","p2","score"
"LGG_00001","LGG_01682",282
"LGG_00001",".LGG_01831",183
"LGG_00001","LGG_01491",238

The edge is IsActingWith which had the score attribute
{
"source": {
    "file": {
        "path": "C:/Users/sams/Desktop/OrientDB2/lac2.csv"
    }
},
"extractor": {
    "csv": {}
},
"transformers": [
    {
        "vertex": {
            "class": "lac2"
        }
    },
    {
        "vertex": {
            "class": "lac2"
        }
    },

    {
        "edge":
        {
                "class": "IsActingWith",
                "joinFieldName": "score_p",
                "lookup": "acore",
                "direction": "out"
        }
    }

],
"loader": {
    "orientdb": {
        "dbURL": "plocal:C:/Users/sams/Desktop/OrientDB2/database/proj",
        "dbType": "graph",
        "dbAutoCreate": true,
        "classes": [
            {
                "name": "lac2",
                "extends": "V"
            },
            {
                "name": "lac2",
                "extends": "V"
            },
            {
                "name": "IsActingWith",
                "extends": "E"
            },

        ]

    }
}
}

That is what I tried but it does not seem logic to me.
The final result I'm looking for is to have a graaph made of p1->ACTINGWITH-> p2 and ACTINGWITH has score of the score attribute

A: maybe there's a better solution but this works.
My plan is to use 3 different etl scripts: first and second for inserting the vertices and the third for the edges. Of course you'll need to execute them in order.
vertex_import_p1.json
{
    "source": { "file": { "path": "/home/ivan/Cose/OrientDB/issues/stack/44641116/file.csv" } },
    "extractor": { "csv": {
        "separator": ",",
    "columns": ["p1:String","p2:String","s:Integer"] } },
    "transformers": [
        { "command": { "command": "UPDATE lac2 set p='${input.p1}' UPSERT WHERE p='${input.p1}'"} }
    ],
    "loader": {
        "orientdb": {
            "dbURL": "plocal:/home/ivan/Cose/OrientDB/issues/stack/44641116/db",
            "dbUser": "admin",
            "dbPassword": "admin",
            "dbType": "graph",
            "classes": [
                {"name": "lac2", "extends": "V"},
                {"name": "isActingWith", "extends": "E"}
            ]
        }
    }
}

vertex_import_p2.json
{
    "source": { "file": { "path": "/home/ivan/Cose/OrientDB/issues/stack/44641116/file.csv" } },
    "extractor": { "csv": {
        "separator": ",",
    "columns": ["p1:String","p2:String","s:Integer"] } },
    "transformers": [
        { "command": { "command": "UPDATE lac2 set p='${input.p2}' UPSERT WHERE p='${input.p2}'"} }
    ],
    "loader": {
        "orientdb": {
            "dbURL": "plocal:/home/ivan/Cose/OrientDB/issues/stack/44641116/db",
            "dbUser": "admin",
            "dbPassword": "admin",
            "dbType": "graph",
            "classes": [
                {"name": "lac2", "extends": "V"},
                {"name": "isActingWith", "extends": "E"}
            ]
        }
    }
}

edge_import_s.json
{
    "source": { "file": { "path": "/home/ivan/Cose/OrientDB/issues/stack/44641116/file.csv" } },
    "extractor": { "csv": {
        "separator": ",",
    "columns": ["p1:String","p2:String","s:Integer"] } },
    "transformers": [
        { "command": { "command": "CREATE EDGE isActingWith FROM (SELECT FROM lac2 WHERE p='${input.p1}') TO (SELECT FROM lac2 WHERE p='${input.p2}') set score=${input.s}"} }
    ],
    "loader": {
        "orientdb": {
            "dbURL": "plocal:/home/ivan/Cose/OrientDB/issues/stack/44641116/db",
            "dbUser": "admin",
            "dbPassword": "admin",
            "dbType": "graph",
            "classes": [
                {"name": "lac2", "extends": "V"},
                {"name": "isActingWith", "extends": "E"}
            ]
        }
    }
}

And here are the situation after the executions:
orientdb {db=db}> select from lac2

+----+-----+------+---------+-------------------+---------------+
|#   |@RID |@CLASS|p        |out_isActingWith   |in_isActingWith|
+----+-----+------+---------+-------------------+---------------+
|0   |#21:6|lac2  |LGG_00001|[#25:5,#26:1,#27:1]|               |
|1   |#21:7|lac2  |LGG_01682|                   |[#25:5]        |
|2   |#22:3|lac2  |LGG_01831|                   |[#26:1]        |
|3   |#23:1|lac2  |LGG_01491|                   |[#27:1]        |
+----+-----+------+---------+-------------------+---------------+

4 item(s) found. Query executed in 0.003 sec(s).
orientdb {db=db}> select from isActingWith

+----+-----+------------+-----+-----+-----+
|#   |@RID |@CLASS      |score|out  |in   |
+----+-----+------------+-----+-----+-----+
|0   |#25:5|isActingWith|282  |#21:6|#21:7|
|1   |#26:1|isActingWith|183  |#21:6|#22:3|
|2   |#27:1|isActingWith|238  |#21:6|#23:1|
+----+-----+------------+-----+-----+-----+

3 item(s) found. Query executed in 0.004 sec(s).


text:
Q: Setting up German language support for Pepper Robot and installing App Launcher Yesterday we did a factory reset for our Pepper robot and we think it was successful. Now we wish to set up German language support in the robot. I googled some ways of doing that and found that I could set up a second language for the robot from the robot's registered account at Softbank's website which I did as you can see.
But this feature did not reflect on the robot even after the reboot. Can someone please help me with this issue. Thanks in advance.

A: Once the language has been installed, you need to open the settings of your robot and change the language there.
Jonas

A: In my experience, if the update does not trigger for some reason, try installing an arbitrary app from the application store, and then press the "send signal" button under 'manage' to force an update. Sometimes this seems to be needed needed. After the update in triggered and the app and language is installed, the app can be uninstalled.


text:
Q: How make SSL server socket support both http & https in java? I'm trying to create simple web server using java sockets which should support both http & https. But i can acheive only one at a time. I need to logic which supports both http @ port 80 & https @ port 443 at same time.

This is the sample code for HTTPS Server using sslsocket. We can acheive HTTP Server using simple ServerSocket.
public class HttpsServer {
    public static void main(String[] args) {
    try {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream("/opt/p12file.p12"), "p12pass".toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, "p12pass".toCharArray());

        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(kmf.getKeyManagers(), null, null);

        SSLServerSocketFactory ssf = sc.getServerSocketFactory();
        SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(8080);

        while (true) {
            SSLSocket c = (SSLSocket) s.accept();
            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
            w.write("HTTP/1.0 200 OK");
            w.newLine();
            w.write("Content-Type: text/html");
            w.newLine();
            w.newLine();
            w.write("
Https Server Works
");
            w.newLine();
            w.flush();
            w.close();
            c.close();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

}
Can anyone help me please??

A:
How make SSL server socket support both http & https in java?

You can't. HTTP is plaintext, which SSLServerSocket cannot support.

I'm trying to create simple web server using java sockets which should support both http & https. But I can achieve only one at a time. I need to logic which supports both http @ port 80 & https @ port 443 at same time.

You need:

*

*a plaintext ServerSocket listening at 80

*an SSLServerSocket listening at 443

*an accept-loop thread for each of these

*a connection thread per accepted socket.

You will never ever get it done inside a static main() method. I suggest you read the 'Custom Networking' section of the Java Tutorial, and then the JSSE Reference Guide.
You also of course need to take a really good look at RFC 2616 HTTP 1.1. It is extremely non-trivial to implement correctly.
As suggested in comments, you should really use something off-the-shelf.

A: You have two options:

*

*Use two different ports, one for http and one for https.

*SSL Hello detection / Port unification:
In HTTP and HTTPS the client is expected to talk first. So the server can use this to detect the protocol the client is expecting:

*

*if the client sends a TLS ClientHello, then proceed with a TLS handshake;

*if a plain HTTP request is sent instead, then handle the request as it is.

More information:

*

*Can a Java server accept both SSL and plaintext connections on one port?

*Is it possible to change plain socket to SSLSocket?


text:
Q: pthread to invoke member func by wrapping it externally I'm trying to invoke a member function by pthread by using an external wrapper but it doesn't quite work for me, I get a seg fault. Why is this?
Here's a little test program that displays the problem:
#include <iostream>
#include <pthread.h>
class test {
    public:
        test();
        ~test();
        void RunTh(void);
    private:
        pthread_t *pid;
};
void *Run_wrp(void *context);
void test::RunTh(void)
{
    while(1);
}
test::test()
{
    pthread_create(pid,NULL,&Run_wrp,this);
}
test::~test(){}

int main(void) {
    test tmp;
    std::cin.get();
}

void *Run_wrp(void *context)
{
    ((test*)context)->RunTh();
}

A: Your pid member variable is just a pointer, not an actual pthread_t object.
Change it to:
private:
    pthread_t pid;

Then create the new thread with:
pthread_create(&pid,NULL,&Run_wrp,this);

Also, if you want to keep everything contained in the class, you can make your Run_wrp() function a static member function of test, as long as you keep the same signature (return value/arguments). It needs to be static, as non-static functions take the this pointer to the class as a hidden argument, and thus end up with a different signature than what you need for pthread_create().


text:
Q: Adding hyperlinks to specific words using react-intl I have the following in a messages.ts file
import { defineMessages } from "react-intl";

export const messages = defineMessages({
  downloadInstructions: {
    id: "download_app.instructions",
    defaultMessage:
      "You'll be directed to the Apple App Store or Google Play Store.",
  },
});

In my app I have the following:
<Text>{intl.formatMessage(messages.downloadInstructions)}</Text>

How can I update this to make both the Apple App Store and Google Play Store be hyperlinked (to the same url?).
I have tried updating my messages.ts file to the below, which resulted in the tags being displayed on the webpage which isn't intended.
import { defineMessages } from "react-intl";

export const messages = defineMessages({
  downloadInstructions: {
    id: "download_app.instructions",
    defaultMessage:
      "You'll be directed to the Apple App Store or Google Play Store.",
  },
});

Thanks in advance.


text:
Q: The sum of subspaces of $V$ is the smallest subspace of $V$ containing each of the subspaces Let $V$ be a vector space with subspaces $U_1,\ldots,U_k$. Then $U_1+\ldots+U_k$ is the smallest subspace of $V$ containing each of $U_1,\ldots,U_k$.
Here's my approach (using Einstein summation) where I have a doubt:
Let $v\in U_1+\ldots+U_k$. Then $v=u_1+\ldots+u_k$ which is a linear combination of elements from $U_1\cup\ldots\cup U_k$, which means $v\in\text{span}(U_1\cup\ldots\cup U_k)$.
Let $v\in\text{span}(U_1\cup\ldots\cup U_k)$. Then $v$ is a linear combination of vectors $u_{ij}$ from subspaces ($j$ subscript denotes which subspace that vector is from and $i$ runs over vectors from a particular subspace):
$$v=b^ja^iu_{ij}=b^jw_j$$ where $a^iu_{ij}=w_j$ lies in $U_j$ due to closure under linear combinations.
My doubt is that any linear combination can contain arbitrarily many terms. Is the above approach valid in the general sense?

A: Let $W$ be any subspace of $V$ containing each of  $U_1,U_2,\cdots, U_k$. Then for any $u_i \in U_i~~~i=1, \cdots, k$, $u_1+u_2+\cdots+u_k \in W~~~(\because \textit{subspace})$ implying $U_1+U_2+\cdots+U_k \subseteq W$, hence $U_1+U_2+\cdots+U_k$ is the smallest.


text:
Q: Issues with Screen Scaling on External Monitor I am using a 2011 Macbook Pro and a horrible Dell Display for some extra space. Because the resolution is horrible on the extra screen, the windows are larger then I would like and Mac OS X does not let me change the scale for it.
Is there an app of something else I could use to solve my problem?

A: I think changing the screen resolution on the external display could help you in this case. Initially when you open up the Displays Settings from System Preferences. It would look something like this below with a limited set of display resolutions.

This list of resolution is what OS X thinks is the best for your Display. When connecting an external monitor/display, there are chances the aspect ratio is wrong because it's a widescreen monitor.
Solution

*

*Open the Display Settings from System Preferences on the second monitor.

*Hold the Option key and click on the Scaled button. It should open up a lot more Display resolutions.

Try finding what's the best option for your display/monitor by trial and error.