text:
Q: Convert a hex string to base64 in an Excel function I have a lengthy string of hex values to convert to base64.
I'm looking for a simple format cell function such as =Hex2b64(Hexstring) that will accept any length of hex characters.
I have been using http://home.paulschou.net/tools/xlate/ to do my conversion manually. The conversion works and the data is received by all relevant databases and parsed appropriately.
The data I am receiving is hex represented binary, which has been converted in multiple blocks and concatenated into long hex strings in accordance with project documentation that I am not privy to.
A typical Input String would be:
Hex= 00014088F6650101393939393939392D30304646463238313030000343332353430342D35353FA10000002805900100002805

and the corresponding output would be:
B64 = AAFAiPZlAQE5OTk5OTk5LTAwRkZGMjgxMDAAA0MzI1NDA0LTU1P6EAAAAoBZABAAAoAF

A: Function Hex2Base64(ByVal sHex)

    Static oNode As Object
    Dim a() As Byte

    If Len(sHex) Mod 2 <> 0 Then
        sHex = Left(sHex, Len(sHex) - 1) & "0" & Right(sHex, 1)
    End If
    If oNode Is Nothing Then
        Set oNode = CreateObject("MSXML2.DOMDocument").createElement("Node")
    End If
    With oNode
        .text = ""
        .dataType = "bin.hex"
        .text = sHex
        a = .nodeTypedValue
        .dataType = "bin.base64"
        .nodeTypedValue = a
        Hex2Base64 = .text
    End With

End Function


text:
Q: Function to return List of Map while iterating over String, kmer count I am working on creating a k-mer frequency counter (similar to word count in Hadoop) written in Scala. I'm fairly new to Scala, but I have some programming experience.
The input is a text file containing a gene sequence and my task is to get the frequency of each k-mer where k is some specified length of the sequence.
Therefore, the sequence AGCTTTC has three 5-mers (AGCTT, GCTTT, CTTTC)
I've parsed through the input and created a huge string which is the entire sequence, the new lines throw off the k-mer counting as the end of one line's sequence should still form a k-mer with the beginning of the next line's sequence.
Now I am trying to write a function that will generate a list of maps List[Map[String, Int]] with which it should be easy to use scala's groupBy function to get the count of the common k-mers
import scala.io.Source

object Main {
  def main(args: Array[String]) {

    // Get all of the lines from the input file
    val input = Source.fromFile("input.txt").getLines.toArray

    // Create one huge string which contains all the lines but the first
    val lines = input.tail.mkString.replace("\n","")

    val mappedKmers: List[Map[String,Int]] = getMappedKmers(5, lines)

  }

  def getMappedKmers(k: Int, seq: String): List[Map[String, Int]] = {
    for (i <- 0 until seq.length - k) {
      Map(seq.substring(i, i+k), 1) // Map the k-mer to a count of 1
    }
  }
}

Couple of questions:

*

*How to create/generate List[Map[String,Int]]?

*How would you do it?

Any help and/or advice is definitely appreciated!

A: You're pretty close—there are three fairly minor problems with your code.
The first is that for (i <- whatever) foo(i) is syntactic sugar for whatever.foreach(i => foo(i)), which means you're not actually doing anything with the contents of whatever. What you want is for (i <- whatever) yield foo(i), which is sugar for whatever.map(i => foo(i)) and returns the transformed collection.
The second issue is that 0 until seq.length - k is a Range, not a List, so even once you've added the yield, the result still won't line up with the declared return type.
The third issue is that Map(k, v) tries to create a map with two key-value pairs, k and v. You want Map(k -> v) or Map((k, v)), either of which is explicit about the fact that you have a single argument pair.
So the following should work:
def getMappedKmers(k: Int, seq: String): IndexedSeq[Map[String, Int]] = {
  for (i <- 0 until seq.length - k) yield {
    Map(seq.substring(i, i + k) -> 1) // Map the k-mer to a count of 1
  }
}

You could also convert either the range or the entire result to a list with .toList if you'd prefer a list at the end.
It's worth noting, by the way, that the sliding method on Seq does exactly what you want:
scala> "AGCTTTC".sliding(5).foreach(println)
AGCTT
GCTTT
CTTTC

I'd definitely suggest something like "AGCTTTC".sliding(5).toList.groupBy(identity) for real code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't move page file to external SD-card Recently I got a windows 8.1 tablet, but it has very low internal memory (16GB). It has extendable memory via an SD card (I put in 64GB) and I tried moving page file to it, but after setting no page file on C drive and system managed on D and restarting tablet I get the error. So, is it even possible to move the page file this way?

A: About the problem.
I think that Windows tries to attach the pagefile before it initializes SD card reader's driver. That makes pagefile unavailable at this time, so Windows creates a temporary one. This issue is unsolvable.
Is it a problem?
No, I don't think so. While hard disks are few orders of magnitude slower than RAM, SD cards are even slower. It means that your system would become really sluggish as soon as it starts paging, ie. when it's low on RAM - and you don't want that.
Moreover, SD cards have lifetime limited by number of writes. It's usually not a problem when they are used for file storage, but paging would kill a card very quickly, probably within few months at best.
Use SD card for storage and internal memory for paging, not the other way.


text:
Q: Adding gridlines to each subplot pie chart in matplotlib I have a 2d array with 8 sub arrays. I want to plot each of the array in pie charts as shown:

fig, axes = plt.subplots(4, 2,figsize=(15, 15))

axes[0,0].pie(counts_list[0])
axes[0,1].pie(counts_list[1])

axes[1,0].pie(counts_list[2])
axes[1,1].pie(counts_list[3])

axes[2,0].pie(counts_list[4])
axes[2,1].pie(counts_list[5])

axes[3,0].pie(counts_list[6])
axes[3,1].pie(counts_list[7])

plt.show()

What I have achieved with this code:

Now I have tried every possible answer solution from SO and the internet, added grids like axes[0][0].grid() to each, added
plt.rcParams['axes.grid'] = True

but for some reason the grid lines are not coming up on the pie charts. How do I solve this?
Any guidance in the correct direction is appreciated. Thanks. Also if the code for the arrays is required, please let me know in the comments.
I have plotted the actual pie charts, just need to add the gridlines and the color scheme.

A: The following should work:
from matplotlib import pyplot as plt

fig, ax = plt.subplots()

data = [32, 45, 67, 12, 1]

ax.pie(data)

# turn on frame
ax.set_frame_on(b=True)

# create locations of grid points
xrange = ax.get_xlim()
ngrids = 7
dx = (xrange[1] - xrange[0]) / ngrids
gridvals = [xrange[0] + (dx / 2) + i * dx for i in range(ngrids)]

# set grid location
ax.set_yticks(gridvals, minor=False)
ax.set_xticks(gridvals, minor=False)

# set tick labels (to be from 1 to 7)
ax.set_xticklabels([f"{i}" for i in range(1, ngrids + 1)])
ax.set_yticklabels([f"{i}" for i in range(1, ngrids + 1)])

# turn grid on
ax.yaxis.grid(True, which="major")
ax.xaxis.grid(True, which="major")

To use the Blues color map, see the example here.


text:
Q: How to take input for all the elements of a 2d string at one shot? I want to store data in a 2d string. The conventional way would be :
char arr[20][20];
int i;
int size;
scanf("%d",&size);
for(i=0;i<size;i++)
 scanf("%s", arr[i]);

This way I would have input:
Hey
I
Am
New
Here

I want to have input as : Hey I am new here
and the array should have : a[20][20]={"Hey","I","am","new","here"}

A: The most elegant way of achieving this will be,

*

*Read the input using fgets().

*Tokenize using strtok()

*Store the tokens in the array elements, after validity checking.

This way, you have many advantages, like

*

*If at all using a fixed sized-array, you can  get rid of the issue for a separate user input for size. You can only keep on tokenizing the whole input till the array elements are there.

*Perform the validity checking of the input values (using strlen(), maybe)

*You can have the flexibility of not having a pre-determined sized array and using dynamic-memory allocation, you can allocate and resize the array, based on the number (and size) of inputs, (if you want).

A: It doesnot matter for scanf() whether you use '\n'(keyboard key-enter) or spaces to separate the input it will work the same way.The standard defined is that any whitespace can separate ino
That is,if you take input as-
Hey
I
Am
New
Here

or as-
 Hey I am new here

it will always store them as {"Hey","I","am","new","here"}


text:
Q: Type or namespace not found hello i am doing a assignment and the program i am using is visual studio 2012 the lab i am getting an error in my behind code in .cs file the error it is giving me is Line 20 and the compilation error message says
The type or namespace name 'Player' could not be found (are you missing a using directive or an assembly reference?).

Please help me
Line 18:     protected void addPlayer(String name, int jersey, String team){
Line 19:
Line 20:         Player player = new Player(name, jersey);
Line 21:
Line 22:         if ( String.Equals(team, "team 1", StringComparison.OrdinalIgnoreCase))

my whole code is
public partial class _default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void addPlayer(String name, int jersey, String team){

        player = new player(name, jersey);

        if ( String.Equals(team, "team 1", StringComparison.OrdinalIgnoreCase))
            listTeam1.Items.Add(player.getName() + "-" + player.getJersey());
        else if (String.Equals(team, "team 2", StringComparison.OrdinalIgnoreCase))
            listTeam2.Items.Add(player.getName() + "-" + player.getJersey());
    }

    protected int numPlayers(String team)
    {
        if (String.Equals(team, "team 1", StringComparison.OrdinalIgnoreCase))
            return listTeam1.Items.Count;
        else if (String.Equals(team, "team 2", StringComparison.OrdinalIgnoreCase))
            return listTeam2.Items.Count;
        else
            return 0;
    }

    protected void buttonLeft_Click(object sender, EventArgs e)
    {
        String addedItem = listTeam2.SelectedItem.Text;

        listTeam2.Items.RemoveAt(listTeam2.SelectedIndex);
        listTeam1.Items.Add(addedItem);

    }

    protected void buttonRight_Click(object sender, EventArgs e)
    {
        String addedItem = listTeam1.SelectedItem.Text;

        listTeam1.Items.RemoveAt(listTeam1.SelectedIndex);
        listTeam2.Items.Add(addedItem);

    }

    protected void buttonAdd_Click(object sender, EventArgs e)
    {
        addPlayer(tbName.Text, int.Parse(tbJersey.Text), radioTeam.SelectedItem.Text);

        tbJersey.Text = "";
        tbName.Text = "";
    }
}

A: When you get this error, it means exactly what it says. It doesn't know what player is, and therefore it's probably in another namespace. You need a using directive that imports the namespace. If Player is in another assembly, you need to add a reference to that assembly.


text:
Q: How to get CMPedometer data in Step by Step count? I'm currently working in an Healthcare Application, which requires to track user step count as they walk holding their phone. I have made use of CoreMotion framework and CMPedometer to track step count and it works fine. However, the callback function won't call for every step count. It clubs all data and returns the step count as 10 Steps (for example) on the whole. To be specific,
startUpdates(from start: Date,
      withHandler handler: @escaping CMPedometerHandler)
