text:
Q: Django & docker-compose - psycopg2 connection error I am trying to run a simple Django app with PostgreSQL using docker-compose.
The PostgreSQL container runs fine and is accessible but I am unable to reach it from inside the Django container using python.
Here is my docker-compose.yaml:
version: "3"
services:
  db:
    image: "postgres"
    restart: always
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
    volumes:
      - pgdata:/var/lib/postgresql/data

  django:
    build: ./qc_django
    ports:
      - "8080:8080"
    environment:
      - DB_NAME=django
      - DB_USER=${DB_USER}
      - DB_PASSWORD=${DB_PASSWORD}
      - DB_HOST=db
      - DB_PORT=5432
      - DEBUG=True
    depends_on:
      - db

volumes:
  pgdata:

Here are the database settings inside of the Django settings:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': env("DB_NAME"),
        'USER': env("DB_USER"),
        'PASSWORD': env("DB_PASSWORD"),
        'HOST': env("DB_HOST"),
        'PORT': env("DB_PORT"),
    }
}

The error it spits out after a minute or so:
django.db.utils.OperationalError: could not connect to server: Connection timed out
     Is the server running on host "db" (172.21.0.2) and accepting
     TCP/IP connections on port 5432?

A:
You need to expose 5432 port for PostgresDB

As you mention, this is not mandatory anymore.
Your issue can throw because the PostgreSQL service is not started yet. So the port 5432 is not already listening. The depends_on parameter wait for the database container start, not for the database service.
You can follow this guide, they suggest putting a script that wait until the database service is launched, then start your Django application : https://docs.docker.com/compose/startup-order/

A: After rebooting and removing orphan containers with --remove-orphans my original configuration worked. Looks like there might have been some interference.


text:
Q: What's the reason aero turns off and then sometimes comes back again? Just now it happened, and after a couple minutes it turned back on, which is not something that happened before. Before this I have only seen it turning off by itself and I had to restart it after a few days to restore it myself.
I am not running any application that doesn't support aero, so that shouldn't be it. My PC also doesn't use power-saving settings either.
Why would windows 7 do this?

A: It might by caused by the Windows System Assessment Tool, which Windows 7 runs every Sunday at 1 AM by default. Aero is disabled while it's running.
More info: http://en.wikipedia.org/wiki/Windows_System_Assessment_Tool

A: Aero is highly dependent of your graphics card. if the driver fails as you mentioned, Aero is prone to get disabled.
This driver failure may be caused by a faulty installation of your graphics drivers or them being outdated.
Make sure you have up-to-date drivers, provided from the manufacturer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What Packages Does KDE Vaults Need to Operate? I'm planning on un-encrypting my home directory for easily moving it to an SSD (by following this tutorial: https://askubuntu.com/a/4960/645874), but I'm not sure if this will affect KDE Vaults.
Does KDE Vaults rely on the packages ecryptfs-utils or libecryptfs0? If so, is their un-installation necessry?

A: The Ubuntu plasma-vault package page for 18.04/bionic doesn't mention "ecryptfs" in any of the dependencies, so I'd say no.
But, there's nothing like getting a custom answer about your specific system, so you can always simulate a remove (or install) to see what other packages would be removed (or added) with a package manager interface like Synaptic, or just
apt-get --simulate remove plasma-vault

The relevant lines should be similar to this non-vaults example:
The following packages were automatically installed and are no longer required:
  libecryptfs1 libtspi1
Use 'apt autoremove' to remove them.
The following packages will be REMOVED:
  ecryptfs-utils


text:
Q: Apache mod_proxy_uwsgi and unix domain sockets I have a uwsgi server running for unix domain socket
[uwsgi]
...
socket = /var/run/someuwsgi.sock
socket = localhost:9987
...

The mod_proxy_uwsgi is installed
In apache config has that line:
    ProxyPass /some uwsgi://localhost:9987
And it is working.
Question: what should be  the apache config line to go through unix domain socket
   /var/run/someuwsgi.sock
?
I tried
ProxyPass /some uwsgi:///var/run/someuwsgi.sock

and got
Bad Request
Your browser sent a request that this server could not understand.

Also tried
ProxyPass /some uwsgi://unix:///var/run/someuwsgi.sock

and got
Proxy Error

The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET /some/.

Reason: DNS lookup failure for: unix:

Thanks!

A: Starting from Apache 2.4.7, support for Unix sockets has been added. The syntax is pretty simple:
ProxyPass / unix:/tmp/uwsgi.sock|uwsgi://

A: Unfortunately the apache proxy api does not (currently) support unix sockets

A: From the comments on the other answer and my experience this seems to be the correct syntax:
ProxyPass /some unix:/var/run/someuwsgi.sock|uwsgi://localhost

https://httpd.apache.org/docs/trunk/en/mod/mod_proxy.html#proxypass

In 2.4.7 and later, support for using a Unix Domain Socket is available by using a target which prepends unix:/path/lis.sock|. For example, to proxy HTTP and target the UDS at /home/www.socket, you would use unix:/home/www.socket|http://localhost/whatever/. Since the socket is local, the hostname used (in this case localhost) is moot, but it is passed as the Host: header value of the request.


text:
Q: Create new log file daily using log4j I want to use Log4j in my java project, which configuration should I provide in
configuration file that every night at 12.00 am new file will generate and file
name should like - output-log-of-MyProjectName-HostName-2013-Dec-10.txt
name). My configuration  file is like that-
log4j.appender.FILE = org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.File = ${log}/log.out
log4j.appender.FILE.DatePattern = '.' yyyy-MM-dd-a

It is creating new file everyday but it appending date after file name.
Please help me. Thanks in advance.

A: I think you want DailyRollingFileAppender (geedubb links to the log4j docs about it)
Here is example
Here is another stackoverflow question like yours


text:
Q: Trying to pull data from Vue components in single file components This is my first time experimenting with Vue.js so it's altogether possible I'm missing something very obvious.
Basically, I have a component that calculates the number of boxes needed for a certain quantity of a printed piece (I work in the print industry).
If needed, I have a button to create an additional component if the printed piece has multiple parts.
I'd like to have a reactive way to update the total number of boxes needed for all parts, but I just can't seem to get there.
Here's a link to my Gitlab repo with the code: https://gitlab.com/dsross/printutils
Any help would be appreciated.
I'm also using Browserify to write the build.js and build.css files referenced in index.html.
Here are my files, in case no one wants to look at the repo:
App.vue
<template>

      <calculator v-for="(part, index) in parts" :key="index"></calculator>

          <button type="button" class="btn" @click="addPart()">Add Part</button>
          <button type="button" class="btn" @click="totalBoxes">Total Boxes</button>
          Box Total (all parts):

</template>

Calculator.vue
<template>

            <form>

Paper:
                        <select class="custom-select" v-model="paperWeight">
                            <option v-for="(mweight, paper) in mweights" :key="mweight" v-bind:value="paper">{{paper}}</option>
                        </select>

Final Width:
                        <input class="form-control" type="text" v-model="finalWidth" id="finalWidth" value="">

Final Height:
                        <input type="text" class="form-control" v-model="finalHeight" id="finalHeight" value="">

Sheets Per Unit:
                        <input type="text" class="form-control" v-model="numberOfSheets" id="numberOfSheets" name="numberOfSheets"
                            value="">

Quantity:
                        <input type="text" class="form-control" v-model="quantity" id="quantity" name='quantity'>

Stitched:
                        <input type="checkbox" v-model="stitched" name="stitched" id="stitched" value="">

            </form>

Part Total Weight: {{ totalWeight }}

Part Box Total: {{ boxQuantity }}

</template>

index.html
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>boxcalculator2</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="icon" href="../favicon.png">
  <title>Box Calculator</title>

  <link href="dist/css/bootstrap.min.css" rel="stylesheet">

  <link href="dist/sticky-footer.css" rel="stylesheet">
  <link rel="stylesheet" href="dist/build.css">

A: If I understand correctly, you'd like the App's total box count to be updated automatically whenever the individual Calculators determine their box counts. One way to do this is to emit an event from Calculator when its box count changes, which could be monitored with a watcher.
There are a couple issues we'll address below:

*

*It doesn't make sense (and is inefficient) to store Calculator -- a single-file-component definition -- in this.parts[]. Instead, it could store meaningful data points, such as Calculator's output.

*Instead of DOM manipulation (i.e., querying the DOM for an element to get/set its value), opt for modeling the data in Vue, and using interpolation in the template. This lets Vue automatically display the updated value in the target element. It also obviates the element ID assignments (assuming they were used exclusively for DOM manipulation), simplifying the template for improved readability.

Storing Calculator output
In App, we must use this.parts[] to track the result of each part's calculation (which we'll capture below). We'll define each array element (i.e., a "part") to be:
{
  boxes: 0 // box count for this part
}