is not getting called for every step count (for stepcount 1, stepcount 2, etc). It clubs the data and gets called only once by adding the total step count.
Is there a way to call the method for every walking step?


text:
Q: Generator does not use JDK8+ Optional if configured accordingly Currently I'm using an OpenAPI model (3.0.2) defining some end point with data furthermore I have defined in the open API model something like this:
 XYZ:
   type: object
   properties:
     id:
       type: string
       nullable: true

The issue is now that based on the openapi-generator-maven-plugin (version 6.4.0) the configuration looks like this

*

*Usage Spring Boot 3.0.2

*JDK17

<plugins>
  <plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>6.4.0</version>
    <executions>
      <execution>
        <goals>
          <goal>generate</goal>
        </goals>
        <configuration>
          <inputSpec>${project.basedir}/xyz.yaml</inputSpec>
          <generatorName>spring</generatorName>
          <generateApiTests>false</generateApiTests>
          <generateModelTests>false</generateModelTests>
          <generateModels>true</generateModels>
          <generateApiDocumentation>false</generateApiDocumentation>
          <generateApis>false</generateApis>
          <configOptions>
            <skipDefaultInterface>true</skipDefaultInterface>
            <useSwaggerUI>false</useSwaggerUI>
            <apiPackage>package.api</apiPackage>
            <modelPackage>package.model</modelPackage>
            <library>spring-boot</library>
            <requestMappingMode>none</requestMappingMode>
            <documentationProvider>none</documentationProvider>
            <useJakartaEe>true</useJakartaEe>
            <useOptional>true</useOptional>
            <useSpringBoot3>true</useSpringBoot3>
            <useSpringController>false</useSpringController>
            <hideGenerationTimestamp>true</hideGenerationTimestamp>
            <openApiNullable>false</openApiNullable>
            <delegatePattern>false</delegatePattern>
            <interfaceOnly>false</interfaceOnly>
          </configOptions>
        </configuration>
      </execution>
    </executions>
  </plugin>
</plugins>

Currently the problem is that the generator does not generate an Optional (of the JDK existing since JDK8) for the above id in the code....
private String id;

public String getId() {
  return id;
}

If I use the configuration like this instead:
<useOptional>false</useOptional>

<openApiNullable>true</openApiNullable>

This will produce the code like this:
@JsonProperty("id")
private JsonNullable<String> id = JsonNullable.undefined();

public JsonNullable<String> getId() {
  return id;
}

This will imply to use a supplemental dependency in the project org.openapitools:jackson-databind-nullable which just recreates the Optional code of the JDK8+ ...
Does someone has a hint what I'm doing wrong?

A: The Optional isn't setup to be used in the pojo.  If you examine the api.mustache template, you will see the following line in the imports
{{#useOptional}}
import java.util.Optional;
{{/useOptional}}

This implies that the useOptional tag is available to all of our templates.  Additionally, further down in the api.mustache template, you can see the {>optionalDataType}} being used.  This tells the template to insert the OptionalDataType template at this point.  The OptionalDataType.mustache checks if useOptional is true, and if it is, then it wraps the dataType in an Optional.  If it is false, then it returns the dataType directly.
We can use this information to update the pojo.mustache to allow for Optional.
First, you will need to add the import to model.mustache.  That's easy enough.  Copy the above import to the model.mustache.  Done.
Second, update the pojo.mustache to allow for useOptional.  The updates need to take place in four locations.  The field declaration, the getter,
the setter, and the builder.
For the field declaration, there are two locations where the field is declared, one, if the field is a container, and one where it isn't.  The below code is for if it isn't a container, but the same change can be made for if it is as well.
add this between the {{^useContainer}}{{/useContainer}} tags:
  {{#useOptional}}
      private {{>optionalDataType}} {{name}};
  {{/useOptional}}

for the fluent setter getter, update the template with this
  {{#useOptional}}
      public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) {
          this.{{name}} = Optional.of({{name}});
      return this;
      }
  {{/useOptional}}
  {{^useOptional}}
  public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) {
    {{#openApiNullable}}
    this.{{name}} = {{#isNullable}}JsonNullable.of({{name}}){{/isNullable}}{{^isNullable}}{{name}}{{/isNullable}};
    {{/openApiNullable}}
    {{^openApiNullable}}
    this.{{name}} = {{name}};
    {{/openApiNullable}}
    return this;
  }
  {{/useOptional}}

For the getter, update as follows:
  {{#useOptional}}
  public {{>optionalDataType}} {{getter}}() {
    return {{name}};
  }
  {{/useOptional}}
  {{^useOptional}}
      public {{>nullableDataType}} {{getter}}() {
      return {{name}};
      }
  {{/useOptional}}

and for the setter, update with this
  {{#useOptional}}
  public void {{setter}}({{>optionalDataType}} {{name}}) {
    this.{{name}} = {{name}};
  }
  {{/useOptional}}
  {{^useOptional}}
  public void {{setter}}({{>nullableDataType}} {{name}}) {
    this.{{name}} = {{name}};
  }
  {{/useOptional}}

If you are making optional collections or other things, then you will need to update those to check useOptional as well, but this should get you started.
Also, this is customizable as you want.  You can have the setter just use the dataType and create an optional of the item, or you can have it as I have written it.  Same with the fluent setter.


text:
Q: "Undefined control sequence. \file_get:nnN" error while compiling markdown file to pdf using pandoc and xelatex I am trying to compile a Markdown file to PDF using pandoc and xelatex.
The command I employed is like this:
pandoc --pdf-engine=xelatex pantest.md -o pantest.pdf

The error information comes as follows:
Error producing PDF.
! Undefined control sequence.
l.931   \file_get:nnN

The markdown file I put into test is quite simple:
abcdefg

It does not contain any CJK characters.
I am using Windows 10, pandoc 2.7 and MikTex 2.9.

Following debugging steps suggested by @mb21 in the comment section, the error information seems to have relation with the "unicode-math". Here is the new error I have now:
command used:
pandoc pantest.md -s -o pantest.tex
xelatex pantest.tex

Error information generated:
l.931   \file_get:nnN
                      {unicode-math-table.tex} {} \l__um_mathtable_tl

'pdflatex pantest.tex' works fine.

A: I think you need to update your LaTeX packages in MiKTeX, as confirmed by several other users here. Alternatively, you could try TinyTeX.


text:
Q: How can i submit multi filed group in flask and store into database Here is my form images

Now i want have function when this form submit i store value in but how can i store value for those fiels genrating dynamicly using jquery
Here is form code to example for dynamic filesds

                        Select Category
                        <select class="form-control" name="question[0].challengecat" data-fv-field="question[0].challengecat">
                                <option value="">None</option>

                                    <option value="nature">Nature</option>

                                    <option value="health">Health</option>

                        </select>
                        Select Question Category
                    The Category is required

                                Percentage Question
                                <input type="text" placeholder="Percentage Question" class="form-control" name="question[0].percentage_question" id="percentage_question" data-fv-field="question[0].percentage_question">
                                Percentage question belongs to category
                    The Question percentage is required

                        <button class="btn btn-default addButton" type="button"></button>

                    Select Category
                        <select class="form-control" name="question[1].challengecat" data-fv-field="question[1].challengecat">
                                <option value="">None</option>

                                    <option value="nature">Nature</option>

                                    <option value="health">Health</option>

                        </select>
                        Select Question Category
                The Category is required

                    Percentage Question
                                <input type="text" placeholder="Percentage Question" class="form-control" name="question[1].percentage_question" id="percentage_question" data-fv-field="question[1].percentage_question">
                                Percentage question belongs to category
                The Question percentage is required

                <button class="btn btn-default removeButton" type="button"></button>

                    Select Category
                        <select class="form-control" name="question[2].challengecat" data-fv-field="question[2].challengecat">
                                <option value="">None</option>

                                    <option value="nature">Nature</option>

                                    <option value="health">Health</option>

                        </select>
                        Select Question Category
                The Category is required

                    Percentage Question
                                <input type="text" placeholder="Percentage Question" class="form-control" name="question[2].percentage_question" id="percentage_question" data-fv-field="question[2].percentage_question">
                                Percentage question belongs to category
                The Question percentage is required

                <button class="btn btn-default removeButton" type="button"></button>

So how can i save these dynamic generated field in variable using for loop or another way
Thanks
CSR

A: You can use element.getElementsByTagName() JavaScript method to get all form elements and their values. For example:

        Attribute1
        <input id="attribute1" type="text">

        Attribute2
        <input id="attribute2" type="text">

        <input type="button" value="Send" onclick="putRequest()">

It will send PUT request to /some/test/url with request body: attribute1=somevalue&attribute2=anothervalue.
On the server side you can get all the attributes from flask.request.form dictionary:
@app.route('/some/test/url')
def some_test_url():
  for attr_name, attr_value in request.form.iteritems():
    print attr_name, attr_value


text:
Q: for, meaning "cause or reason" here? Consider:

Sometimes pensions are adjusted for inflation. This is known as indexation.
It is the capital that is adjusted for risk.
Under the comprehensive approach, the exposure is adjusted for possible increases and the collateral is adjusted for possible decreases in value.

I think "for" here fits the definition (used to show a reason or cause) as in "I couldn't speak for laughing".
Am I right? Can I replace "for" with "according to" or "as per" here?

A: This use of for is peculiar to specific verbs signifying quantitative change, such as adjust, reduce, increase, modify, alter. It could be paraphrased as to account for, in proportion to, to reflect and indicates the factor which determines the degree of change.

Pensions are adjusted in proportion to inflation.
  Capital is adjusted to account for risk.
  Exposure is adjusted to reflect possible increases, and collateral is adjusted to reflect possible decreases.

According to is a marginally acceptable paraphrase, but is better reserved to designating a source or conformity to an authority.  As per is common in Indian English, but I would not use it with an English or American audience. It has never been common in Anglo usage outside of business and commercial law.
This use is only distantly analogous to I couldn't speak for laughing. As a rule I think it is a mistake to think of prepositions as having this or that  general significance which can be extended from one situation to another. Treat adjust for as one of a set of related 'phrasal verbs'—idiomatic expressions of the form changeVERB for.


text:
Q: jQuery on click using .before() i have this method, that does some ajax and with the result makes a new div before a div and then inserts the ajax response in it. The problem i have is while using on('click') my second click appends a new div before the previously created div(what i want) but also creates another div after(not what i want) that is exactly the same.
AJAX/jQuery:
$(document).on('click', '.ajaxcommentbutton1', function() {
var currentDiv, pageValue, newPage, newPageid;
currentDiv = $(this).attr('group');
pageValue = parseFloat($(this).attr('data'));
newPage = pageValue + 1;
newPageid =  '.' + newPage;

$.ajax({url:"comments.php",
       type:'POST',
   dataType:'text',
       data: {id: currentDiv,
              page: newPage},
    success:function(result){
        $('div[data="' + currentDiv + '"] .commentsContainer > div').before("
&nbsp
");
        $('div[data="' + currentDiv + '"] ' + newPageid).html(result);
        $('button[group="' + currentDiv + '"]').attr('data', newPage);
        $('button[group="' + currentDiv + '"]').off();
   }});
});

HTML Result of first click:

stuff in here

stuff in here

HTML Result of second click (BAD ONE):

stuff in here

stuff in here

stuff in here

stuff in here

A: Because $('div[data="' + currentDiv + '"] .commentsContainer > div') matches every
 under your container, and .before() will add your AJAX content into every matched
, duplicating your AJAX content.
i.e. in the second click, the new element is inserted into both
stuff in here
 and
stuff in here

Try replace it with $('div[data="' + currentDiv + '"] .commentsContainer > div:first-child') to match only the first child of all the
s, with the :first-child selector


text:
Q: WPF Performance Suite throws BadImageFormatException I need to profile my WPF 4.0 application. When I try to open it in WPF Performance Suite 4.0 (from Windows SDK 7.1) it throws a BadImageFormatException:

It complains about a newer runtime, so I ran corflags on my exe to check the runtime version. It says:
Version   : v4.0.30319
CLR Header: 2.5
PE        : PE32
CorFlags  : 1
ILONLY    : 1
32BIT     : 0
Signed    : 0

What's wrong? Why can't I open this WPF application in the profiler?
UPDATE
Tried JeffRSon's suggestion which produced another exception:
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.Assembly.GetTypes()
   at Microsoft.WpfPerformance.ToolAssembly..ctor(Assembly assembly)
   at Microsoft.WpfPerformance.Controls.AddToolDialog.ScanAssembly(String filename)
   at Microsoft.WpfPerformance.Controls.AddToolDialog.ScanAssembly()

A: Create a file called WpfPerf_managed.exe.config in C:\Program Files\Microsoft Windows Performance Toolkit\WPF Performance Suite or wherever WPF Performance Suite is installed with the following content:
<?xml version="1.0"?>
<configuration>
   <startup useLegacyV2RuntimeActivationPolicy="true">
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
   </startup>
</configuration>

This enables side-by-side runtimes in one process.
Restart WPF Performance Suite and load your assembly.


text:
Q: C# - Fill Listview in a different form - VS2015 I have 2 forms. Form 1 which shows a ListView and Form 2 a button called button1.
What I'm trying to do is when the button on form 2 is clicked. I want it to fill the Listview on form1.
The listview has 3 columns;
Flavour
Quantity
Sub-Total
When the button1 is pressed, it should show Vanilla, 1, £1.00 in the listview on form1.
I'm able to do this if the listview is on the same form as the button, but not if it's on different forms.
Form1
public partial class form1: Form
{
    public form1()
    {
        InitializeComponent();
    }

Form2
public partial class form2: Form
{
    public form2()
    {
        InitializeComponent();
    }

private void button1_Click(object sender, EventArgs e)
    {
        ListViewItem lvi = new ListViewItem("Vanilla");
        lvi.SubItems.Add("1");
        lvi.SubItems.Add("£1.00");
        listView1.Items.Add(lvi);
    }

A: Create a reference of form1 in form2 like this:
class Program {
    static void Main() {
        var form1 = new Form1();
        var form2 = new Form2(form1);
    }
}

public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void DoStuff(ListViewItem lvi) {
        // TODO: Stuff
    }
}

public partial class Form2: Form
{
    private Form1 _form1;

    public form2(Form1 form1)
    {
        InitializeComponent();
        _form1 = form1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ListViewItem lvi = new ListViewItem("Vanilla");
        lvi.SubItems.Add("1");
        lvi.SubItems.Add("£1.00");
        listView1.Items.Add(lvi);

        _form1.DoStuff(lvi);
    }
}


text:
Q: Intel 7260 does not manually set frequency in 15.10 as it did in 14.04 I have been a Ubuntu user for some time and have come across a problem with using Ubuntu 15.10 with an Intel 7260 Wi-Fi chip for packet captures. I am unable to set the frequency in 15.10 as I have been in older versions of Ubuntu (14.04):
sudo ifconfig wlp3s0 down
sudo iwconfig wlp3s0 mode monitor
sudo ifconfig wlp3s0 up
sudo ifconfig wlp3s0 promisc
sudo iw dev wlp3s0 set freq 2412

none of the commands give me an error but the frequency is not applied:
eth0      no wireless extensions.

lo        no wireless extensions.

wlp3s0    IEEE 802.11abgn  Mode:Monitor  Tx-Power=0 dBm
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:off

With a 14.04 partition on the same machine everything works fine:
eth0      no wireless extensions.

lo        no wireless extensions.

wlp3s0    IEEE 802.11abgn  Mode:Monitor  Frequency:2.412 GHz Tx-Power=0 dBm
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:on

I have checked and all of the drivers are the same but the firmware is different.
Does anybody have any ideas?


text:
Q: Hillshade is not showing relief in ArcMap
When I use the hillshade tool this is what the map looks like. The shaded relief is not showing what it should.
How do I fix this?

A: This is caused when the source DEM is in a geographic coordinate system rather than a projected coordinate system. The solution is to project the source DEM to a projected coordinate system (e.g. UTM) and rerun the hillshade.


text:
Q: Fastcgi error with apache2 The guide i followed: http://www.howtoforge.com/using-php5-fpm-with-apache2-on-ubuntu-11.10-p2
The error I am getting:
    root@server:/etc/apache2/sites-enabled# /etc/init.d/apache2 restart
WARNING: MaxClients (10) must be at least as large
 as ThreadsPerChild (25). Automatically
 increasing MaxClients to 25.
Syntax error on line 45 of /etc/apache2/sites-enabled/mysite.net:
FastCgiExternalServer: redefinition of previously defined class "/usr/lib/cgi-bin/php5-fcgi"
Action 'configtest' failed.
The Apache error log may have more information.
   ...fail!

The offending line 45:
FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /tmp/php5-fpm.sock -pass-header Authorization

How can I fix this?

A: Its likely that you've already defined /usr/lib/cgi-bin/php5-fcgi somewhere else.  This can only be defined once, and you probably want this in your /etc/apache2/sites/default directory as the instructions indicate.  You can see if you're defining it elsewhere by running:
grep -RIs "FastCgiExternalServer" /etc/apache2


text:
Q: Why 32-bit processor can only address 4GiB of memory, even with large word size? Until now I thought that a 32-bit processor can use 4 GiB of memory because 232 is 4 GiB, but this approach means processor have word size = 1 byte. So a process with 32-bit program counter can address 232 different memory words and hence we have 4 GiB.
But if a processor has word size larger than 1 byte, which is the case with most of processors now days I believe (My understanding is that word size is equal to the width of data bus, so a processor with 64-bit data bus must have a word size = 8 bytes).
Now same processor with 32 bit Program counter can address 2^32 different memory words, but in this case word size is 8 bytes hence it can address more memory which contradicts with 4 GiB thing, so what is wrong in my argument ?

A: CPU (at least x86 family 32-bit) must be able to access any byte/word/dword in 4GB space. So an instruction is encoded such a way that target word size and memory address (usually) belong to different bit-fields. So it doesn't matter whether CPU accesses byte or dword, but the encoded memory address must be the same.
Note that 32-bit OS and x86 CPU technically is able to acccess more than 4GB address space using PAE mode. But it is not supported by, say, the current Windows OS family (except Server editions). Some versions of WinXP, as well as Linux and other 32-bit OS can address 64GB of memory on x86 CPU.
Also, usually OS reserves some part of virtual address space (for OS kernel, Video memory etc.), so user programs may use, say, no more than 3 GB of RAM of the 4GB an OS can address within each process.

A: Your premise is incorrect. 32-bit architectures can address more than 4GB of memory, just like most (if not all) 8-bit microcontrollers can use more than 256 bytes of memory. Indeed a 32-bit program counter can address 232 different memory locations, but word-addressable memory is only used in architectures for very special purposes like DSPs or antique architectures in the past. Modern architectures for general computing all use byte-addressable memory
See Why byte-addressable memory and not 4-byte-addressable memory?

Even in 32-bit byte-addressable architectures there are many ways to access more than 4GB of memory. For example 64-bit JVM can address 32GB of memory with 32-bit pointer using compressed Oops. See the Trick behind JVM's compressed Oops
32-bit x86 CPUs can also address 64GB (or more in later versions) of memory with PAE. It basically adds a another level of indirection in the TLB with a few more bits in the address. That allows the whole system to access more than 4GB of memory. However the pointers in applications are still 32-bit long so each process is still limited to 4GB at most. The analog on ARM is LPAE.
The 4GB address space of each process is often split into user and kernel space (before Meltdown), hence limited the user memory even more. There are several ways to workaround this

*

*Spawning multiple processes, which is used in Adobe Premiere CS4

*Mapping the needed part of memory into the current address space, like Address Windowing Extensions on Windows

*...


text:
Q: Fatal error: Call to undefined function ssh2_connect() in C:\Apache\htdocs\test\testSsh2_03.php on line 13 Running PHP 5.6.5
I have installed "libssh2.dll" under c:\PHP
I have installed "php_ssh2.dll" and "php_ssh2.pdb" in C:\PHP\ext in both flavours, 64 and 32, but none work.
I have also tried "phpseclib", and I get another error. I have researched it on the web for a couple of days now and most of the solutions are old, none have worked for me.
Here is the code:
<?php
   // =================================================
   // testscp_02.php
   // =================================================
   $hostname      = 'myconnection.com';
   $username      = 'my_userName';
   $password      = 'MyPassword';

   $sourceFile    = 'TestScp.php';
   $targetFile    = '/home/myDir/TestScp.php';

   $connection    = ssh2_connect($hostname, 22);
   echo '
[' . $connection . ']
';
   ssh2_auth_password($connection, $username, $password)
   ssh2_scp_send($connection, 'C:/Apache/htdocs/test/testscp_02.php',   '/home/myDir/TestScp.php', 0666);
 ?>

I have tried many things, I cannot get PHP to see SSH2 as pointed out by some people that it should happens when I install the DLL as stated at the beginning of this post.

A: I finally found the DLLs for PHP 5.6 and it is working now.
The link is: https://www.apachelounge.com/viewtopic.php?t=6123
I hope this helps someone else.


text:
Q: Combine duplicate values by date in JavaScript array Good afternoon, I need some help to combine the data of this example array taking the position [0] of the date and the position [1] of the name (AA, BB, CC...)

//Origin Array
[
['10/08/2022',  'AA',   '08:00',    '12:00',    '',       '17:00'],
['10/08/2022',  'BB',   '08:01',    '13:15',    '14:16',    '17:01'],
['10/08/2022',  'AA',   ''     ,    ''     ,  '13:00',  ''     ],
['10/08/2022',  'CC',   '09:00',    '11:30',    '12:30',    '18:00']
]

//Result Array
[
['10/08/2022',  'AA',   '08:00',    '12:00',    '13:00',    '17:00'],
['10/08/2022',  'BB',   '08:01',    '13:15',    '14:16',    '17:01'],
['10/08/2022',  'CC',   '09:00',    '11:30',    '12:30',    '18:00']
]

A: I'll give you a brute force answer.  As others have noted, functions exist to improve it.
First I'll check if the date/name pair already exists.  If not, just add the data.  If it did, then update the blanks.
originalArray = <your data>
resultArray = []

function findDateNamePair(resultArray, aDate, aName) {
    // return index if resultArray[index][0] = aDate and resultArray[index][1] = aName
    // return -1 if not found

    for (var i=0; i < resultArray.length; i++) {
        if (resultArray[i][0] == aDate && resultArray[i][1] == aName) {
            return i;
        }
    }
    return -1;
}

for (var i=0; i < originalArray.length; i++) {
    const thisEntry = originalArray[i];
    const existingIndex = findDateNamePair(resultArray, thisEntry[0], thisEntry[1]);
    if (existingIndex == -1) {
        resultArray.push(thisEntry);
    }
    else {
        for (var j=2; j<=5; j++) {
            if (resultArray[existingIndex][j] == '') {
                resultArray[existingIndex][j] = thisEntry[j];
            }
        }
    }
}

A: You can use reduce method to group the items, and checkValue will combine the filled values only, and Object.values to return it to a multi diminution array after object reduction.

const data = [
['10/08/2022',  'AA',   '08:00',    '12:00',    '',       '17:00'],
['10/08/2022',  'BB',   '08:01',    '13:15',    '14:16',    '17:01'],
['10/08/2022',  'AA',   ''     ,    ''     ,  '13:00',  ''     ],
['10/08/2022',  'CC',   '09:00',    '11:30',    '12:30',    '18:00']
]

const checkValue = (oldItem, newItem) =>
    oldItem ? oldItem.map((item, i) => item || newItem[i]) : newItem

const result = Object.values(data.reduce((acc, item) =>
    ({ ...acc, [item[1]]: checkValue(acc[item[1]], item) }),
{}))

console.log(result)


text:
Q: If row contains specified value then copy ID to first column If a row contains the value "car" I am trying to copy the contents of the ID cell to A1.
For example, if row D12 contains "car" I want to copy the contents of cell B12 to A12.
Currently this is my code:
Dim lastRow As Long
Dim cell As Range

lastRow = Range("A" & Rows.Count).End(xlUp).Row + 1

For Each cell In Range("D2:D" & lastRow)
If InStr(1, cell.Value, "CAR") <> 0 Then
            cell.Offset(0, -3).Value = "test"
    End If
Next

So currently the code find's the rows that has "car" but populates the cell with the value "test". I am struggling with how to reference/copy the cell over.
This is because the first column of my worksheet requires a concatenation of values as the ID and I do not want to apply it to this string.
Thanks for any advice/help!

A: The reason you get "test" as inserted in to column A is, that is what the code is specifying.  The code needs to be changed to reflect what is wanted.
If the contents of column B is wanted, then replace the string "test" with:
cell.Offset(0, -2).Value

So the whole line would read:
cell.Offset(0, -3).Value = cell.Offset(0, -2).Value

Since you are iterating through column D, cell is located in column D.  The offset part is saying, "Move over three places from column D and place the value from two columns over".  Or column A on the same row, which is 3 cells to the left from the current cell in column D and place the value from Column B on the same row, which is 2 cells to the left of the current cell in column D.

A: Another quick way would be to use the autifilter.
For example:
Sub Button1_Click()
    Dim lastRow As Long
    Dim rng1 As Range, rng2 As Range

    Application.ScreenUpdating = 0
    lastRow = Range("D" & Rows.Count).End(xlUp).Row + 1

    Columns("D:D").AutoFilter Field:=1, Criteria1:="=*Car*"

    Set rng1 = Range("A2:A" & lastRow).SpecialCells(xlCellTypeVisible)
    Set rng2 = Range("B2:B" & lastRow).SpecialCells(xlCellTypeVisible)

    rng1.Value = rng2.Value

    ActiveSheet.AutoFilterMode = 0

End Sub


text:
Q: Dual Display Settings lost after blank screen / lock I upgraded to Ubuntu 20.04 recently and have just started having this problem.
I have a dual-monitor setup with two different monitor manufacturers. Ubuntu detects the monitor I use as my 'primary' as #2 (if this matters). In Display Settings, I have set this as my 'Primary Display' and moved it to the left of display #1.
After the computer switches to a lock / blank screen, my primary monitor goes to 'sleep'. When I return to the computer, this monitor is not 'woken' - the secondary monitor turns on and allows me to login, but I have to go and change the display settings again to turn on the primary monitor and set the correct layout.
This started happening after the upgrade and worked fine before. Has anyone else seen this - is there a fix?

A: I had the same problem and to solve it I have edited the file
~/.config/monitors.xml

There I had 4 logicalmonitor configurations, instead of only 2.


text:
Q: Controlling the ShareThis javascript window opens I have just started using ShareThis Widget to help handle social media integration with one of our sites. While the functionality is great, I feel I lose a lot of the capabilities I have if I were to code each item by hand, such as the ability to control the size of the windows opened by clicking a 'share' functionality.
While their site shows basic functions you can add to the buttons (url, etc) I am looking to customize the feel such that when a button is clicked, I can control the size of that window or even possibly open in an existing colorbox snippet.
Has anybody had luck with this before? When I try to control via javascript function it just seems to get overwritten or ignored.

A: You'd need to unbind their events and handle them all yourself. It probably isn't a good idea, as your code will be at the mercy of their implementation.

A: I am not sure if your question is resolved, but you will need to add as following inside JS.
popup: 'true'

The same is on their Support Page


text:
Q: Subtract the date from current date javascript I want to subtract the pastDate with current date and check if the different is greater than 7 days. I am trying to do with momentjs but the subtract doesn't seems working my way.
pastDate= "2018-03-09 22:53:19";
dateFrom = moment(Date.now() - pastDate).format('YYYY-MM-DD HH:mm:ss');

if(dateFrom >= 7 ){
  console.log("Expiry Date");
}

Please help me with correct syntax.


text:
Q: Thunar does not automount USB drives anymore Automounting USB drives used to work fine. I do not know what I changed to make it stop working.
The user account still has all groups configured, the media manager still shows the automount enabled marks.
I now get "Not authorized to perform operation." when trying to open the drive. Thunar still shows the drawer. "Send to" menu also does not work.
I can mount as root by hand but I want to repair the old behavior.
I have issues with USB sticks will all sorts of file systems, none are mounting automatic (FAT32, XFS, NTFS which all did work before)
I am using Xubuntu 18.04 and also tried updating all packages.


text:
Q: Converting hex color code, to rgba and fetching the red value If I have a color code in sass in a hexadecimal format #aaaaaa, is there any way to convert this to an RGB format, and get only the red value number with a function?
An example on what I would like to achieve:
@function getRedValue($color) {
     // convert $color which will be provided in hexadecimal format, to rgba
     // return the red value of the color number
}

A: There are some SASS default color functions you could use.
Please check red(), green() and blue().


text:
Q: Django wizard interaction between forms I need to make a two form wizard. In one form I need to gather some data, process that and prepopulate a field in the second form. What's the best/easiest way to do it?

A: Add get_form_initial() method in your wizard class, for the 2nd step, use data from first step using get_cleaned_data_for_step().
Something like:
class myWizardView:

    def get_form_initial(self, step):
        if int(step) == 1:
            # get cleaned data from prev step
            return self.get_cleaned_data_for_step(str(int(step) - 1))

You may want to manipulate the dict to have appropriate attribute names etc.
More reference at Form Wizard


text:
Q: jq: setpaths with regex on paths, how to handle paths that end with an integer which produce an error? I have the following object:
{
  "domainId": "hidden",
  "lastUsed": "Thu Oct 04 2018",
  "lastUsedTimestamp": 1538673002460,
  "users": [
    {
      "userId": "hidden",
      "lastUsedTimestamp": 1538673002460
    },
    {
      "userId": "hidden",
      "lastUsedTimestamp": 1536087726701
    },
    {
      "userId": "hidden",
      "lastUsedTimestamp": 1536086675399
    },
    {
      "userId": "hidden",
      "lastUsedTimestamp": 1536182646984
    }
  ]
}

I want to convert all lastUsedTimestamp values to a date. This works with:
reduce (paths | select(.[-1] == "lastUsedTimestamp")) as $p
  (.;setpath($p; getpath($p) / 1000 | todate))

But what if I had other timestamp keys such as createdTimestamp or startTimestamp in other places of the object? For instance:
{
  "domainId": "hidden",
  "lastUsed": "Thu Oct 04 2018",
  "lastUsedTimestamp": 1538673002460,
  "users": [
    {
      "userId": "hidden",
      "lastUsedTimestamp": 1538673002460
    },
    {
      "userId": "hidden",
      "lastUsedTimestamp": 1536087726701
    },
    {
      "userId": "hidden",
      "lastUsedTimestamp": 1536086675399,
      "createdTimestamp": 1536086675399
    },
    {
      "userId": "hidden",
      "lastUsedTimestamp": 1536182646984,
      "startTimestamp": 1536182646984
    }
  ]
}

I tried
reduce (paths | select(.[-1] | endswith("Timestamp")) as $p
  (.;setpath($p; getpath($p) / 1000 | todate))

or an equivalent with test but paths that end with an integer make it fail.
How can I work around this?

A: To supress errors use ... ? operator, which is a shorthand for try .... For example:

reduce (paths|select(.[-1]|endswith("Timestamp")?)) as $p
(.; setpath($p; getpath($p)/1000|todate))

A: For this type of problem, walk/1 is often convenient:
def timestamps:
  with_entries(if .key | endswith("Timestamp")
               then .value |= (./1000 | todate) else . end);

walk( if type == "object" then timestamps else . end )

As a one-liner
If you want a one-liner:
walk( if type == "object" then with_entries(if .key | endswith("Timestamp") then .value |= (./1000 | todate) else . end) else . end)

If your jq allows the else . to be omitted, this becomes a bit more digestible:
walk(if type == "object" then with_entries(if .key | endswith("Timestamp") then .value |= (./1000 | todate) end) end)


text:
Q: Clustering Pentaho C.E. 5.x with Jackrabbit repository I'm trying to run several Pentaho BI CE server instances atop of a clustered PostgreSQL Database.
Pentaho Clustering guide on clustering(Cluster the Application Server) says that I should keep the contents of Jackrabbit per-node configurations the same

Your application nodes all need the same configurations and BA deployments installed already in order for clustering to work.

and then I only need to configure Jackrabbit's journal to specify unique node ids.
<Cluster id="Unique_ID ">
    <Journal class="org.apache.jackrabbit.core.journal.DatabaseJournal">
      <param name="revision" value="${rep.home}/revision.log"/>
      <param name="url" value="jdbc:postgresql://HOSTNAME:PORT/jackrabbit"/>
      <param name="driver" value="org.postgresql.Driver"/>
      <param name="user" value="jcr_user"/>
      <param name="password" value="password"/>
      <param name="databaseType" value="postgresql"/>
      <param name="janitorEnabled" value="true"/>
      <param name="janitorSleep" value="86400"/>
      <param name="janitorFirstRunHourOfDay" value="3"/>
    </Journal>
</Cluster>

Jackrabbit's guide on clustering however has more requirements(emphasis mine)

In order to use clustering, the following prerequisites must be met:

*

*Each cluster node must have its own repository configuration.

*A DataStore must always be shared between nodes, if used.

*The global FileSystem on the repository level must be shared (only the one that is on the same level as the data store; only in the
  repository.xml file).

*Each cluster node needs its own (private) workspace level and version FileSystem (only those within the workspace and versioning
  configuration; the ones in the repository.xml and workspace.xml file).

*Each cluster node needs its own (private) Search indexes.

*Every cluster node must be assigned a unique ID.

*A journal type must be chosen, either based on files or stored in a database.

*Each cluster node must use the same (shared) journal.

*The persistence managers must store their data in the same, globally accessible location

Does it mean that FileSystem inside 'Versioning' and 'Workspace' should have different prefixes per node or point to another(possibly non shared) place? This contradicts with the Pentaho documentation(Use PostgreSQL as Your Repository Database) where everything points to single database.

A:
Does it mean that FileSystem inside 'Versioning' and 'Workspace' should have different prefixes per node or point to another(possibly non shared) place?

If you use a shared database, then yes.

This contradicts with the Pentaho documentation(Use PostgreSQL as Your Repository Database) where everything points to single database.

Not necessarily, it depends on the definition of "same". If you use a local file system or local database, then the configuration is the same, as "Your application nodes all need the same configurations and BA deployments installed already in order for clustering to work."


text:
Q: WebSocket connection failed: One or more reserved bits are on: reserved1 = 0, reserved2 = 1, reserved3 = 1

I am trying to setup WebSockets in my Javascript (React) application using Socket.io.
When using the polling transport from the Socket.io client (v1.4.5), everything works fine.
But I would like to use actual and secure WebSockets (wss:// protocol)...
My server is a Debian 7 running Nginx v1.2.1 as a proxy for my virtual hosts, and my Node.js app (using Socket.io v1.4.5).
My domain name (api.tribeez.net) is set up via CloudFlare, which just announced full WebSocket support (including over SSL, i.e. wss://).
When I start my app in Chrome (v50.0), I see the WebSocket connection in the Network panel of Chrome (status pending).
But after one minute, the WebSocket disconnects (status 101 Switching Protocols) and the console throws me a confusing WebSocket connection to 'wss://api.tribeez.net/socket.io/?EIO=3&transport=websocket&t=LI3t1dh' failed: One or more reserved bits are on: reserved1 = 0, reserved2 = 1, reserved3 = 1
When turning on socket.io debugging, this is what I get:
Fri, 06 May 2016 02:23:37 GMT socket.io:server incoming connection with id L43EOXmwsqkgCMVJAAAD
Fri, 06 May 2016 02:23:37 GMT socket.io:client connecting to namespace /
Fri, 06 May 2016 02:23:37 GMT socket.io:namespace adding socket to nsp /
Fri, 06 May 2016 02:23:37 GMT socket.io:socket socket connected - writing packet
Fri, 06 May 2016 02:23:37 GMT socket.io:socket joining room /#L43EOXmwsqkgCMVJAAAD
Fri, 06 May 2016 02:23:37 GMT socket.io:client writing packet {"type":0,"nsp":"/"}
Fri, 06 May 2016 02:23:37 GMT socket.io-parser encoding packet {"type":0,"nsp":"/"}
Fri, 06 May 2016 02:23:37 GMT socket.io-parser encoded {"type":0,"nsp":"/"} as 0
Transport=websocket, query=/socket.io/?EIO=3&transport=websocket&t=LI3t1dh
Fri, 06 May 2016 02:23:37 GMT socket.io:socket joined room /#L43EOXmwsqkgCMVJAAAD
Fri, 06 May 2016 02:23:37 GMT socket.io:socket joining room tribe#1
Fri, 06 May 2016 02:23:37 GMT socket.io:socket joined room tribe#1
Fri, 06 May 2016 02:24:37 GMT socket.io:client client close with reason transport close
Fri, 06 May 2016 02:24:37 GMT socket.io:socket closing socket - reason transport close

And this is the Nginx log:
2016/05/06 04:24:37 [error] 28383#0: *549 upstream timed out (110: Connection timed out) while reading upstream, client: xxx.xxx.xxx.xxx, server: api.tribeez.net, request: "GET /socket.io/?EIO=3&transport=websocket&t=LI3t1dh HTTP/1.1", upstream: "http://127.0.0.1:3010/socket.io/?EIO=3&transport=websocket&t=LI3t1dh", host: "api.tribeez.net"

And my Nginx conf for this app:
http {
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }
}

server {
    server_name api.tribeez.net;
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:3010;
    }
    location /socket.io/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:3010;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}

Any idea why it closes? Could it be that I need to ping it regularly?

A: Found the answer at the bottom of an Nginx blogpost: I needed to upgrade my Nginx version to a 1.3.13+. I installed the 1.10 (latest stable) using the right Nginx Debian repository (see instructions), which fixed the issue.
Here is my browser output after setting localStorage.debug = '*':
socket.io-client:url parse https://api.tribeez.net +0ms
socket.io-client new io instance for https://api.tribeez.net +5ms
socket.io-client:manager readyState closed +2ms
socket.io-client:manager opening https://api.tribeez.net +1ms
engine.io-client:socket creating transport "polling" +2ms
engine.io-client:polling polling +2ms
engine.io-client:polling-xhr xhr poll +1ms
engine.io-client:polling-xhr xhr open GET: https://api.tribeez.net/socket.io/?EIO=3&transport=polling&t=LI4PaE9 +2ms
engine.io-client:polling-xhr xhr data null +2ms
engine.io-client:socket setting transport polling +1ms
socket.io-client:manager connect attempt will timeout after 20000 +3ms
socket.io-client:manager readyState opening +3ms
engine.io-client:polling polling got data ArrayBuffer +468ms
engine.io-client:socket socket receive: type "open", data "{"sid":"0BCyhfQm--8uOQYUAAAb","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}" +5ms
engine.io-client:socket socket open +1ms
socket.io-client:manager open +0ms
socket.io-client:manager cleanup +1ms
socket.io-client:socket transport is open - connecting +0ms
engine.io-client:socket starting upgrade probes +1ms
engine.io-client:socket probing transport "websocket" +1ms
engine.io-client:socket creating transport "websocket" +0ms
engine.io-client:polling polling +2ms
engine.io-client:polling-xhr xhr poll +0ms
engine.io-client:polling-xhr xhr open GET: https://api.tribeez.net/socket.io/?EIO=3&transport=polling&t=LI4PaLo&sid=0BCyhfQm--8uOQYUAAAb +1ms
engine.io-client:polling-xhr xhr data null +0ms
engine.io-client:polling polling got data ArrayBuffer +252ms
engine.io-client:socket socket receive: type "message", data "0" +1ms
socket.io-parser decoded 0 as {"type":0,"nsp":"/"} +0ms
engine.io-client:polling polling +2ms
engine.io-client:polling-xhr xhr poll +0ms
engine.io-client:polling-xhr xhr open GET: https://api.tribeez.net/socket.io/?EIO=3&transport=polling&t=LI4PaPo&sid=0BCyhfQm--8uOQYUAAAb +0ms
engine.io-client:polling-xhr xhr data null +1ms
engine.io-client:socket probe transport "websocket" opened +441ms
engine.io-client:socket probe transport "websocket" pong +252ms
engine.io-client:socket pausing current transport "polling" +1ms
engine.io-client:polling we are currently polling - waiting to pause +1ms
engine.io-client:polling polling got data ArrayBuffer +98ms
engine.io-client:socket socket receive: type "noop", data "undefined" +1ms
engine.io-client:polling pre-pause polling complete +0ms
engine.io-client:polling paused +1ms
engine.io-client:socket changing transport and sending upgrade packet +0ms
engine.io-client:socket setting transport websocket +0ms
engine.io-client:socket clearing existing transport polling +1ms
engine.io-client:polling ignoring poll - transport state "paused" +0ms

Socket.io seems to be opening a polling connection anyway, but pauses it to prefer the websocket once the latter is working (I suppose...)


text:
Q: Show that $\frac{d}{dx}\int_0^xf(x,y)dy = f(x,x) + \int_0^x \frac{\partial f}{\partial x}(x,y)dy$ Here is the answer link, but I don't see one thing. Why is $$\frac{d}{dx}G(x,x) = \frac{ \partial G}{\partial u}(x,x) + \frac{\partial G}{\partial v}(x,x)$$
The way I understand this is that $G$ is a function of $u$ and $v$ that in this case take values $u=x, v=x$, so for me it looks like $\frac{d}{dx}$ is derivative with respect to value, like for example writing $f(z) = z^2$ and then asking what is $\frac{df}{d1}f(1)$. Or is this just treating $u, v$ as $u(x) = x, v(x) = x$?

A: Claim:
Let $\phi(x),\psi(x)\in C^1([\alpha,\beta]), a\lt \phi(x)\lt \psi(x)\lt b$ on $[\alpha,\beta]$. Assume that $f(x,y),f_x(x,y)$ are continuous on $[\alpha,\beta]\times [a,b]$, then$$\frac{d}{dx}\int_{\phi(x)}^{\psi(x)}f(x,y)dy=\int_{\phi(x)}^{\psi(x)}f_x(x,y)dy+f(x,\psi(x))\psi'(x)-f(x,\phi(x))\phi'(x)$$
Proof:
Let $g(x)=G(x,\phi(x)=u,\psi(x)=v)=\int_{\phi(x)}^{\psi(x)}f(x,y)dy$, then $g'(x)=G_x+G_{u}\phi'(x)+G_{v}\psi'(x)$. By the first fundamental theorem of calculus, $G_{v}=f(x,\psi(x))$ and $G_{u}=-f(x,\phi(x))$. Since $f_x(x,y)$ is continuous, $G_x=\int_{\phi(x)}^{\psi(x)}f_x(x,y)dy$ (this may also be proven more rigorously using $\epsilon-\delta$ argument). Combine the three parts and we have $$g'(x)=G_x+G_{u}\phi'(x)+G_{v}\psi'(x)=\int_{\phi(x)}^{\psi(x)}f_x(x,y)dy+f(x,\psi(x))\psi'(x)-f(x,\phi(x))\phi'(x)$$
Hence proven. Your problem is then the special case $\phi(x)=0,\psi(x)=x$, so
$$\int_0^x f(x,y)dy=\int_0^x f_x(x,y)dy+f(x,x)(1)-f(x,0)(0)=\int_0^x f_x(x,y)dy+f(x,x)$$


text:
Q: print in a loop Python Windows I noticed something strange when using the Django shell on Windows. I tested different calls with a simple script which is :
for it in range(5):
    print(it)

When typing this script in a Python environment or a manage.py shell one, it works fine. But when I put this code in a file and execute it with python manage.py shell < myFile.py there's nothing which is displayed when I'm printing in loops, the output is "..." instead.
I overpassed this restriction by executing it in the build-in console from Eclipse but I'm pretty curious of the reasons why the output isn't well displayed when calling the script from an output file.
Does anyone knows what happened ?

A: Both worked fine
In addition, for those who are using Python 3+, execfile doesn't work anymore, replace
echo 'execfile("myFile.py")' | python manage.py shell

with
echo exec(open('MyFile.py').read()) | python manage.py shell

Thanks for both of you!

A: It works this way:
echo 'execfile("myFile.py")' | python manage.py shell

A: try this
echo "for i in range(5): print i" | python manage.py shell


text:
Q: Using Parse's JavaScript framework with Google Apps Script I would like to use the Parse framework directly in Google Apps Script and copied the following source code from Parse.com directly into my project.
However, it seems that there are some adjustments required to get this to work correctly. e.g. when running the following sample code...
function upload()
{
  Parse.initialize("wCxiu8kyyyyyyyyyyyyyyyyy", "bTxxxxx8bxxxxxxxxx");
  var TestObject = Parse.Object.extend("TestObjectJSSSSS");
  var testObject = new TestObject();
  testObject.save({foo: "bar"}, {
     success: function(object) {
     alert("yay! it worked");
  }
  });
}

… I get the error message TypeError: Cannot call method "getItem" of undefined.
which seems to relate to localStorage. I believe I should replace localStorage with a similar storage type available in Google Apps Script. Would that be possible and how would I need to adjust the Parse code?
What other adjustments would I need to get to the Parse framework to work in my Google Apps Script project?

A: I would suggest that using Parse REST API would be a far simpler solution and it is meant for such cases.


text:
Q: Word for an opening inside an island where water lies? What would be a word to name the opening of an island where a body of water (the ocean) enters into the land-mass?
I sketched an illustration of what I mean:

I know I have used a word to describe this before, but I have completely lost it.
Any suggestions would be greatly appreciated.

A: The word inlet is defined in this sense by Lexico as

a small arm of the sea, a lake or a river

bay is defined by the same dictionary as

a broad inlet of the sea where the land curves inward

So a bay is a broad inlet and an inlet is a narrow bay, exactly where an inlet becomes a bay is probably debatable.
Another term for an inlet can be cove which is

A small sheltered bay.

but a cove usually has cliffs and curving arms which mean that the body of the cove is wider than it's mouth.
A lagoon is different in that it is

A stretch of salt water separated from the sea by a low sandbank or coral reef.

From your comment it seems that you were looking for 'inlet'


text:
Q: Making python run on my webserver im getting a bit stuck regarding options for running python scripts on my server. From the research ive done so far, i can see i need to modify apache slightly to run python scripts, by using either mod_wsgi or mod_python. Two issues i have:
mod_python doesnt appear to be maintained anymore (last release, 2007)
mod_wsgi appears to require modification of my httpd.conf file on a per application basis.
What im wanting to know, is there a way of getting python scripts to run in the same way as php, i.e. just by going to index.py etc... or is it more involved than that?
At present im just trying to set it up on my xampp install.
Any help would be appreciated.

A: I would stick with mod_wsgi.  It seems more actively maintained.  There are good docs for it on the project page.  If you want mod_wsgi to handle your .py scripts, you can add something like:
AddHandler wsgi-script .py

In the appropriate context in Apache.  There are configuration instructions and installation instructions that should really help.

A: You can simply run Python scripts as CGI, if you really want - just add .py as a CGI handler in your Apache conf:
AddHandler cgi-script .cgi

Note that this is a very bad idea other than for very low-usage applications, as it is slow and inefficient. You really are much better off going with mod_wsgi.

A: One can do a once off configuration of mod_wsgi which then allows you to add applications without needing to go back and modify the configuration again. As someone else mentioned, this revolves around using AddHandler instead of WSGIScriptAlias. See:
http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines
BTW, you probably want to look at a higher level framework or library of WSGI components rather than work with raw WSGI. For example, see:
http://werkzeug.pocoo.org/
http://flask.pocoo.org/
There are lots of others referenced at:
http://www.wsgi.org/wsgi/Frameworks

A: I posted simple tutorial of how to install python for XAMPP on my blog. Let me know if you found it useful.


text:
Q: Python - iterable, not NoneType What does this mean ? TypeError: pyautogui.click() argument after * must be an iterable, not NoneType
error: pyautogui.click(*pos4)
My code:
repeat = 100

while repeat > 0:

    def retry(action, max_secs=120):
        start = datetime.now()
        res = None
        while (datetime.now() - start).total_seconds() < max_secs:
            res = action()
            if res: break
        return res

    pos4 = retry(lambda: pyautogui.locateCenterOnScreen('nextMatch.PNG'))
    pyautogui.click(*pos4)

    time.sleep(1)

    repeat -= 1

A: Not sure but see the changes :
repeat = 100

while repeat > 0:

    def retry(action, max_secs=120):
        start = datetime.now()
        res = None
        while (datetime.now() - start).total_seconds() < max_secs:
            res = action
            if res: break
        return res

    pos4 = retry(lambda: pyautogui.locateCenterOnScreen('nextMatch.PNG'))
    pyautogui.click(pos4)

    time.sleep(1)

    repeat -= 1


text:
Q: Wpf ListView Is it possible to order the group items differently from the group headers? I have a List View Control with grouping and sorting.
The group headers are Dates in descending order.
I am trying to find out how to order the grouped items under each group header in an ascending order, but cant figure out how to get it done or if it is even possible with ListView.
Here is the XAML I have so far.
Note: ScheduledItemSearchResults is an observable collection of ScheduleItems each item has a Title and a ScheduleDate property.
<Grid x:Name="TxScheduleItemResults"
              Grid.Column="1">
            <Grid.Resources>
                <CollectionViewSource Source="{Binding ScheduledItemSearchResults}" x:Key="scheduledItems">
                    <CollectionViewSource.SortDescriptions>
                        <scm:SortDescription PropertyName="Value.ScheduleDateTime" Direction="Descending"/>
                    </CollectionViewSource.SortDescriptions>
                    <CollectionViewSource.GroupDescriptions>
                        <dat:PropertyGroupDescription PropertyName="Value.ScheduleDateTime.Date" />
                    </CollectionViewSource.GroupDescriptions>
                </CollectionViewSource>
            </Grid.Resources>

            <ListView x:Name="ScheduledItemResultsList"
                      Style="{StaticResource TransparentListViewStyle}"
                      ItemContainerStyle="{StaticResource alternatingListViewItemStyle}"
                      AlternationCount="2"
                      ItemsSource="{Binding Source={StaticResource scheduledItems}}"
                      >

                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Scheduled Items"
                                        Width="{Binding ElementName=ScheduledItemResultsList, Path=ActualWidth}"
                                        >
                            <GridViewColumn.HeaderTemplate>
                                <DataTemplate>
                                    <TextBlock Style="{StaticResource ModuleGroupHeader}"
                                               Text="{Binding}"
                                               />
                                </DataTemplate>
                            </GridViewColumn.HeaderTemplate>
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBox Text="{Binding Value.Title}" Width="200"/>
                                        <TextBox Text="{Binding Value.ScheduleDateTime, StringFormat={}{0:HH:mm:ss}}" Width="120"/>
                                    </StackPanel>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
                <ListView.GroupStyle>
                    <GroupStyle>
                        <GroupStyle.ContainerStyle>
                            <Style TargetType="{x:Type GroupItem}">
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate>
                                            <Expander IsExpanded="True">
                                                <Expander.Header>
                                                    <StackPanel Orientation="Horizontal">
                                                        <TextBlock Text="{Binding  Path=Items[0].Value.ScheduleDateTime.Date, StringFormat={}{0:dd/MM/yyyy}}" FontWeight="Bold" Foreground="Gray" FontSize="22" VerticalAlignment="Bottom" />
                                                        <TextBlock Text="{Binding ItemCount}" FontSize="22" Foreground="Green" FontWeight="Bold" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
                                                        <TextBlock Text=" item(s)" FontSize="22" Foreground="Silver" FontStyle="Italic" VerticalAlignment="Bottom" />
                                                    </StackPanel>
                                                </Expander.Header>
                                                <ItemsPresenter />
                                            </Expander>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </GroupStyle.ContainerStyle>
                    </GroupStyle>
                </ListView.GroupStyle>
            </ListView>
        </Grid>

A: You can have several SortDescriptions elements in one CollectionViewSource:
 <CollectionViewSource Source="{Binding ScheduledItemSearchResults}" x:Key="scheduledItems">
                <CollectionViewSource.SortDescriptions>
                    <!--This will sort groups-->
                    <scm:SortDescription PropertyName="Value.ScheduleDateTime.Date" />
                    <!--This will items-->
                    <scm:SortDescription PropertyName="Value.ScheduleDateTime" Direction="Descending"/>
                </CollectionViewSource.SortDescriptions>
                <CollectionViewSource.GroupDescriptions>
                    <dat:PropertyGroupDescription PropertyName="Value.ScheduleDateTime.Date" />
                </CollectionViewSource.GroupDescriptions>
            </CollectionViewSource>

P.S. I don't quite get how exactly you want to sort it, but if you sort first groups and then items it should work.


text:
Q: How to set css style to local storage for dynamically created list using Javascript? I've just started a Udemy course on Javascript, and the first project is to create a task list. I created it fine according the the tutorial but I wanted to add some features to it. when a new task gets added, I want to add the ability to mark it as complete.
I've been experimenting on how to do this using css (text-decoration: line-through) but have hit a dead end. Once the button to mark as "complete" is clicked a function is called that checks the list items for the class "check-item". I then add the class name "check-item-style" which applies the line-through to the clicked list item. If you could please help me to insert this into local storage and 'get' from local storage once the browser re-opens.
I'll try and keep the code as brief as possible. Only vanilla javascript if possible! I tried doing a code snippet but it wasn't working very well (maybe due to local storage not being available), so I have included shorted code below. Some of the code wasn't working without all the libraries so had to include sorry!

// Define UI Vars
const form = document.querySelector("#task-form");
const taskList = document.querySelector(".collection");
const taskInput = document.querySelector("#task");

//Event Listeners
form.addEventListener("submit", addTask);
taskList.addEventListener("click", checkTask);
document.addEventListener("DOMContentLoaded", getTasks);

function getTasks() {
  if (localStorage.getItem("tasks") === null) {
    tasks = [];
  } else {
    tasks = JSON.parse(localStorage.getItem("tasks"));
  }
  tasks.forEach(function(task) {
    const li = document.createElement("li");
    li.className = "collection-item";
    li.appendChild(document.createTextNode(task));
    const linkCheck = document.createElement("a");
    linkCheck.className = "check-item secondary-content";
    linkCheck.innerHTML = '';
    li.appendChild(linkCheck);
    taskList.appendChild(li);
  });
}

function addTask(e) {
  if (taskInput.value === "") {
    alert("Add a task");
  } else {
    const li = document.createElement("li");
    li.className = "collection-item";
    li.appendChild(document.createTextNode(task));
    const linkCheck = document.createElement("a");
    linkCheck.className = "check-item secondary-content";
    linkCheck.innerHTML = '';
    li.appendChild(linkCheck);

    taskList.appendChild(li);
    storeTaskInLocalStorage(taskInput.value);
    //Clear input
    taskInput.value = "";
  }

  e.preventDefault();
}

function storeTaskInLocalStorage(task) {
  let tasks;
  if (localStorage.getItem("tasks") === null) {
    tasks = [];
  } else {
    tasks = JSON.parse(localStorage.getItem("tasks"));
  }
  tasks.push(task);

  localStorage.setItem("tasks", JSON.stringify(tasks));
}

function checkTask(e) {
  let check = e.target.parentElement.parentElement;
  if (e.target.parentElement.classList.contains("check-item")) {
    check.className = "check-item-style";
    addStylingToLocalStorage(check.className);
  }
}

function addStylingToLocalStorage() {
  //Please help here
}
.check-item-style {
  text-decoration: line-through;
  padding: 10px;
  padding-right: 20px;
  padding-left: 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
  margin: 0px;
}
<!DOCTYPE html>

    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"
    />
    <link
      href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
      rel="stylesheet"
      integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
      crossorigin="anonymous"
    />
    <title>Task List</title>
    <link rel="stylesheet" href="stylesheet.css" />

      <form id="task-form">

          <input type="text" name="task" id="task" />
          New Task

        <input type="submit" value="Add Task" class="btn" />
      </form>

A: There is an easy way of doing this without storing CSS In localStorage. Right now, if your list of tasks is Cleaning, Sleeping, and Reading, then you JSON looks like this:
[
    "Cleaning",
    "Sleeping",
    "Reading"
]

Each item is just a string. If you want to keep track of what has already been checked, store and retrieve an array of objects from localStorage. This is an example JSON structure.
[
    {
        "name": "Cleaning",
        "done": true
    },
    {
        "name": "Sleeping",
        "done": true
    },
    {
        "name": "Reading",
        "done": false
    }
]

If you reload the page, you just need to style the tasks based on the done property.
Edit to your storing function:
function storeTaskInLocalStorage(task, done) {
  let tasks;
  if (localStorage.getItem('tasks') === null) {
    tasks = [];
  } else {
    tasks = JSON.parse(localStorage.getItem('tasks'));
  }
  tasks.push({
    name: task,
    done: done
  });

  localStorage.setItem('tasks', JSON.stringify(tasks));
}


text:
Q: Is there a convenience method to delete a pin in the Pinterest IOS SDK? Per the documentation (https://developers.pinterest.com/docs/sdks/ios/) there's a method to delete a board PDKClient.sharedInstance().deleteBoardbut I don't see anything to delete a pin?

A: Updating this... a pull request was added re: this issue:  https://github.com/pinterest/ios-pdk/pull/56


text:
Q: Can I use my own AttachedProperty as the StoryBoard.TargetProperty? One of the controls in my view shall have the AttachedProperty "FocusClaim" set to true as soon as the VisualState "Prepared" is activated.
The msdn documentation says I'm allowed to use AttachedProperties, I just have to give ownerType and PropertyName in parenthesis. But doing so results in an Exception:
System.InvalidOperationException: TargetProperty "(my:VisualStateMacro.FocusClaim)" cannot be resolved for the given object.
That's my VisualState with the animation:
<VisualState x:Name="Prepared">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Foo"
            Storyboard.TargetProperty="(my:VisualStateMacro.FocusClaim)">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <system:Boolean>True</system:Boolean>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

And the actual target:
    <TextBox my:VisualStateMacro.FocusClaim="False" x:Name="Foo"/>
One line (found on msdn here PropertyPath for Animation Targets ) though somewhat clashes with the examples given on the same site:

propertyName must be a property that exists on the type specified by Storyboard.TargetName.

And a few lines further down:
<animation Storyboard.TargetProperty="(ownerType.propertyName)" .../>

So am I allowed to use my own AttachedProperty as target or am I bound to use the properties that are present at the Control class?
This is how I defined my AttachedProperty:
public class VisualStateMacro
{
    public static bool GetFocusClaim( DependencyObject obj )
    {
        return (bool) obj.GetValue( FocusClaimProperty );
    }

    public static void SetFocusClaim( DependencyObject obj, bool value )
    {
        obj.SetValue( FocusClaimProperty, value );
    }

    public static readonly DependencyProperty FocusClaimProperty =
        DependencyProperty.RegisterAttached( "FocusClaim", typeof( bool ),
                    typeof( VisualStateMacro ),
                    new PropertyMetadata( false, HandleFocusClaimChanged ) );

    private static void HandleFocusClaimChanged(
              DependencyObject d,
              DependencyPropertyChangedEventArgs e)
    {
        var focusTarget = d as Control;
        if(focusTarget==null)return;

        var shouldReceiveFocusNow = (bool)e.NewValue;

        if (shouldReceiveFocusNow)
        {
            focusTarget.Focus();
        }
    }
}


text:
Q: Why is the IP address lookup in /etc/hosts only sometimes work? The '/etc/hosts' file in a Linux laptop (with LAN IP 172.17.37.21) by default contains :
127.0.1.1 Acer-Aspire-6930G

When I want to reach this laptop wirelessly from a smartphone or a PC using an FTP client, then setting the FTP server (vsftpd) as 127.0.1.1, Acer-Aspire-6930G, or Acer-Aspire-6930G.local sometimes work, but at other times doesn't work. Why is this?
In my modem/router I can set the LAN IP address to always be the same for the MAC address of the laptop, so that 172.17.37.21 can always be used as the FTP server address but, unfortunately, the modem/router at my nephew's laptop site doesn't has this setting. Is there a workaround?


text:
Q: PySpark how to convert an rdd to string I need to pass coordinates in an url but I need to convert the rdd to a string and separate with a semicolon.
all_coord_iso_rdd.take(4)

[(-73.57534790039062, 45.5311393737793),
 (-73.574951171875, 45.529457092285156),
 (-73.5749282836914, 45.52922821044922),
 (-73.57501220703125, 45.52901077270508)]

type(all_coord_iso_rdd)
pyspark.rdd.PipelinedRDD

Results lookin for:
"-73.57534790039062,45.5311393737793;-73.574951171875,45.529457092285156,
 -73.5749282836914,45.52922821044922;-73.57501220703125,45.52901077270508"

The form of my URL should be as follows:
http://127.0.0.1/match/v1/driving/-73.57534790039062,45.5311393737793; -73.574951171875,45.529457092285156,-73.5749282836914,45.52922821044922;-73.57501220703125,45.52901077270508

A: From the snippet you posted all_coord_iso_rdd is an rdd, where each row is a tuple(float, float). Calling take(n) returns n records from the rdd.
x = all_coord_iso_rdd.take(4)
print(x)
#[(-73.57534790039062, 45.5311393737793),
# (-73.574951171875, 45.529457092285156),
# (-73.5749282836914, 45.52922821044922),
# (-73.57501220703125, 45.52901077270508)]

The value returned is simply a list of tuples of floating point numbers. To convert it into the desired format, we can use str.join inside of a list comprehension.
First, you need to convert the floats to str and then we can join the values in each tuple using a ",". We use map(str, ...) to map each value to a str.
This yields:
print([",".join(map(str, item)) for item in x])
#['-73.5753479004,45.5311393738',
# '-73.5749511719,45.5294570923',
# '-73.5749282837,45.5292282104',
# '-73.575012207,45.5290107727']

Finally join the resultant list using ";" to get your desired output.
print(";".join([",".join(map(str, item)) for item in x]))

A: Here is a pure spark way of doing the same (may be useful for larger
rdds/different use cases):
list=[(-73.57534790039062, 45.5311393737793),(-73.574951171875, 45.529457092285156),\
 (-73.5749282836914, 45.52922821044922),(-73.57501220703125, 45.52901077270508)]

rdd=sc.parallelize(list)
rdd.map(lambda row: ",".join([str(elt) for elt in row]))\
   .reduce(lambda x,y: ";".join([x,y]))


text:
Q: Inserting the data from one table to another by grouping one column in Oracle I have a table
Table:1
LEDGER      SOURCE    CATEGORY    ACCOUNT   DR          CR
-------    --------   ---------  --------  ------      -------
ABC          JS1       JE1         A1     123456.7      2345.6
ABC          JS1       JE2         A1     16.7          345.6
ABC          JS2       JE3         A1     13456.7       10
ABC          JS3       JE4         A2     1456.7        45.6
ABC          JS1       JE2         A2     16            345
ABC          JS3       JE5         A2     2456.7        2.6
ABC          JS1       JE1         A3     156.7         25.6    .........

I want to insert this data into another table(table 2) by Source and Category.
For example, I have two lines for source and category JS1, JE1 i.e., line no 1,7 in table 1 for the accounts A1, A3. But I want to insert this data into table2 with only one line as shown below
Table:2
LEDGER SOURCE  CATEGORY  DR_A1  CR_A1   DR_A2  CR_A2  DR_A3  CR_A3
------ ------  -------   ------ ------  -----  -----  -----  ----
ABC    JS1     JE1       1234.7  2345.6 0       0      156.7  5.6
ABC    JS1     JE2       16.7    345.6  16      345    0      0
ABC    JS2     JE3       1346.7  10     0       0      0      0
ABC    JS3     JE4       0       0      1456.7  45.6   0      0
ABC    JS3     JE5       0       0      2456.7  2.6    0      0

(Note: Columns DR_A1, CR_A1 are DR of Account A1 and CR of A1 etc..)
Could anyone please help me to achieve this?

A: You can do this via a standard pivot query:
INSERT INTO Table2 (LEDGER, SOURCE, CATEGORY, DR_A1, CR_A1, DR_A2, CR_A2, DR_A3, CR_A3)
SELECT
    LEDGER,
    SOURCE,
    CATEGORY,
    MAX(CASE WHEN ACCOUNT = 'A1' THEN DR END) AS DR_A1,
    MAX(CASE WHEN ACCOUNT = 'A1' THEN CR END) AS CR_A1,
    MAX(CASE WHEN ACCOUNT = 'A2' THEN DR END) AS DR_A2,
    MAX(CASE WHEN ACCOUNT = 'A2' THEN CR END) AS CR_A2,
    MAX(CASE WHEN ACCOUNT = 'A3' THEN DR END) AS DR_A3,
    MAX(CASE WHEN ACCOUNT = 'A3' THEN CR END) AS CR_A3
FROM Table1
GROUP BY
    LEDGER,
    SOURCE,
    CATEGORY;

But looking at your expected output, it seems that maybe you are also adjusting the DR/CR values during the insert.  If so, then you should add an explanation to your question about what is happening.

A: If you're on Oracle 11g there is a standard way of doing this, that is even shorter:
SELECT *
  FROM tab
  pivot (MAX(dr) dr, MAX(cr) cr FOR (ACCOUNT) IN ('A1' AS a1, 'A2' as a2, 'A3' AS a3))


text:
Q: OpenCV application - Android Camera crashes after 10 seconds Background
In this application, I was able to launch my camera preview that was developed in Android Studio with an aim to incorporate OpenCV into it. However, I face an error; the camera preview only lasts around 10 seconds until it crashes and the app shuts down. Would there be any way to resolve this? Here is my code;
MainActivity.java
package com.example.cv;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.opengl.Matrix;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.Toast;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2
{
    private static String TAG = "MainActivity";
    JavaCameraView javaCameraView;
    Mat mRGBA, mRGBAT;

    private static final int MY_CAMERA_REQUEST_CODE = 100;

    BaseLoaderCallback baseLoaderCallback = new BaseLoaderCallback(MainActivity.this) {
        @Override
        public void onManagerConnected(int status)
        {
            if (status == BaseLoaderCallback.SUCCESS) {
                javaCameraView.enableView();
            } else {
                super.onManagerConnected(status);
            }
        }
    };

    static
    {
        if (OpenCVLoader.initDebug())
        {
            Log.d(TAG, "OpenCV is Configured or Connected successfully.");
        }
        else
        {
            Log.d(TAG, "OpenCV not Working or Loaded.");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        javaCameraView = (JavaCameraView) findViewById(R.id.my_camera_view);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED)  {
            Log.d(TAG, "Permissions granted");
            javaCameraView.setCameraPermissionGranted();
            javaCameraView.setCameraIndex(CameraBridgeViewBase.CAMERA_ID_BACK);
            javaCameraView.setVisibility(CameraBridgeViewBase.VISIBLE);
            javaCameraView.setCvCameraViewListener(this);
        } else {
            Log.d(TAG, "Permission prompt");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
        }

    }

    @Override
    public void onCameraViewStarted(int width, int height)
    {
        mRGBA = new Mat(height, width, CvType.CV_8UC4);
    }

    @Override
    public void onCameraViewStopped()
    {
        mRGBA.release();
    }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame)
    {
        mRGBA = inputFrame.rgba();
        mRGBAT = mRGBA.t();
        Core.flip(mRGBA.t(), mRGBAT, 1);
        Imgproc.resize(mRGBAT, mRGBAT, mRGBA.size());
        return mRGBAT;
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (javaCameraView != null)
        {
            javaCameraView.disableView();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (javaCameraView != null)
        {
            javaCameraView.disableView();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (OpenCVLoader.initDebug())
        {
            Log.d(TAG, "OpenCV is Configured or Connected successfully.");
            baseLoaderCallback.onManagerConnected(BaseLoaderCallback.SUCCESS);
        }
        else
        {
            Log.d(TAG, "OpenCV not Working or Loaded.");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION, this, baseLoaderCallback);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_CAMERA_REQUEST_CODE) {
            // camera can be turned on
            Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
            javaCameraView.setCameraPermissionGranted();
            javaCameraView.setCameraIndex(CameraBridgeViewBase.CAMERA_ID_FRONT);
            javaCameraView.setVisibility(CameraBridgeViewBase.VISIBLE);
            javaCameraView.setCvCameraViewListener(this);
        } else {
            //camera will stay off
            Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
        }
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.cv">

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera"/>
    <uses-feature android:name="android.hardware.camera.autofocus"/>
    <uses-feature android:name="android.hardware.camera.front"/>
    <uses-feature android:name="android.hardware.camera.front.autofocus"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <org.opencv.android.JavaCameraView
        android:id="@+id/my_camera_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

</RelativeLayout>

A: I did some further investigation on your issue and here are a few considerations:
1 - I had already suggested you in the comments of this previous answer to release the matrices inside onCameraFrame() as soon as they are not needed anymore. Forgetting this can generate garbage collection issues, as outlined in this answer or here. You can explicitly invoke this process to happen by using the Mat.release() method, as the user does in the same answer. Did you try it? from my tests it was extending the 10 seconds of camera life, despite not yet fixing the bug
2 - from this answer instead, we can understand that transposing too many times may create other troubles. Let's give a look at your code:
mRGBAT = mRGBA.t();
Core.flip(mRGBA.t(), mRGBAT, 1);

This definitely looks like something we can improve. You are first assigning mRGBA.t() to mRGBAT but then you ask again to calculate the transpose matrix for mRGBA when calling Core.flip(). The result is already stored in mRGBAT, thus there is no need to perform such operation again. Then you can fix this issue like this:
mRGBAT = mRGBA.t();
Core.flip(mRGBAT, mRGBAT, 1);

3 - there is no real difference between Mat.t() and Core.transpose() but the first is a wrapper around the second and we can directly use the latter
The entire snippet that will solve your issue is the following:
Mat mRGBA, mRGBAT, dst;

@Override
public void onCameraViewStarted(int width, int height)
{
    mRGBAT = new Mat();
    dst = new Mat();
}

@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame)
{
    mRGBA = inputFrame.rgba();
    Core.transpose(mRGBA, mRGBAT);
    Core.flip(mRGBAT, mRGBAT, 1);
    Imgproc.resize(mRGBAT, dst, mRGBA.size());
    mRGBA.release();
    mRGBAT.release();
    return dst;
}


text:
Q: Find value in vector and return reference to value I'm using this function to find value in vector.
void program_data::find_curlAccountdata(int world, std::wstring login, std::wstring pass, curl_accounts & tmp){
    std::unordered_map <int, std::vector<curl_accounts> > &t = curl_accountsdata; //world
    std::vector<curl_accounts> &b = t[world];
    std::vector<curl_accounts>::iterator & it = std::find_if(b.begin(), b.end(), [login, pass](curl_accounts& s) { return (s.name == login && s.pass == pass); });
    if (it != b.end()){
        tmp = *it;
    }
}

And curl_accounts is struct.
Now when I edit some value in the struct in one place, and try to check it in second place it not the same.
So could you fix my function?
EDIT::
curl_accounts tmp,tmp2;
program_data::getInstance().find_curlAccountdata(server, login, pass, tmp);
tmp.logged = true;
std::cout << "TMP LOGGED: "<< tmp.logged<<std::endl; // return true
program_data::getInstance().find_curlAccountdata(server, login, pass, tmp2);
std::cout << "TMP 2 LOGGED: " << tmp2.logged << std::endl; // return false
std::cout << "sth";

A: You need a reference to a pointer. Try changing your signature to use curl_accounts *& tmp, instead of curl_accounts &tmp.


text:
Q: Sockets used to send messages between machines I want to make a sort of chat server between my desktop and my laptop using sockets. Does anybody know of a good tutorial on this or if you have any files with comments on it that I can use as reference?

A: This could be good at the beginning of your adventure:
https://medium.com/swlh/lets-write-a-chat-app-in-python-f6783a9ac170


text:
Q: Difference in Pointers in C What are the differences between these three pointers in C? I'm confused on how they differ.
int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);

A: int* arr1[8];

arr1 is an array of 8 pointers to int.
int (*arr2)[8];

arr2 is a pointer to array of 8 ints.
int *(arr3[8]);

Same as arr1. The brackets are superfluous.
You may want to read Right-Left rule on how to read complex C declarations.


text:
Q: Div hover not working when scrolling in chrome Please take a look at this code: http://jsfiddle.net/6JnJb/1/
My problem is that in chrome, the divs doesn't change their color if the mouse is over them, when scrolling. If I move the mouse over a div 'manually' (not when scrolling) than it changes it's color to red.
In Firefox it works perfect, but not in Chrome.
Can I solve this problem or simply this how Chrome works?

A: Chrome does not propagate mouseover events right away when scrolling. There really isn't any way around this issue, since it is giving priority to the scrolling event rather than the hover event on a particular element.
The behavior I see is that the hover effect doesn't move with the still mouse on scroll but catches up when the scroll speed is sufficiently low.


text:
Q: How to write to file from different threads, OpenMP, C++ I use openMP for parallel my C++ program. My parallel code have very simple form
#pragma omp parallel for shared(a, b, c) private(i, result)
        for (i = 0; i < N; i++){
         result= F(a,b,c,i)//do some calculation
         cout<<i<<" "<<result<<endl;
         }

If two threads try to write into file simultaneously, the data is mixed up.
How I can solve this problem?

A: OpenMP provides pragmas to help with synchronisation.  #pragma omp critical allows only one thread to be executing the attached statement at any time (a mutual exclusion critical region).  The #pragma omp ordered pragma ensures loop iteration threads enter the region in order.
// g++ -std=c++11 -Wall -Wextra -pedantic -fopenmp critical.cpp
#include <iostream>

int main()
{
  #pragma omp parallel for
  for (int i = 0; i < 20; ++i)
    std::cout << "unsynchronized(" << i << ") ";
  std::cout << std::endl;
  #pragma omp parallel for
  for (int i = 0; i < 20; ++i)
    #pragma omp critical
    std::cout << "critical(" << i << ") ";
  std::cout << std::endl;
  #pragma omp parallel for ordered
  for (int i = 0; i < 20; ++i)
    #pragma omp ordered
    std::cout << "ordered(" << i << ") ";
  std::cout << std::endl;
  return 0;
}

Example output (different each time in general):
unsynchronized(unsynchronized(unsynchronized(05) unsynchronized() 6unsynchronized() 1unsynchronized(7) ) unsynchronized(unsynchronized(28) ) unsynchronized(unsynchronized(93) ) unsynchronized(4) 10) unsynchronized(11) unsynchronized(12) unsynchronized(15) unsynchronized(16unsynchronized() 13unsynchronized() 17) unsynchronized(unsynchronized(18) 14unsynchronized() 19)
critical(5) critical(0) critical(6) critical(15) critical(1) critical(10) critical(7) critical(16) critical(2) critical(8) critical(17) critical(3) critical(9) critical(18) critical(11) critical(4) critical(19) critical(12) critical(13) critical(14)
ordered(0) ordered(1) ordered(2) ordered(3) ordered(4) ordered(5) ordered(6) ordered(7) ordered(8) ordered(9) ordered(10) ordered(11) ordered(12) ordered(13) ordered(14) ordered(15) ordered(16) ordered(17) ordered(18) ordered(19)

A: Problem is: you have a single resource all threads try to access. Those single resources must be protected against concurrent access (thread safe resources do this, too, just transparently for you; by the way: here is a nice answer about thread safety of std::cout). You could now protect this single resource e. g. with a std::mutex. Problem then is, that the threads will have to wait for the mutex until the other thread gives it back again. So you only will profit from parallelisation if F is a very complex function.
Further drawback: as threads work parallel, even with a mutex to protect std::in, the results can be printed out in arbitrary order, depending on which thread happens to operate earlier.
If I may assume that you want the results of F(... i) for smaller i before the results of greater i, you either should drop parallelisation entirely or do it differently:
Provide an array of size N and let each thread store its results there (array[i] = f(i);). Then iterate over the array in a separate non-parallel loop. Again, doing so is only worth the effort if F is a complex function (and for large N).
Additionally: Be aware that threads must be created, too, which causes some overhead somewhere (creating thread infrastructure and stack, registering thread at OS, ... – unless if you can reuse some threads already created in a thread pool earlier...). Consider this, too, when deciding if you want to parallelise or not. Sometimes, non-parallel calculations can be faster...