This definition allows a computed property (which we'll define later), based on .boxes, to be reactive.
So, in addPart() and the data option:
// App.vue
export default {
  // ...
  methods: {
    addPart() {
      this.parts.push({ boxes: 0 });
    }
  },
  data() {
    return {
      parts: [{ boxes: 0 }]
    }
  }
}

Notifying App of Calculator output
Typically, parents pass data to children via props, and children communicate data to parents with events. Alternatives include using a state management library, such as Vuex, but for the sake of simplicity, we'll use events here.
In Calculator, we want to notify the parent (App) of changes to the boxes value, so we'll add a watcher that emits an event (e.g., called boxes-changed) whenever boxes changes:
// Calculator.vue
export default {
  //...
  watch: {
    boxes(value) {
      this.$emit('boxes-changed', value);
    }
  }
}

In App, we'll listen to the boxes-changed event, and copy the event detail's value to the current part's boxes variable, where part is the current array element of parts[] being iterated.
// App.vue
<calculator v-for="(part, index) in parts" @boxes-changed="part.boxes = $event" :key="index"></calculator>

Breakdown of @boxes-changed="part.boxes = $event":

*

*@boxes-changed="..."    - listen to boxes-changed event emitted from <calculator>

*part.boxes = $event     - set part.boxes to value of event detail

Making totalBoxCount reactive
With the changes above, we have the tools needed to make App's totalBoxCount reactive:

*

*Change totalBoxCount into a computed property that sums up the .boxes fields of this.parts[]. This property will be computed automatically whenever array elements of this.parts[] changes.
 // App.vue
 export default {
   computed: {
     totalBoxCount() {
       // Note: Alternatively, use a simple for-loop to sum .boxes
       return this.parts
               .filter(p => p.boxes && !Number.isNaN(p.boxes) // get only parts that have a positive `.boxes` value
               .map(p => p.boxes)          // map object array into an integer array of `.boxes` values
               .reduce((p,c) => p + c, 0); // sum all array elements
     },
   },
   data() {
     return {
       parts: [],
       // totalBoxCount: 0   // CHANGED INTO COMPTUED PROP ABOVE
     }
   }
 }

*In App's template, use string interpolation to display totalBoxCount:

Box Total (all parts): {{totalBoxCount}}

*We might as well remove the Total Boxes button (previously used to manually trigger a calculation) from the template:

and its associated click-handler:
    // App.vue
    export default {
      methods: {
        // totalBoxes: function() { /* .. */ } // DELETE THIS
      }
    }

demo


text:
Q: Make GNU Parallel not delay before executing arguments from STDIN GNU Parallel, without any command line options, allows you to easily parallelize a command whose last argument is determined by a line of STDIN:
$ seq 3 | parallel echo
2
1
3

Note that parallel does not wait for EOF on STDIN before it begins executing jobs — running yes | parallel echo will begin printing infinitely many copies of y right away.
This behavior appears to change, however, if STDIN is relatively short:
$ { yes | ghead -n5; sleep 10; } | parallel echo

In this case, no output will be returned before sleep 10 completes.
This is just an illustration — in reality I'm attempting to read from a series of continually generated FIFO pipes where the FIFO-generating process will not continue until the existing pipes start to be consumed. For example, my command will produce a STDOUT stream like:
/var/folders/2b/1g_lwstd5770s29xrzt0bw1m0000gn/T/tmp.PFcggGR55i
/var/folders/2b/1g_lwstd5770s29xrzt0bw1m0000gn/T/tmp.UCpTBzI3J6
/var/folders/2b/1g_lwstd5770s29xrzt0bw1m0000gn/T/tmp.r2EmSLW0t9
/var/folders/2b/1g_lwstd5770s29xrzt0bw1m0000gn/T/tmp.5TRNeeZLmt

Manually cat-ing each of these files one at a time in a new terminal causes the FIFO-generating process to complete successfully. However, running printfifos | parallel cat does not work. Instead, parallel seems to block forever waiting for input on STDIN — if I modify the pipeline to printfifos | head -n4 | parallel cat, the deadlock disappears and the first four pipes are printed successfully.
This behavior seems to be connected to the --jobs|-j parameter. Whereas { yes | ghead -n5; sleep 10; } | parallel cat produces no output for 10 seconds, adding a -j1 option yields four lines of y almost immediately followed by a 10 second wait for the final y. Unfortunately this does not solve my problem — I need every argument to be processed before parallel can get EOF from reading STDIN. Is there any way to achieve this?

A: A bug in GNU Parallel does, that it only starts processing after having read one job for each jobslot. After that it reads one job at a time.
In older versions the output will also be delayed by the number of jobslots. Newer versions only delay output by a single job.
So if you sent one job per second to parallel -j10 it would read 10 jobs before starting them. Older versions you would then have to wait an additional 10 seconds before seeing the output from job 3.
A workaround the limitation at start is to feed one dummy job per jobslot to parallel:
true >jobqueue; tail -n+0 -f jobqueue | parallel &
seq $(parallel --number-of-threads) | parallel -N0 echo true >> jobqueue
# now add the real jobs to jobqueue

A workound the output is to use --linebuffer (but this will mix full lines from different jobs).


text:
Q: "JSON editor" for windows? Is there any JSON program for Windows, like Cocoa's JSON Editor ?
It's important that it's visual easy, and that you can by clicking adding new objects etc.

A: Nevermind. I found one here. Simple, and visual easy to use.


text:
Q: How to retrieve/display multi columns single row from database to different html tags OK so what I'm am trying to do is retrieve multiple columns of data from a single row in mysql database and basically place the data of the different columns into multiple places on my html code such as in "p" and "td" tags to display on webpage.
I have successfully been able to display the "description"(description is the name of 1 of the database columns) inside the "p" tags using PHP but I don't know how to display any other columns of the database into other html tags such as the "td" tags. There is probably going to be a total of roughly 10 columns of text in database I want to display in the webpage but again where it's displaying is in various html tags and not a table which is what I keep finding when researching and tired of banging my head on the desk. There is a small example below. I'm learning as I go so any help would be great. Thank you!
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
?>

Descrption

    <?php
    if($resultCheck > 0) {
      while ($row = mysqli_fetch_assoc($result)) {
        echo $row['Description'];
      }
    }
    ?>

  <?php
  if($resultCheck > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
      echo $row["Material"];
    }
  }
  ?>

A: Try this

        <?php
                $sql = "SELECT * FROM Parts;";
                $result = mysqli_query($conn, $sql);
                $resultCheck = mysqli_num_rows($result);

                      if($resultCheck > 0) {
                      while ($row = mysqli_fetch_assoc($result)) {
        ?>

Descrption

                    <?php

                        echo $row['Description'];

                    ?>

                  <?php

                      echo $row["Material"];

                  ?>

        <?php

        }
    }
        ?>

A: My preference is to fetch all rows first, rather then fetching rows while rendering html, otherwise if there is an error fetching rows, it becomes mixed in with your html
I also recommend using htmlentities() to escape any html data (assuming that description or material does not already include valid html
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);

?>

Descrption

    <?php
      foreach ($rows as $row) {
        echo htmlentities($row['Description']);
      }
    ?>

  <?php
    foreach ($rows as $row) {
      echo htmlentities($row["Material"]);
    }
  ?>


text:
Q: OpenVPN server not starting after generating config file for client I am new to OpenVPN and to set up a server I followed this guide. I am using Ubuntu 18.04.4 LTS.
Here is what I get on starting OpenVPN
omayr@x556uqk:~$ sudo systemctl start openvpn@server
Job for openvpn@server.service failed because the control process exited with error code.
See "systemctl status openvpn@server.service" and "journalctl -xe" for details.

Status:
omayr@x556uqk:~$ sudo systemctl status openvpn@server
● openvpn@server.service - OpenVPN connection to server
   Loaded: loaded (/etc/systemd/system/openvpn@.service; indirect; vendor preset
   Active: activating (auto-restart) (Result: exit-code) since Sat 2020-02-22 23
     Docs: man:openvpn(8)
           https://community.openvpn.net/openvpn/wiki/Openvpn24ManPage
           https://community.openvpn.net/openvpn/wiki/HOWTO
  Process: 3740 ExecStart=/usr/sbin/openvpn --daemon ovpn-server --status /run/o
 Main PID: 3740 (code=exited, status=1/FAILURE)


text:
Q: Android Facebook Sdk 4.11.0 How to post a simple status update to wall without any link or image I am trying to build an app that updates a user's facebook status when the user gives a voice input like "update my status to enjoying holidays at Newyork " and "enjoying holidays at Newyork" will be posted as user's status.
How can i do this ?
I have tried shareLinkContet but it seems to share a link with some description and also tried setting setContentTitle and setContentUrl to null but failed,I have been using Facebook Android Sdk 4.11.0 ..

A: I have finally got the answer
  GraphRequest request=GraphRequest.newPostRequest(AccessToken.getCurrentAccessToken(), "me/feed", null, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
                     Log.d(TAG,"STATUS UPDATED SUCESSFULLY");
        }
    });
    Bundle parameters=new Bundle();
    parameters.putString("message","hellow everyone from newyork");
     request.setParameters(parameters);
    request.executeAsync();

this works perfectly


text: Q: Subversion Lost Track of Deleted Files I've been doing a lot of cleanup on a large solution controlled via Subversion.  We use the AnkhSVN plugin for Visual Studio support.  I had to restart my machine for unrelated reasons, and after returning to Visual Studio, all the deleted files have disappeared from the Pending Changes window.  The various project files where the files were are still showing as modified, but I fear that when I check in the changes, the files I deleted will not be deleted from the repository.  The deleted files are still deleted from my local machine, and are not showing up in Solution Explorer, but when I browse the SVN repo, they are (obviously) still shown there.  How can I force SVN to take a closer look at my working copy and see that I've deleted the files?


text:
Q: Returning a const reference to an object instead of a copy Whilst refactoring some code I came across some getter methods that returns a std::string.  Something like this for example:
class foo
{
private:
    std::string name_;
public:
    std::string name()
    {
        return name_;
    }
};

Surely the getter would be better returning a const std::string&?  The current method is returning a copy which isn't as efficient.  Would returning a const reference instead cause any problems?

A: Okay, so the differences between returning a copy and returning the reference are:

*

*Performance: Returning the reference may or may not be faster; it depends on how std::string is implemented by your compiler implementation (as others have pointed out). But even if you return the reference the assignment after the function call usually involves a copy, as in std::string name = obj.name();

*Safety: Returning the reference may or may not cause problems (dangling reference). If the users of your function don't know what they are doing, storing the reference as reference and using it after the providing object goes out of scope then there's a problem.
If you want it fast and safe use boost::shared_ptr. Your object can internally store the string as shared_ptr and return a shared_ptr. That way, there will be no copying of the object going and and it's always safe (unless your users pull out the raw pointer with get() and do stuff with it after your object goes out of scope).

A: The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed.  Like this:
foo *pFoo = new foo;
const std::string &myName = pFoo->getName();
delete pFoo;
cout << myName;  // error! dangling reference

However, since your existing function returns a copy, then you would
not break any of the existing code.
Edit: Modern C++ (i. e. C++11 and up) supports Return Value Optimization, so returning things by value is no longer frowned upon.  One should still be mindful of returning extremely large objects by value, but in most cases it should be ok.

A: I'd change it to return const std::string&.  The caller will probably make a copy of the result anyway if you don't change all the calling code, but it won't introduce any problems.
One potential wrinkle arises if you have multiple threads calling name().  If you return a reference, but then later change the underlying value, then the caller's value will change.  But the existing code doesn't look thread-safe anyway.
Take a look at Dima's answer for a related potential-but-unlikely problem.

A: Actually, another issue specifically with returning a string not by reference, is the fact that std::string provides access via pointer to an internal const char* via the c_str() method.  This has caused me many hours of debugging headache.  For instance, let's say I want to get the name from foo, and pass it to JNI to be used to construct a jstring to pass into Java later on, and that name() is returning a copy and not a reference.  I might write something like this:
foo myFoo = getFoo(); // Get the foo from somewhere.
const char* fooCName = foo.name().c_str(); // Woops!  foo.name() creates a temporary that's destructed as soon as this line executes!
jniEnv->NewStringUTF(fooCName);  // No good, fooCName was released when the temporary was deleted.

If your caller is going to be doing this kind of thing, it might be better to use some type of smart pointer, or a const reference, or at the very least have a nasty warning comment header over your foo.name() method.  I mention JNI because former Java coders might be particularly vulnerable to this type of method chaining that may seem otherwise harmless.

A: It is conceivable that you could break something if the caller really wanted a copy, because they were about to alter the original and wanted to preserve a copy of it. However it is far more likely that it should, indeed, just be returning a const reference.
The easiest thing to do is try it and then test it to see if it still works, provided that you have some sort of test you can run. If not, I'd focus on writing the test first, before continuing with refactoring.

A: One problem for the const reference return would be if the user coded something like:
const std::string & str = myObject.getSomeString() ;

With a std::string return, the temporary object would remain alive and attached to str until str goes out of scope.
But what happens with a const std::string &? My guess is that we would have a const reference to an object that could die when its parent object deallocates it:
MyObject * myObject = new MyObject("My String") ;
const std::string & str = myObject->getSomeString() ;
delete myObject ;
// Use str... which references a destroyed object.

So my preference goes to the const reference return (because, anyway, I'm just more confortable with sending a reference than hoping the compiler will optimize the extra temporary), as long as the following contract is respected: "if you want it beyond my object's existence, they copy it before my object's destruction"

A: Some implementations of std::string share memory with copy-on-write semantics, so return-by-value can be almost as efficient as return-by-reference and you don't have to worry about the lifetime issues (the runtime does it for you).
If you're worried about performance, then benchmark it (<= can't stress that enough) !!! Try both approaches and measure the gain (or lack thereof). If one is better and you really care, then use it. If not, then prefer by-value for the protection it offers agains lifetime issues mentioned by other people.
You know what they say about making assumptions...

A: Odds are pretty good that typical usage of that function won't break if you change to a const reference.
If all of the code calling that function is under your control, just make the change and see if the compiler complains.

A: Does it matter? As soon as you use a modern optimizing compiler, functions that return by value will not involve a copy unless they are semantically required to.
See the C++ lite FAQ on this.

A: Depends what you need to do.  Maybe you want to all the caller to change the returned value without changing the class.  If you return the const reference that won't fly.
Of course, the next argument is that the caller could then make their own copy.  But if you know how the function will be used and know that happens anyway, then maybe doing this saves you a step later in code.

A: I normally return const& unless I can't. QBziZ gives an example of where this is the case. Of course QBziZ also claims that std::string has copy-on-write semantics which is rarely true today since COW involves a lot of overhead in a multi-threaded environment. By returning const & you put the onus on the caller to do the right thing with the string on their end. But since you are dealing with code that is already in use you probably shouldn't change it unless profiling shows that the copying of this string is causing massive performance problems. Then if you decide to change it you will need to test thouroughly to make sure you didn't break anything. Hopefully the other developers you work with don't do sketchy stuff like in Dima's answer.

A: Returning a reference to a member exposes the implementation of the class.
That's could prevent to change the class. May be usefull for private or protected methods incase the optimization is needed.
What should a C++ getter return


text:
Q: Get multiline textbox value from jquery dialog I try to make a popup dialog in my asp net website with form for send message.
I do in asp net user control:
<asp:Panel runat="server" ID="panelMain" ToolTip="" style="display: none">
    <asp:Label runat="server" ID="Label1" AssociatedControlID="txtMessage" Text=""></asp:Label>:

    <asp:TextBox runat="server" ID="txtMessage" ></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1"
        ControlToValidate="txtMessage" Display="Dynamic"
        ErrorMessage=""></asp:RequiredFieldValidator>

    <asp:Button ID="butOk" runat="server" Text="" OnClick="butOk_Click"/>
    <asp:Button ID="butCancel" runat="server" Text="" CausesValidation="false" />
</asp:Panel>

$.fn.extend({
    dialogCloseAndSubmit: function(butOkId)
    {
        var dlg = $(this).clone();
        $(this).dialog("destroy").remove();
        dlg.css("display", "none");
        $("form:first").append(dlg);
        $("#" + butOkId, dlg).click();
        return true;
    }
});

In code behind:
protected void butOk_Click(object sender, EventArgs e)
    {
        // will be send mail
        Literal str_message = new Literal();
        str_message.Mode = LiteralMode.PassThrough;
        str_message.Text = "
Success!Message: " + this.txtMessage.Text;
        this.Page.Controls.Add(str_message);
    }

And it's all good when TextBox is one line (Success!Message: hello), but if I change attribute to TextMode="MultiLine" I have no TextBox value (Success!Message:)
How can I solve this problem?

A: Maybe Try:
$(this).find('textarea[id*=txtMessage]').val();

As discussed in this answer


text:
Q: ¿Cómo llenar select con ajax? Muestro un pedazo del HTML y Javascript, la parte del del HTML igual tengo un input donde almaceno un id y el nombre del grupo, entonces la respuesta del ajax del javascript si me trae los datos y si lleno esos input, pero no logro llenar el select con los elementos que me trae
HTML
<select class="duallistbox" multiple="multiple" id="editarPermisos" name="editarPermisos[]">
        <?php
             $permisos = ControladorOtros::ctrMostrarPermisos();
             foreach ($permisos as $key => $value) {
                     echo '<option value="'.$value["nombre_permiso"].'">'.$value["nombre_permiso"].'</option>';
             }

        ?>
</select>

JS grupos.js
$(document).on("click", ".btnEditarGrupo", function(){

var id_grupo = $(this).attr("id_grupo");

var datos = new FormData();
datos.append("id_grupo", id_grupo);

$.ajax({
    url: "ajax/grupos.ajax.php",
    method: "POST",
    data: datos,
    cache: false,
    contentType: false,
    processData: false,
    dataType:"json",
    success: function(respuesta){

        $("#editarNombreGrupo").val(respuesta["nombre_grupo"]);
        $("#id_grupo").val(respuesta["id_grupo"]);

        var values = respuesta["permisos"].toString();
        values = values.split(",");
        $.each(values, function(i,e){
            $("#editarPermisos option[value='" + e + "']").prop("selected", true);
        })

    }

})
})

Ahora el siguiente código:
var values = ["Crear usuarios","Editar usuarios","Eliminar usuarios"].toString();
    values = values.split(",");
        $.each(values, function(i,e){
            $("#editarPermisos option[value='" + e + "']").prop("selected", true);
        })

Si lo pongo fuera de todo el ajax osea a raíz de grupos.js si funciona y hace lo que quiero que hiciera pero con array que traigo de la base de datos, ya que si se fijan en este pedacito he puesto un array manualmente, pero yo el mio el que quiero dentro de la respuesta ajax la traigo desde la base de datos
Anexo una imagen del resultado que me deberia de dar con la respuesta ajax

Espero me haya dado a entender y espero me puedan ayudar
La siguiente imagen es lo que me sale en consola después de hacer el split

A: Solo te faltaría agregar el refresh del duallist así:
$("#editarPermisos").bootstrapDualListbox('refresh');


text:
Q: VSCode c# autocomplete not working on an added package I am trying to build a library on top of and other library / framework.
I am doing this in C#, So at first i create a new project by doing
dotnet new console

Then i add the package which will serve as the basis for my library. I do this in the following way:
dotnet add package Veldrid

This works fine, i see it get added and it is visible in the .csproj
But then when i try to acces a function of a class or even create a new instance of a class from that package i see no autocomplete options what so ever :( But when i type my own class within the project its namespace autocomplete works all fine.
Why doesnt the autocomplete function work for added packages?
Extra information:
i am using a mac,
I have dotnet core 2.2.300 installed,
i am using vscode with the c# extension,
and in my project i have the using Veldrid added so i can use the package.
Let me know if something is unclear or extra information is needed!
side note:
I keep getting the message: Some projects have trouble loading. Please review the output for more details whenever i open a c# project in vscode.

A: after spending an age of googling and searching i found what was causing the problem for me.
I had unity installed which also installs the mono framework. (for me the mono framework caused all the problems). So i uninstalled unity and the removed the monoframework from my computer (mac) and all was well.
Hope this helps anyone in the future!
If there are better ways of going about this please let me know!


text:
Q: How do I split a list on certain conditions in Haskell? As a programming exercise I'm trying to build a function in Haskell where given a list it splits the list whenever an element is repeated. [1,2,3,3,4,5] would split into [[1,2,3],[3,4,5]] for example. My first idea was to split the list into a list of lists with single elements, where [1,2,3,3,4,5] would become [[1],[2],[3],[3],[4],[5]] and then merge lists only when the elements being compared are not equal, but implementing this has been a headache for me as I'm very new to Haskell and recursion has always given me trouble. I think something is wrong with the function I'm using to combine the lists, it will only ever return a list where all the elements that were broken apart are combined, where [1,2,3,3,4,5] becomes [[1],[2],[3],[3],[4],[5]] but my split_help function will transform this into [[1,2,3,3,4,5]] instead of [[1,2,3],[3,4,5]]
I've pasted my incomplete code below, it doesn't work right now but it should give the general idea of what I'm trying to accomplish. Any feedback on general Haskell code etiquette would also be welcome.
split_breaker breaks the list into a list of list and split_help is what I'm trying to use to combine unequal elements.
split_help x y
     | x /= y = x ++ y
     | otherwise = []

split_breaker :: Eq a => [a] -> [[a]]
split_breaker [] = []
split_breaker [x] = [[x]]
split_breaker (x:xs) = [x]:split_breaker xs

split_at_duplicate :: Eq a => [a] -> [[a]]
split_at_duplicate [x] = [[x]]
split_at_duplicate (x:xs) = foldl1 (split_help) (split_breaker [xs])

A: Do you want to work it something like this?
splitAtDup [1,2,3,3,3,4,4,5,5,5,5,6]
[[1,2,3],[3],[3,4],[4,5],[5],[5],[5,6]]

Am I right?
Then do it simple:
splitAtDup :: Eq a => [a] -> [[a]]
splitAtDup (x : y : xs) | x == y = [x] : splitAtDup (y : xs)
splitAtDup (x : xs) =
  case splitAtDup xs of
    x' : xs' -> (x : x') : xs'
    _ -> [[x]]
splitAtDup [] = []

A: Here's a maximally lazy approach:
splitWhen :: (a -> a -> Bool) -> [a] -> [[a]]
splitWhen f = foldr go [[]] where
  go x acc = (x:xs):xss where
    xs:xss = case acc of
      (z:_):_ | f x z -> []:acc
      _ -> acc

splitAtDup :: Eq a => [a] -> [[a]]
splitAtDup = splitWhen (==)

To verify the laziness, try this:
take 2 $ take 4 <$> splitAtDup (1:2:3:3:4:5:6:undefined)

It can be fully evaluated to normal form as [[1,2,3],[3,4,5,6]].


text:
Q: What is the best way to cache data in an EJB? I have some common data that all of my EJBs will need, so I decided to write 1 EJB to go and get the data, while the other EJBs will call the first EJB to get the data. Now I want to cache the data in the EJB so that it does not have to go back to the database each time it is asked for the data.
So, how do I cache the data in the EJB and maybe pull a fresh copy every 1 hour or so.
Can I do this with Ehcache? Or am I thinking about this all wrong, and there is a better way to do it.
Thanks

A: I think you must use the frameworks that already do this work. By example:

*

*If you are using JPA for access to database you can configure the cache in the persistence.xml and its will depend of your Persistence Provider (Hibernate, Toplink, etc).

*If you are using Hibernate it has support for third party Cache Frameworks like EHCache.

*Anyway you can configure EHCache  (or other similar) for do this work.

A: Yes you can use ehcache for that purpose but this is then still not 'cached' inside the EJB and remains inside the memory of the node the server is running on.
In a stateless EJB you only have this option whereas in a stateful EJB you could keep the data in the EJB (but having a stateful EJB for such a long time is just stupid), so this is not a really alternative.
One other approach is to use some data holder inside the EJB in a static manner. E.g. create a static map that keeps the data or a static list. Of course this is only per class loader, but as long as the class isn't removed from the classloader the static data stays there. This is then really inside the memory. For refreshing you could create a quartz job that periodically updates the data inside the static member.


text:
Q: Searching for a 3d engine. (Mac, cocoa) What 3d engines are avaliable for mac to use with cocoa? (xcode)?? A list of all would be great + a recommend
Thank you very much :)
EDIT:
In OpenGL. There is a 2d engine which uses opengl but i need a 3d engine for physics simulation in OpenGL. (shoot'em up)

A: Galaxy Engine meets all your requirements - Cocoa, 3D and OpenGL - and is free and open source.
http://code.google.com/p/galaxyengine/
EDIT: I read your edit and saw that you need physics as well. Bullet works well with Galaxy Engine, which unfortunately is lacking a physics model of its own: http://bulletphysics.org/wordpress/

A: A simple answer for a simple question: OpenGL.


text:
Q: Parsing html using JAVA (Jsoup) I am facing a problem in parsing html document using jsoup (Java). The HTML I'm parsing has this format:
.....

    Text 1

    Text 2

   Text 3

    Text

   Text

  ...

I want to isolate the HTML text between two "hr" tags. I am trying this code:
File input = new File("C:\\Users\\page.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
Elements body = doc.select("body");
Elements hrs = body.select("hr");
ArrayList<String> objects = new ArrayList<String>();
for (Element hr : hrs) {
  String textAfterHr = hr.nextSibling().toString();
  objects.add(textAfterHr);
}

System.out.println(objects);
but the ArrayList doesn't contain what I want, I don't know how to resolve it. (Could I transform the "hr" tag to "hr"text"/hr" tags)?

A: Here you get the result by reading the childrens of each hr tags. Use this for better solution.
ArrayList<String> objects = new ArrayList<String>();
Elements hrs = body.select("hr");
for(int i=0;i<hrs.size();i++){
 Element hrElm=hrs.get(i);
 Elements childrens=hrElm.children();
  for(Element child: childrens){
   String text=child.text();
   objects.add(text);
 }
}

A: public static void main(String[] args) throws ParseException, IOException {
    String html = ".....\n" +
                    "
\n" +
                    "    Text 1
\n" +
                    "
\n" +
                    "    Text 2
\n" +
                    "
\n" +
                    "   Text 3
\n" +
                    "
\n" +
                    "   \n" +
                    "
\n" +
                    "

\n" +
                    "    Text\n" +
                    "

\n" +
                    "
\n" +
                    "  \n" +
                    "
\n" +
                    "

\n" +
                    "   Text\n" +
                    "

\n" +
                    "
\n" +
                    "  ...";
    //Split your html string at each hr tag and keep the delimiter
    String [] splited = (html.split("(?=
)"));
    //join it back to a string using a closing hr tag
    html = String.join("
\n",splited);
    //use the jsoup xmlParser
    Document doc = Jsoup.parse(html,"",Parser.xmlParser());
    Elements eles = doc.select("hr");
    for(Element e : eles){
        System.out.println(e.html());
        System.out.println("-----------------------");
    }
}


text:
Q: MultiSelect TreeView in WPF I am new to WPF, I have to create multiselect treeview in WPF, I have found article
WPF TreeView with Multiple Selection , but I am not sure where to write. Do I need to write this code inside SelectedItemChanged event handler? Please advise.

A: You just need to call this method from the constructor of your window class after InitializeComponent().


text:
Q: Birt Report and How to display record on Excel using one sheet? I use a birt in my grails application. Currently exporting to excel works, but if let say:

*

*you have 100 records

it will:

*

*show 40 records in one sheet and you will end up having 3 sheets in your excel file.

I wanted to know how I can import them in one single sheet to:

*

*display all the 100 records.

I have Googled it. I can't come up with a clear solution to my IDEAS.

I use the following Code in my Birt:
def IRenderOption options = null
case ReportTypeEnum.XML:
    //TODO:
    options = new RenderOption(outputFormat: "xml")
    break

The emitter I use is :
options = new EXCELRenderOption(outputFormat: "xls")
optiions.setEmitterID("uk.co.spudsoft.birt.emitters.excel.XlsEmitter")
println "Report:"+ options.isEnableMultipleSheet()

Does anybody have any idea?
Example :

A: The solution was ain't to modify some code or to change emitters but ,simple as shown below
The real challenge could be setting this property on run time , by detecting the report Types,because you might not apply all paging stuff to all your pages ...

Thank you, Bini .
Refer this web Blog which has all the correct answers.
http://www.biny08.blogspot.com/2013/06/spudsoft-excel-emitter-single-sheet.html#more
Make
         Page Break Interval = 0 ( for unlimited ) or your custome Value
and set
         Repeat Header to false
Done! you will see all your  record in one sheet . Awsome :) !

A: I have been looking for the answer to that question for months, and finally found it by myself:
there is no need to write code, just consider this:
The XLSX export makes as much sheets as there are root items in the TOC or in the first groupment of a table. if only one item, you will get only one sheet.

*

*in your design, create an empty group in your main table, with the following specifications:

*name: Root

*group on: null (enter just these 4 letter in the field)

*table of content: 'Customer list' (any text you may want)
no problem if you have other groups, just place this one before the others (cut/paste)

Then you will get a TOC (table of content) with as first level, your group just containing the text you have defined.
This way, you also can keep the html view or pdf export with original pages, which is useful when you work with TOC for instance. Imagine having a 100 000 items population, you can create 3 groups:
- one null group with TOC text like 'Population'
- the second one containing just the first letter of name (you should get 26 items)
- the last one containing people names
then, you will have to manage only 100000/26=3846 items per sub group.
And for those who do want excel sheets, remember : the first group item count equals the excel sheet count....

A: Click on the data set. Open Property Editor for the same data set.
Go to Page Break option and give Page break interval to maximum number. I tried and 2147483647 was the maximum number BIRT designer takes.
Set options as below.
Before = Avoid,
Inside = Avoid,
After  = Always,
Master Page = None.

Tick the Repeat Header if you want the header to be available when data overflows to next sheet in excel after 2147483647 rows.
Attaching the screenshot for reference.
Click to open screenshot

A: This worked for me

*

*Select the entire table

*Go to Properties

*Select Page Break

*Set the Page Break Interval to 0

Done.


text:
Q: gitlab-ci parent-child include not working I'm trying to include another file with jobs (parent-child) but it's not doing anything:
.gitlab-ci.yml looks like this:
workflow:
  rules:
    - if: $CI_COMMIT_REF_NAME == "master" && $CI_PIPELINE_SOURCE == "schedule"
      variables:
        CODENAME: all
    - when: always

stages:
 - stage1
 - stage2

job1:
  stage: stage1
  rules:
    - if: $CI_COMMIT_REF_NAME == "master" && $CI_PIPELINE_SOURCE == "schedule"
    - changes:
      - job1/*
      variables:
        CODENAME: all
  trigger:
    include:
    - project: 'project-name'
      file: 'job1/pipeline.yml'

job2:
  stage: stage2
  rules:
    - if: $CI_COMMIT_REF_NAME == "master" && $CI_PIPELINE_SOURCE == "schedule"
    - changes:
      - job2/*
      variables:
        CODENAME: bionic
  trigger:
    include:
      - project: 'project-name'
        file: 'job2/pipeline.yml'

job1/pipeline.yml:
include:
  - project: 'project-name'
    file: file.yml

.template: &template
  extends: .kaniko-build # extend of the above include

job1-1:
  <<: *template
  rules:
    - if: '$CODENAME == "xenial" || $CODENAME == "all"'
      when: always
    - when: never
job1-2:
  <<: *template
  rules:
    - if: '$CODENAME == "bionic" || $CODENAME == "all"'
      when: always
    - when: never
job1-3:
  <<: *template
  rules:
    - if: '$CODENAME == "focal" || $CODENAME == "all"'
      when: always
    - when: never
job1-4:
  <<: *template
  rules:
    - if: '$CODENAME == "latest" || $CODENAME == "all"'
      when: always
    - when: never

job2/pipeline.yml:
include:
  - project: 'project-name'
    file: 'job1/pipeline.yml'

include:
  - project: 'project-name'
    file: file.yml

.template-custom-image1: &template-custom-image1
  extends: .kaniko-build # extend of the above include

custom-image1-1:
  <<: *template-custom-image1
  rules:
    - if: '$CODENAME == "xenial" || $CODENAME == "all"'
      when: always
    - when: never
custom-image1-2:
  <<: *template-custom-image1
  rules:
    - if: '$CODENAME == "bionic" || $CODENAME == "all"'
      when: always
    - when: never
custom-image1-3:
  <<: *template-custom-image1
  rules:
    - if: '$CODENAME == "focal" || $CODENAME == "all"'
      when: always
    - when: never
custom-image1-4:
  <<: *template-custom-image1
  rules:
    - if: '$CODENAME == "latest" || $CODENAME == "all"'
      when: always
    - when: never

Right now changes in job2 folder is triggering job2 which will trigger job2/pipeline.yml, all fine and dandy. But right now I only see one job meaning custom-image1-x. I'd expect to also see job1/pipeline.yml job1-x included as I include that in job2/pipeline.yml:
include:
  - project: 'project-name'
    file: 'job1/pipeline.yml'

I also have the requirement for them to run sequentially, so I can't use another trigger, as they'll run in parallel. Any clues or tipps how to tackle? Maybe I'm looking at this from the wrong angle?

A: secondly:
changes in job1/* should only trigger stage1's specific job in child pipeline. changes in job2/* however should trigger stage1 and then stage2 sequentially (depends) but with the variable defined in .gitlab-ci:
job2:
  stage: stage2
  rules:
    - changes:
      - job2/*
      variables:
        CODENAME: bionic

Sorry had to post this as an answer so it's properly formatted :-/

A: So my main issue was that I needed to run stage1 additionally when there are changes in stage2. I've fixed this with adding workflow rules with changes to stage2 (job2/*):
previously I had in my .gitlab-ci in job2:
job2:
  stage: stage2
  rules:
    - if: $CI_COMMIT_REF_NAME == "master" && $CI_PIPELINE_SOURCE == "schedule"
    - changes:
      - job2/*
  trigger:
    include:
      - project: 'project-name'
        file: 'job2/pipeline.yml'

which would trigger job2/pipeline.yml:
include:
  - project: 'project-name'
    file: 'job1/pipeline.yml'

include:
  - project: 'project-name'
    file: file.yml

.template-custom-image1: &template-custom-image1
  extends: .kaniko-build # extend of the above include

custom-image1-1:
  <<: *template-custom-image1
custom-image1-2:
  <<: *template-custom-image1
custom-image1-3:
  <<: *template-custom-image1
custom-image1-4:
  <<: *template-custom-image1

On top you notice an include for job1/pipeline.yml
include:
  - project: 'project-name'
    file: 'job1/pipeline.yml'

Which I somehow expected to magically execute - without an extend or anything but it never executed. I fixed this like this in .gitlab-ci:
workflow:
  rules:
    - changes:
      - job2/*
      variables:
        SET_STAGE: TWO
        CODENAME: bionic
...

job1:
  stage: stage1
  rules:
    - if: $SET_STAGE == "TWO"
    - if: $CI_COMMIT_REF_NAME == "master" && $CI_PIPELINE_SOURCE == "schedule"
    - changes:
      - job1/*
  trigger:
    include:
      - project: 'project-name'
        file: 'job1/pipeline.yml'
    strategy: depend

job2:
  stage: stage2
  rules:
    - if: $CI_COMMIT_REF_NAME == "master" && $CI_PIPELINE_SOURCE == "schedule"
    - changes:
      - job2/*
  trigger:
    include:
      - project: 'project-name'
        file: 'job2/pipeline.yml'
    strategy: depend

So really all I did is on top in my .gitlab-ci I defined workflow rules that would set a variable (SET_STAGE) on changes in job2/* and use that variable in my first stage. If it's set than it will run that stage as well. Of course I could have solved it this way:
...
    - changes:
      - job1/*
    - changes:
      - job2/*
...

instead of this:
...
    - changes:
      - job1/*
    - if: $SET_STAGE == "TWO"
...

But I needed to set an overall common variable (CODENAME) somewhere anyway which I'm doing in workflows and moved that into separate file, thus making my .gitlab-ci file a bit slimmer.
It looks really simple but it took me a while to figure that out. The Matrix mentioned by Simon in the first post comments is interesting but for my use-case not really useful. So I kept it the way it is and that's working fine. Another issue I solved within this thread was with "strategy: depend" so stage1 and stage2 would not execute in parallel. Thanks everyone for helping! :-)


text:
Q: Is the distribution of prime numbers chaotic? The distribution of prime numbers, at first glance, appears to be somewhat random. It is however, deeply structured and deterministic. Does this qualify it as chaotic.
As chaotic is somewhat of a loose term, I will use the following definition: when the initial conditions determine later conditions, but the approximate initial conditions do not approximately determine later conditions. To be more clear, I will break this question down into three parts:

*

*Can particular "conditions" be identified for prime numbers? Again this is hard to answer, but maybe there are similar distributions that prime numbers can be compared to.

This aleads to the next question,

*Do the initial conditions determine the later conditions?

And

*Do approximate initial conditions not approximate later conditions

A: As Gerry Myerson already noted in a comment, to talk about the chaoticity of anything, you first have to embed it into the framework of dynamical systems. At the very least, you have to have:

*

*some notion of state of a system (this may be what you understand by condition),

*some dependence of future states on present states,

*some notion of distance between possible states.

Applying the first point to prime numbers already requires making some very loose associations creativity. There are no different states of prime numbers; they just are.
You could consider an individual prime number as a state of a system and the function $n$ that maps a prime number to the next prime number as your temporal relation between states. But then all you can modify about your sequence is where in the sequence you start – the sequence itself is fixed. The best approximations of a state $p_i$ are its predecessor $p_{i-1}$ and successor $p_{i+1}$. If you insist continuing with this, the best approximations of the present state do allow for the best approximation of the future states. For example, if the present state is $p_i$ the future state after $k$ iterations is $n^k(p_i) = p_{i+k}$ and the respective future states the best approximations of the present state are $p_{i+k-1}$ and $p_{i+k+1}$, which happen to be the best approximations of the future state. But keep in mind that this is already stretching the perspective a lot.

Is the distribution of prime numbers chaotic?

What is that even supposed to mean? I never heard anybody apply the term chaotic to distributions. It's dynamics that can be chaotic.


text:
Q: Use regular expression to match characters appearing in Traditional Chinese ONLY \p{Han} can be used to match all Chinese characters (in the Han script), which mix both Simplified Chinese and Traditional Chinese.
Is there a regular expression to match only the characters unique in Traditional Chinese? In other words, match any Chinese characters except for the ones in Simplified Chinese. Things like (?!\p{Hans})\p{Hant}.
Furthermore, ideally, if the regular expression can also exclude Japanese Kanji, Korean Hanja, Vietnamese Chữ Nho and Chữ Nôm.

A: Because Traditional Chinese characters are not continuous on the Unicode table, there is unfortunately not a simple Regex rather than testing them one by one, unless things like \p{Hant} and \p{Hans} are supported by Regex.
Inspired by the answer^ pointed by @jdaz's comment, I wrote a Python script using hanzidentifier module to generate the Regex that matches the characters unique in Traditional Chinese&:
from typing import List, Tuple

from hanzidentifier import identify, TRADITIONAL

def main():
    block = [
        *range(0x4E00, 0x9FFF + 1),  # CJK Unified Ideographs
        *range(0x3400, 0x4DBF + 1),  # CJK Unified Ideographs Extension A
        *range(0x20000, 0x2A6DF + 1),  # CJK Unified Ideographs Extension B
        *range(0x2A700, 0x2B73F + 1),  # CJK Unified Ideographs Extension C
        *range(0x2B740, 0x2B81F + 1),  # CJK Unified Ideographs Extension D
        *range(0x2B820, 0x2CEAF + 1),  # CJK Unified Ideographs Extension E
        *range(0x2CEB0, 0x2EBEF + 1),  # CJK Unified Ideographs Extension F
        *range(0x30000, 0x3134F + 1),  # CJK Unified Ideographs Extension G
        *range(0xF900, 0xFAFF + 1),  # CJK Compatibility Ideographs
        *range(0x2F800, 0x2FA1F + 1),  # CJK Compatibility Ideographs Supplement
    ]
    block.sort()

    result: List[Tuple[int, int]] = []

    for point in block:
        char = chr(point)
        identify_result = identify(char)
        if identify_result is TRADITIONAL:
            # is traditional only, save into the result list
            if len(result) > 0 and result[-1][1] + 1 == point:
                # the current char is right after the last char, just update the range
                result[-1] = (result[-1][0], point)
            else:
                result.append((point, point))

    range_regexes: List[str] = []
    # now we have a list of ranges, convert them into a regex
    for start, end in result:
        if start == end:
            range_regexes.append(chr(start))
        elif start + 1 == end:
            range_regexes.append(chr(start))
            range_regexes.append(chr(end))
        else:
            range_regexes.append(f'{chr(start)}-{chr(end)}')

    # join them together and wrap into [] to form a regex set
    regex_char_set = ''.join(range_regexes)
    print(f'[{regex_char_set}]')

if __name__ == '__main__':
    main()

This generates the Regex which I've posted here: https://regex101.com/r/FkkHQ1/5 (seems like Stack Overflow doesn't like me posting the generated Regex)
Note that because hanzidentifier uses CC-CEDICT, and especially it is not using the latest version of CC-CEDICT, definitely, some Traditional characters are not covered, but should be enough for the commonly used characters.
Japanese Kanji is a large set. Luckily, the Japanese Agency for Cultural Affairs has a list of commonly used Kanjis and thus I created this text file for the program to read. After excluding the commonly used Kanjis, I got this Regex: https://regex101.com/r/FkkHQ1/7
Unfortunately, I couldn't find a list of commonly used Korean Hanja. Especially, Hanja are rarely used nowadays. Vietnamese Chữ Nho and Chữ Nôm have almost been wiped out as well.

Footnote:
^: the Regex in that answer doesn't match all Simplified characters. To get a Regex that matches all Simplified characters (including the ones in Traditional Chinese as well), change if identify_result is TRADITIONAL to if identify_result is SIMPLIFIED or identify_result is BOTH, which gives us the Regex: https://regex101.com/r/FkkHQ1/6
&: this script doesn't filter Japanese Kanji, Korean Hanja, Vietnamese Chữ Nho or Chữ Nôm. You have to modify it to exclude them.


text:
Q: jQuery multiple buttons with this same id I have a problem with multiple buttons with this same id. When i click one of buttons, it works only for id=1 (When I enter something in the text field and press any button, in each case only the record with id = 1 will be updated). How to solve this problem?
div id="ShowPrace">
<?php
try {
  $stmt = $pdo->prepare("SELECT * FROM prace");
  $stmt->execute(array());
  $count = $stmt->rowCount();
  while($row = $stmt->fetch(PDO::FETCH_ASSOC)){

?>

  <textarea class="form-control" name="id" rows="1" id="id"><?php echo $ind; ?></textarea>

    Link do obrazka:
    <textarea class="form-control" name="link" rows="1" id="link"><?php echo $row['img']; ?></textarea>

    Tytuł:
    <textarea class="form-control" name="title" rows="1" id="title"><?php echo $row['title']; ?></textarea>

    Opis:
    <textarea class="form-control" name="opis" rows="1" id="opis"><?php echo $row['opis']; ?></textarea>

    <button type="submit" id="poprawa" name="poprawa" class="btn btn-primary"> Popraw</button>

  <?php
    }

  } catch (\Exception $e) {
      echo "Wystąpił nieoczekiwany błąd!";
  }
  ?>

And JS:
("#poprawa").click(function(){

var link = $("#link").val().trim();
var title = $("#title").val().trim();
var opis = $("#opis").val().trim();
var id = $("#id").val().trim();

$.ajax({
  url: 'update_prace.php',
  type: 'POST',
  data: {link:link, title:title, opis:opis, id:id},
  success: function(response){
    if(response == 0){
      alert("error");
    }
    else{
      alert("Poprawione!");
      location.reload();
    }
  }
});

});

A: IDs are unique and cannot be repeated.  You should use a class in your DOM instead and change your selector accordingly
HTML:
<button type="submit" name="poprawa" class="btn btn-primary poprawa"> Popraw</button>

JS:
$(".poprawa").click(function(){

For instance.

A: You have to differenciate ids because an id is unique.
You can do something like :
<?php
    ...
    $i=0;
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
...
<textarea class="form-control" name="id" rows="1" id="id-"<?php $i ?>>
...
<?php
    }
    $i++;
    } catch (\Exception $e) {
       echo "Wystąpił nieoczekiwany błąd!";
    }
?>

$i allowed to change ids for each loop.


text:
Q: How to organize Objects using an Integer parameter Say I have an Object composed of a String and an Integer. How would I make an ArrayList<Object> with the objects with the highest integer value first and lowest last?

A: You could sort them with a customer Comparator based on that property. With Java 8's enhancements, it should be pretty elegant:
myList.sort(Comparator.comparingInt(MyObject::getIntegerProperty).reversed());


text:
Q: socket.io multiple line message issue We are using socket.io@1.3.5 and Socket.IO-Client-Swift to implement a chat application. Everything works okay when a one line message is send. socket.io-parser parses the packet and process it.

  engine handling "POST" http request "/socket.io/?transport=polling&sid=D4hHosMaFHKF2xZAAAAA" +0ms
  engine setting new request for existing client +1ms!
  engine:polling received "20:42["message","test"]" +0ms
  engine:socket packet +0ms
  socket.io-parser decoded 2["message","test"] as {"type":2,"nsp":"/","data":["message","test"]} +8.2m
  socket.io:socket got packet {"type":2,"nsp":"/","data":["message","test"]} +6m
  socket.io:socket emitting event ["message","test"] +0ms

But when I try to send a two line message, it fails to decode it;

  engine handling "POST" http request "/socket.io/?transport=polling&sid=D4hHosMaFHKF2xZAAAAA" +0ms
  engine setting new request for existing client +0ms
  engine:polling received "27:42["message","test2
test3"]" +1ms
  engine:socket packet +0ms
  socket.io:client no socket for namespace undefined +1m

What would be a possible solution for the issue?
Thank you
Edit:
I trim the text that I get from the input box if it is more than 255 chars

if (text.length > 255) { // trim the text longer than 255
    text = [text substringToIndex:255];
}

And then I emit it with a "message" event;
[_socket emit:@"message" withItems:@[text]];

It seems in the NSLog as below;
2015-05-23 23:36:43.580 TestApp[383:3300397] Text: test3
test4

I am not removing new line or any other special characters (which I should maybe)
Edit 2:
I've checked my old configuration Socket V0.9 and it looks line client sends the message as "test1\ntest2", I am not sure if the issue belongs the client or the server. Is it related with the header content-type?

A: Issue solved by adding "\r\n" characters manually.
Obviously old implementation that I am using (https://github.com/pkyeck/socket.IO-objc) was doing that automatically. But the new implementation (https://github.com/nuclearace/Socket.IO-Client-Swift) that have to be done in your code.


text:
Q: How to execute an SSIS package through Excel Macro when SQL Server BIDS is installed on a remote machine and NOT locally? I have a typical case here when I don't have SQL Server BIDS (Business Intelligence Development Studio) application installed on my PC and I want to run/execute a .dtsx package file using an excel macro which will launch the BIDS instance residing on a CITRIX server (remote machine) and use the package configuration file (XML config file) to execute it.
I NEITHER have SQL Server installed on my PC from where I could atlease create a SQL Agent job and schedule the package execution programmatically or use the Command line statements to execute the package from DOS prompt.
Please help me out as I need to find a solution to this ASAP. Thanks!!

A: Assuming that the server is not so remote that you can't talk to it at all, the usual approach would be to set up an agent job to run the package, then find a way to trigger the job.  There's a good discussion of this in this Microsoft article.
The most straight-forward way requires opening a DB connection to the server and running sp_start_job (which means you need credentials which will allow this), as described in the article - but there's obviously multiple other ways to fire off a job.


text:
Q: How to make single copy of an activity over entire application Here i have opened activity in following order
A->B->C->D
now i just want to re-launch activity B so that order becomes:
A->C->D->B
can anyone please tell me that how can i achieve this state in android.
Thanks in advance.

A: Do this in your manifest file for activity B:
<activity
   android:name=".B"
   android:launchMode="singleTask"/>

A: now you have A B C D in your app
try the following below:
Intent intent = new Intent(xxx.this, B.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

also check file in here


text:
Q: Visual Studio Crashing When I Select Text in Code Editor I have exactly the same problem as this SO poster; Visual Studio Crashing When I Select Text in Code Editor, except I'm running Windows 7 Ultimate and the fix for bulltorious isn't workable for me on Windows 7.
Event Viewer reports the error as;
Fault bucket 1097131459, type 5
Event Name: CLR20r3
Response: Not available
Cab Id: 0

Problem signature:
P1: devenv.exe
P2: 10.0.30319.1
P3: 4ba1fab3
P4: UIAutomationProvider
P5: 4.0.0.0
P6: 4ba1f837
P7: 3
P8: 0
P9: System.DllNotFoundException
P10:

I can't select any text in any file type. If I attempt to add or edit any code, I crash to desktop. I have done Windows Update and updated the usual drivers just in case. No luck.
I have no add-ins running and I've tried running devenv /safemode, with no success.  I know this has something to do with UIAutomationProvider, but with no idea how to fix it!
Any ideas?
I did post on Microsoft's Connect, but that was useless: https://connect.microsoft.com/VisualStudio/feedback/details/618754/visual-studio-2010-crash-on-code-view-load

A: Reverse-engineering the Watson dump, it is crashing in MS.Internal.Automation.UiaCoreProviderApi.RawUiaClientsAreListening.  This is a pinvoked function from UIAutomationCore.dll
You'll need to find out what happened to that DLL.  It is present in c:\windows\system32, mine has a time-stamp of July 13th 2009, 6:27:31 pm CST.


text:
Q: The form of a set of positive integers that contains $k+1$ whenever it contains $k$ I've seen there are lots of proofs by mathematical induction on the site, yet I haven't seen a problem like mine (or at least couldn't pattern my problem after the other).
"Let $m$ be the smallest element of set $A\subseteq\mathbb{N}$. If $k+1$ is the element of $A$ whenever a natural number $k$ is, then $A=\{n\in\mathbb{N}:n\geq m\}$."

I think I should create another set for which only the first part of the problem is true, but not $$A=\{n\in\mathbb{N}:n\geq m\}.$$ Then conclude from the former information that this is really true.

(1) Let's assume $a=m$; since $m\in A\subseteq\mathbb{N}$, $a$ is a natural number in $A$.
(2) Let $K\subseteq\mathbb{N}$, let $m$ be its smallest element, and for all $k\in K$ there's $k+1$ in $K$. For this set (1) also holds, since some $k=m$ must be the element of $K$.
(3) If $m$ is the smallest element of $K$, then $m+1$ is the next element in the set ($m+1\in K$), and so on. This is true because of the assumption (2) "for any natural $k\in K$ there's $k+1\in K$". Therefore now we know that $K$ contains all natural numbers $k$, starting from $m$: $$K=\{k\in\mathbb{N}:k\geq m\}.$$
Is this a good proof? If someone could drop a hint I'd be glad.

A: You're making it more complicated than it needs to be. I'm not at all sure what part (1) is about, for example.
Note that since $m$ is the smallest element of $A$ and $A\subseteq\Bbb N,$ then we can immediately conclude that $$A\subseteq\{n\in\Bbb N:n\ge m\}.\tag{$\star$}$$ This is because if $a\in A,$ then $a\in\Bbb N$ since $A\subseteq\Bbb N,$ and $a\ge m$ since $m$ is the least element of $A;$ thus, $a\in\{n\in\Bbb N:n\ge m\},$ and since this holds for all $a\in A,$ then $(\star)$ holds.
All that remains is to show that if $n\in\Bbb N$ such that $n\ge m,$ then $n\in A,$ from which the reverse inclusion of $(\star)$ follows, and so we have equality. That's where induction comes in handy. The idea is to note that if $n\in\Bbb N$ and $n\ge m,$ then either $n=m$ or $n=m+k$ for some positive integer $k.$ Proceed by induction on $k$ to show that all such $n$ are elements of $A.$
Let me know if you have any trouble, or just want to check your reasoning.

A: I don't know how to merge accounts, and that one was made without login. (roro) I tried, but it says my profile link is invalid... whatever. Now I cannot comment on that answer. I'm sorry I'm doing exactly what is against the rules (replying to the answer in "an answer", but I figured, because I've already chosen the best one, this won't hurt).

I didn't see that you used "$\subseteq$" instead of "$=$". ...
Natural number is a positive integer. Set of natural numbers is a set with $1$ as a starting number, and the next number is bigger by $1$ from the previous.


text:
Q: How to make points representing a 2D line denser in Python # imports
import numpy as np
import matplotlib.pyplot as plt

Problem
I have  a 2 arrays, representing datapoints on a line. For example:
x = np.array([0,1,2])
y = np.array([5,6,4])

Plot the data:
plt.plot(x,y)
plt.scatter(x,y,c='r')

Get:

I'd like to have arrays where the datapoints represent the same lines as above, but they are doubled. The desired result is:
new_x = np.array([0,0.5,1,1.5,2]) # this is the result I am looking for
new_y = np.array([5,5.5,6,5,4]) # this is the result I am looking for

Plot:
plt.plot(new_x,new_y)
plt.scatter(new_x,new_y,c='r')

Result:

My attempt
My method of doing this:
x = np.array([0,1,2])
y = np.array([5,6,4])

new_x=[]
for index, each in enumerate(x):
    if index!=0:
        new_x.append((each+x[index-1])/2)

new_y=[]
for index, each in enumerate(y):
    if index!=0:
        new_y.append((each+y[index-1])/2)

new_x.extend(x)
new_y.extend(y)

Plot:
plt.plot(new_x,new_y)
plt.scatter(new_x,new_y,c='r')

Result:

Points are in the right place, the new points added are the correct points, but they are put into the new_x & new_y arrays in the wrong order. It is fixable by paying more attention to the .extend, but this does not seem a good method to me anyway, because of the iteration.

My research

*

*linear interpolation between two data points: doesn't use 2D arrays

*How to write a function that returns an interpolated value (pandas dataframe)?: deals with interpolated values of functions, not resampling lines as above

And there are some other questions with the [interpolation] tag, but I haven't found one descibing this problem above.

Question
How do I get the above described new_x and new_y, preferably without iteration?

A: You could use these one-liner list comprehensions:
new_x = [j for i, v in enumerate(x) for j in [v, (x[i] + x[(i + 1 if (len(x) - 1) != i else i)]) / 2]]
new_y = [j for i, v in enumerate(y) for j in [v, (y[i] + y[(i + 1 if (len(y) - 1) != i else i)]) / 2]]
plt.plot(new_x, new_y)
plt.scatter(new_x, new_y, c='r')
plt.show()

Output:


text:
Q: Lisp: cycle through functions I use elfeed to read RSS in emacs and want to make a function that cycle through different views: news, 9gag, nonnews etc.
I have tried to make some code via quick research. When I press ctrl + right arrow key it cycle through the views. It works fine, but I don't think it is the most convenient code.
I also want to make it go reverse through the views when pressing ctrl + left arrow key.
;;cycle through views
(setq a 0)
(defun cycle-list-view ()
  (interactive)
  (if (= a 3)
    (progn
    (elfeed-read-9gag)
    (setq a 4)
    ))
  (if (= a 2)
    (progn
    (elfeed-read-nonnews)
    (setq a 3)
    ))
  (if (= a 1)
    (progn
    (elfeed-read-news)
    (setq a 2)
    ))
  (if (= a 0)
    (progn
    (elfeed-read-defaultnews)
    (setq a 1)
    ))
  (if (= a 4)
    (progn
    (setq a 0)
    ))
  )

 (global-set-key (kbd "<C-right>") 'cycle-list-view)

A: You should probably put the data in a separate variable, and have your code simply maintain a global index variable into that structure.  Perhaps like this:
(defvar elfeed-views-list "List of views for `elfeed-cycle-views'.
Each member should be a cons of a label string and a function.
`elfeed-views--index' is a pointer into this structure."
  (("default" . #'elfeed-read-defaultnews)
   ("news" . #'elfeed-read-news)
   ("nonnews" . #'elfeed-read-nonnews)
   ("9gag" . #'elfeed-read-9gag)))

Adding a new view no longer requires code changes -- just push another item to the end of this list.
Now all the cycling function needs to do is increment or decrement an index into this structure, and take care of wrapping if you go past the end:
;; The double dash in the name suggests a private variable
(defvar elfeed-views--index "Index into `elfeed-views-list' for `elfeed-cycle-views'.
Use that function to manipulate the index." 0)

(defun elfeed-cycle-views (&optional skip)
  "Update `elfeed-views--index' by adding SKIP (default 1) and
wrapping if necessary, then call the function at this index in
`elfeed-views-list'."
  (interactive)
  (setq elfeed-views--index (+ elfeed-views-index (or skip 1)))
   ;; BUG: skips with an absolute value bigger than 1 don't wrap properly.
  (if (>= elfeed-views--index (length elfeed-views-list))
    (setq elfeed-views--index 0)
   (when (< elfeed-views--index 0)
     (setq elfeed-views--index (1- (length elfeed-views-list))) ))
  (eval (cdr (nth elfeed-views--index elfeed-views-list))) )

Cycling the other way can now simply be achieved by passing -1 as the SKIP parameter.
(Untested, but at least this should give you ideas.)
As a stylistic aside, you want to learn about cond instead of the ghastly sequence of if statements.  You apparently had to force an unintuitive reverse sorting order of your code because you did not know about this control structure.

A: It looks like tripleee's answer will work for the general question you asked (regarding how to cycle through a list of functions).  For the specific question (cycling through Elfeed filters), I wrote an implementation of this for myself a while back, and thought I'd post it here in case it's of use to you.
Without seeing the code you're calling (e.g., elfeed-read-news) it's hard to say how this differs from your implementation, but I'm guessing you don't need to have all of your views written up as separate functions (unless you also want a command to jump straight to a particular view).
Also, I should note that my implementation uses the dash library, which you can find on MELPA.
(defvar my/elfeed-favorite-filters
  '("@6-months-ago +unread"
    "+todo")
  "A list of commonly-used filters for Elfeed.
Use `my/elfeed-search-next-favorite-filter' to cycle through
these.")

(defun my/elfeed-search-next-favorite-filter (&optional verbose)
  "Apply the next filter in `my/elfeed-favorite-filters'.

If the current search filter is an element of
`my/elfeed-favorite-filters', apply the filter immediately
following that one in the list, looping back to the beginning if
necessary.

If the current search filter is not an element of
`my/elfeed-favorite-filters', apply the first filter in the
list.

If `my/elfeed-favorite-filters' is empty, just apply the default
filter.

Return the filter applied.  When called interactively or the optional
VERBOSE parameter is non-nil, also print a message informing the user
of the newly applied filter."
  (interactive "p")
  (let ((new-filter
         (my/successor-in-list my/elfeed-favorite-filters
                                elfeed-search-filter :cyclical)))
    (elfeed-search-set-filter new-filter)
    (when verbose (message "Filter applied: %s" elfeed-search-filter))
    elfeed-search-filter))

(defun my/successor-in-list (list elt &optional cycle)
  "Return the element in LIST following ELT.
If ELT is not an element of LIST, return nil.

If ELT is the last element in LIST, return (car LIST) if the
optional parameter CYCLE is non-nil; otherwise, return nil."
  (require 'dash)                       ; For `-drop-while'
  (let ((found  (-drop-while (lambda (x) (not (equal x elt)))
                             list)))
    (cond
     ((null found)                   nil)
     ((or (cdr found) (null cycle))  (cadr found))
     (:else                          (car list)))))

I don't use a "cycle backward" command, but it's pretty easy to tack one on:
(defun my/elfeed-search-prev-favorite-filter (&optional verbose)
  "Apply the previous filter in `my/elfeed-favorite-filters'.

As `my/elfeed-search-next-favorite-filter', but cycle backwards."
  (interactive "p")
  (let ((my/elfeed-favorite-filters (reverse my/elfeed-favorite-filters)))
    (my/elfeed-search-next-favorite-filter verbose)))


text:
Q: API Platform - No identifiers defined for resource of type I have an Doctrine Entity Class identified by an iso_code attribute :
/**
 * @ApiResource(
 *     graphql={
 *          "item_query",
 *          "collection_query"
 *     }
 * )
 *
 * @ORM\Entity(repositoryClass="App\Repository\LanguageRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Language extends BaseEntity
{
    /**
     * @var string
     * @ApiProperty(identifier=true)
     *
     * @ORM\Id()
     * @ORM\Column(type="string", length=2, unique=true)
     */
    private $iso_code;

    public function getId(): string
    {
        return $this->iso_code;
    }

    public function getIsoCode(): string
    {
        return $this->iso_code;
    }
}

When I try to access a list through a GET requests /api/v2/languages?pages=1, I got "No identifiers defined for resource of type \"App\\Entity\\Language\"" error.
When I try to access an item through a GET requests /api/v2/languages/en, I got Invalid identifier value or configuration
Configuration:
- api platform v2.5.6
- php 7.4
- symfony 4.4

A: You have to add
App\Entity\Language
  properties:
    id:
      identifier: false
    iso_code:
      identifier: true

A: Solved similar issue by setting identifier   @ApiProperty(identifier=true)   on top of the
getter function

A: Changing the name of the identifier to $id did the trick.
But I can't get why it's not possible to use $iso_code


text:
Q: Combining Multiple Events in RX I have 2 touch enabled Canvas' in a Silverlight App.  What I need to do is when a person Holds (presses and keeps pressing) both canvases at the same time increment a value on the screen once. This should happen for every "double" hold.  I can do that fine using normal events but tried writing the same thing using RX and I am getting stuck.
Currently my code looks identical to the separate events approach (using global variables and global method) but I think there must be a better way to compose this.  Can anyone suggest a better approach?
        var leftHold = Observable.FromEvent<TCanvas.HoldHandler, GestureHoldEventArgs>(
                h => new TCanvas.HoldHandler(h),
                h => HoldLeft.Hold += h,
                h => HoldLeft.Hold += h
            );

        var rightHold = Observable.FromEvent<TCanvas.HoldHandler, GestureHoldEventArgs>(
                h => new TCanvas.HoldHandler(h),
                h => HoldRight.Hold += h,
                h => HoldRight.Hold += h
            );

        var rightRelease = Observable.FromEvent<TCanvas.ReleaseHandler, EventArgs>(
                h => new TCanvas.ReleaseHandler(e => { }),
                h => HoldRight.Release += h,
                h => HoldRight.Release += h
            );

        var leftRelease = Observable.FromEvent<TCanvas.ReleaseHandler, EventArgs>(
                h => new TCanvas.ReleaseHandler(e => { }),
                h => HoldLeft.Release += h,
                h => HoldLeft.Release += h
            );

        leftHold.Subscribe(e =>
        {
            _leftHeld = true;
            DoCheck();
        });

        rightHold.Subscribe(e =>
            {
                _rightHeld = true;
                DoCheck();
            });

        rightRelease.Subscribe(e =>
        {
            _rightHeld = false;
            DoCheck();
        });

        leftRelease.Subscribe(e =>
        {
            _leftHeld = false;
            DoCheck();
        });

And the very basic DoCheck function looks like this....
    private void DoCheck()
    {
        if (_rightHeld && _leftHeld)
        {
            MyTextBox.Text = (Convert.ToInt32(MyTextBox.Text) + 1).ToString() ;
        }
    }

Hopefully you can see what I am trying to do.  Each canvas has a hold and release event so when HoldLeft and HoldRight are both held do something until either HoldRight or HoldLeft are is released.
Any help would be appreciated.

A: I believe I have solved my own problem.
Rather than the multiple subscribes I went for this.
        leftHold.Zip(rightHold, (a,b) => true)
            .TakeUntil(leftRelease.Amb(rightRelease))
            .Subscribe(_ => TextOutput.Text = (Convert.ToInt32(TextOutput.Text) + 1).ToString());

It appears to do what I want but I am open to further suggestions/improvements.

A: I came across this answer and thought that it didn't make sense:
    leftHold.Zip(rightHold, (a,b) => true)
        .TakeUntil(leftRelease.Amb(rightRelease))
        .Subscribe(_ => TextOutput.Text =
            (Convert.ToInt32(TextOutput.Text) + 1).ToString());

*

*Zip pairs up events so would
require that I release the left and
the right before holding them again.
If I released right and the held it
again this observable wouldn't fire
again.

*I also would think that the hold
events only fire once, so there
shouldn't be any need for a
TakeUntil call.

*Also I don't see how this answer will
refire - it seems to get only one
value.

Here's an alternative:
var left = leftHold.Select(x => true).Merge(leftRelease.Select(x => false));
var right = rightHold.Select(x => true).Merge(rightRelease.Select(x => false));

var bothHold =
    left.CombineLatest(right, (l, r) => l && r)
        .Where(lr => lr == true)
        .Select(lr => (Convert.ToInt32(MyTextBox.Text) + 1).ToString());

bothHold.Subscribe(t => MyTextBox.Text = t);

I know this question is a year old, but I would love to know if I've missed something or if this answer works.


text:
Q: deleting a record leading to loss of records in another table There is a many-to-many relationship between
products & suppliers
 (joining table is products_suppliers).
Since every supplier has a price of a product, and this price may also change, I have the following relationship as well:
products_suppliers <-> unit_prices (1:N).
Now, if I want to break the relationship between a product & a supplier (e.g. bec. the supplier doesn't supply the product any more), I would delete the one record in the products_suppliers table. However, this will destroy the access to the price history of the product from that supplier.
How to do this properly?
I have a problem in the deletion part. I don't know how to deal with it. Please help.

A: Consider adding a field to your products_suppliers table, which you can use to indicate whether the product-to-supplier relationship is still active. You could call it "active", or reverse the logic and call it "archived" or "inactive".
This will probably force you to change your queries in other parts of the application, but it will allow you to preserve that link to your price history table. It also has the advantage that if a supplier starts to carry a product again, then you just change the flag in the products_suppliers table again.


text:
Q: Should I backup from within each guest, or from the host? I'm searching for advice on whether backups are better taken from within a guest (e.g. ShadowProtect), or from within the host (e.g. copying virtual disk files, or other software).
We have 12 VM's (a mixture of Win2012, Win2008, and Debian) running on a pair of oVirt (KVM) nodes.  Storage is on an HP P2000 SAN, and backup space is available on a FreeNAS server.
Currently I'm considering a two-pronged approach:

*

*Host-based homegrown script to shutdown the VM's and rsync the qcow2 file to the backup server weekly

*Use guest-based software to backup time-critical data on the email server & file server every hour

It feels like there should be A Better Way™, particularly considering the homegrown script.
Should I focus on host-based backups, guest-based backups, or a combination of the two?

A: Ever considered using technology applicable for the job? I can not imagine a backup that requires the VM to be turned off and then is done via a hodge podge script, instead of having a backup software that integrated with the hypervisor.
Plus, this is not nevessarily "either or". I use Hyper-V and we do machine backups from the host twice per day - BUT: critical data within the VM's is backed up every 15 minutes by agents in the VM. This gives me for a databsae server a twice per day system image and a 15 minute accurate database backup.
From about 30 or so VM's 4-5 have agents installed. ALL are backed up from the host twice per day.
And drop the scripts - here is backup management software around.

A: It is better to backup the virtual machines themselves. The host should be disposable.
If you ever have to rebuild the hardware, a machine backup can be problematic. Also, if you need to restore an individual VM then your only option is to restore the whole thing.
There are many products out there that support backing up running virtual machines.


text:
Q: No storing Cookies with php cURL I have some problems with cookies, I need to store it, and after that use it, here is my code, but i don't know why it don't store it.
there are any mistake ?
$uagentutilitzat = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, "http:\\www.domain.com");
curl_setopt ($ch, CURLOPT_VERBOSE, 0);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLINFO_HEADER_OUT,true);
curl_setopt ($ch, CURLOPT_USERAGENT, $uagentutilitzat);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt ($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt ($ch, CURLOPT_REFERER, "http:\\www.domain.com");
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS,'entradaDesde=AVISO_SEG_FIRMA&mensajeXML=&hojaEstilos=..%2F..%2FEstatico%2FComunesSEI%2FStyles%2Festilo_e.css&imagenes.flecha=flecha_e.gif');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output=curl_exec($ch);

ths a lot !


text:
Q: Why does JUnit not execute the whole method? How come the second Assert is never executed. I mean Assert does not throw an exception. So why is the method interrupted. It has no return value as well.
 @Test
 public void testReverse2()
 {
     Assert.assertEquals(1.0, 2.0,0);

     Assert.assertEquals(4.0, 5.0,0);
 }

A: Actually, assertEquals does throw an Exception when it fails. In Your case it will always fail since You are comparing 1.0 with 2.0 with delta of 0.0. So, it will always throw AssertionError and will never execute the second check.

A: According to the documentation will interrupt if not equals and if you want to execute the whole assertion you can use ErrorCollector
Note: equalTo in org.hamcrest.CoreMatchers from hamcrest library
public class TargetTest {

    @Rule
    public ErrorCollector collector = new ErrorCollector();

    @Test
    public void testReverse2() {
        collector.checkThat(1.0, equalTo(2.0));
        collector.checkThat(4.0, equalTo(5.0));
    }
}


text:
Q: conditional column in M query if text.contain using OR function I added a column in powerquery and the conditionals contain texts with varying values. I can add each phrase for each conditional but I am thinking of writing it in a more efficient way using the OR function.
so far I have the following:
= Table.AddColumn(#Changed Type", "Assigned Group", each if Text.Contains([Assigned to], "John") Then "Group 1" else if Text.Contains([Assigned to], "johnny") Then "Group 1" else if Text.Contains([Assigned to], "jane") Then "Group 1" else if Text.Contains([Assigned to], "sean") Then "Group 1" else if Text.Contains([Assigned to], "Mary") Then "Group 2" else if Text.Contains([Assigned to], "Pete") Then "Group 2" else "Group 3")

Like mentioned, is there a way to write this more efficiently without the long text like above?
Somehow I tried:
= Table.AddColumn(#Changed Type", "Assigned Group", each if Text.Contains(OR(([Assigned to], "John"), ([Assigned to], "johnny"), ([Assigned to], "jane"), ([Assigned to], "sean"))) Then "Group 1" else if Text.Contains(OR(([Assigned to], "Mary"), ([Assigned to], "Pete"))) Then "Group 2" else "Group 3")

It says that the Or is not recognized. I also tried the OR function before the text.contains phrase then it still not works.
How do I enter the OR function like it is in excel or maybe in power query.

A: First of all, keep in mind: M is case-sensitive language. So, Then isn't correct syntax. Also there are no OR function in PQ, but there is or operator.
You may use following code:
  = Table.AddColumn(
    #"Changed Type",
    "Assigned Group",
    each
      let
        fn = (list) =>
          List.AnyTrue(
            List.Transform(list, (x) => Text.Contains([Assigned to], x, Comparer.OrdinalIgnoreCase))
          )
      in
        if fn({"John", "Jane", "Sean"}) then
          "Group 1"
        else if fn({"Mary", "Pete"}) then
          "Group 2"
        else
          "Group 3"
  )


text:
Q: How to expire a nonce? I am aware of the fact that we can alter nonce life time using filter , 30 seconds here:
add_filter( 'nonce_life', function () { return 30; } );

I have a logout() function for my rest api .I wish to expire a nonce that i created after successful login :$nonce =  wp_create_nonce( 'login'.$user_id );

A: The problem with expiring a nonce is that in WordPress, nonces aren't nonces in the purest sense of the term: "number used once." Rather, a WP nonce is a (substring of a) hash of a string involving a time signature at the moment it was generated, among other things: user ID, the action name and your php session token. As such, once generated, it is what it is, it's "use-by" date is baked in, and you can't expire it (and you can't extend it).
Edit:
You can see how the nonce is built in wp-includes/pluggable.php:
function wp_create_nonce($action = -1) {
    $user = wp_get_current_user();
    $uid = (int) $user->ID;
    if ( ! $uid ) {
        /** This filter is documented in wp-includes/pluggable.php */
        $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
    }

    $token = wp_get_session_token();
    $i = wp_nonce_tick();

    return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );

The same set of criteria are used in wp_verify_nonce(): nonce_tick (which is the time element), action, token and uid are all combined and hashed in the same order and compared to the submitted nonce. So, if any of these have changed, the hashes will not match and the nonce is rejected.
End Edit
WP validates it only by whether a submitted string time-matches (via php's hash_equals()) an expected value that is generated when you pass in the nonce string along with the action. If the nonce and action combine with your current user ID and session token to create a hash substring that matches the time-hash check, you pass.
What's missing to make a WP nonce a "true" nonce is a check to see if it has already been used/processed once before.
The security assumption is that it doesn't matter, because even if someone gets ahold of the nonce and its corresponding action, you would still need to submit it using the same User ID and php session token under which it was generated -- highly unlikely unless a hacker has hijacked your device and is logged in as you... but by then you have a different kind of security problem.


text:
Q: Converting multiple lines of mysql string into predefined csv format? this is more like a how-to question about csv, excel, mysql files than a standard coding question. However I really would appreciat some help with this.
I have this predefined CSV format, that I need in order to import it to a database with Sequel Pro.
ID,"user_login","user_pass","user_nicename","user_email","user_url","user_registered","user_activation_key",user_status,"display_name"

1,"some_name","$P$BDMmGci3KAqNQwfPtgzfQTp8D3k7bC.","some_name","some.name@gmx.net","","2013-06-27 11:32:08","",0,"Some Name"

On the other hand I have an old database file looking like this …
CREATE TABLE `ezxsubscription` (
  `id` int(11) NOT NULL auto_increment,
  `version_status` int(11) NOT NULL default '0',
  `subscriptionlist_id` int(11) default '0',
  `email` varchar(255) default '',
  `hash` varchar(255) default '',
  `status` int(11) default '0',
  `vip` int(11) default '0',
  `last_active` int(11) NOT NULL default '0',
  `output_format` varchar(255) default '',
  `creator_id` int(11) NOT NULL default '0',
  `created` int(11) NOT NULL default '0',
  `confirmed` int(11) NOT NULL default '0',
  `approved` int(11) NOT NULL default '0',
  `removed` int(11) NOT NULL default '0',
  `user_id` int(11) default '0',
  `bounce_count` int(11) default '0',
  PRIMARY KEY  (`id`,`version_status`)
) TYPE=MyISAM;

--
-- Dumping data for table `ezxsubscription`
--

INSERT INTO `ezxsubscription` VALUES (454,1,5,'name@surname.com','31b6bde64e1282ba82d7d0c8ad6ebaa9',2,0,0,'2',1127,1142840848,0,1142840868,0,2633,0);
INSERT INTO `ezxsubscription` VALUES (1,1,5,'name.name@gmail.com','fff4b8d75ecdfad43ed8c89444939cfb',2,0,0,'2',10,1141956489,1141956489,1141956489,0,14,0);
…

The database has like 400 users in it that I couldn't sort by hand. I need to have the database file to be in the format of the predefined CSV above. Where the email-address should be the user_login and user_name. The rest of the old database like approved, removed or whatever can simply be disregarded. It's just about the user-login and the passwords.
Any clever idea on how to do so? The aim is to import all the old users of the old database to the new database (based on Wordpress).
I would really appreciate some tips or tricks.
Thank you in advance.
Matt

Update:
This is the old format of the ezxsubscription table.
"id","version_status","subscriptionlist_id","email","hash","status","vip","last_active","output_format","creator_id","created","confirmed","approved","removed","user_id","bounce_count"
1,1,5,"andreas@gmail.at","fff4b8d75ecdfad43ed8c89444939cfb",2,0,0,2,10,1141956489,1141956489,1141956489,0,14,0

All I wanna do now is convert this users to the new wordpress format:
"ID","user_login","user_pass","user_nicename","user_email","user_url","user_registered","user_activation_key","user_status","display_name"
1,"local","$P$BCf7QHr3rsp0YNZd7eMfYgncRZmR6j0","local","temp@local.dev","","2013-03-14 18:46:29","",0,"local"

I do even have problems understanding what the hash in the old db means.
All I wanna do is copy all existing old users to the new wordpress database so that I have the e-mail addresses and the passwords, so that they are able to login again.
So I want to make the old email the username of the new wordpress db. And the hash should probably be the new user_pass in wordpress. However I only hope that the hash is the password of the current login — I don't even know for sure.
Kind Regards,
Matt

A: Use SELECT ... INTO OUTFILE syntax to create a CSV file from your old table with a query like this
SELECT *
  INTO OUTFILE '/path/to/your/file.csv'
    FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
  FROM
(
  SELECT 'id', 'user_login', 'user_pass', 'user_nicename','user_email','user_url','user_registered','user_activation_key','user_status','display_name'
  UNION ALL
  SELECT id, email, hash, SUBSTRING_INDEX(email, '@', 1), email, '', created, '', status, SUBSTRING_INDEX(email, '@', 1)
    FROM ezxsubscription
) q

Content of the created file:

"id","user_login","user_pass","user_nicename","user_email","user_url","user_registered","user_activation_key","user_status","display_name"
"454","name@surname.com","31b6bde64e1282ba82d7d0c8ad6ebaa9","name","name@surname.com","","1142840848","","2","name"
"1","name.name@gmail.com","fff4b8d75ecdfad43ed8c89444939cfb","name.name","name.name@gmail.com","","1141956489","","2","name.name"