text:
Q: Variable arguments Is there a non-boost way to create a function with variable arguments? I know the argument types number of arguments and they are usually less then 5, all of the same type.
I need to know if there is a way without supplying the argument count or ending the param list with null.

A:
I know the argument types and they are usually less then 5.

If it is not going to be greater than 5, then simple overloads may do the work. Call the overload which accepts maximam number of arguments from all other overloads accepting less than 5 arguments, or define a worker (internal) function, call this from the overloads.
If possible, you could use default values for some of the parameters, if that helps reducing the number of overloaded functions.
In C++11, you could use variadic-template.

A: For up to 5 arguments all of the same type, simple overloads can do the trick.
For more generality, supporting any number of arguments of the same type, just pass a collection such as a std::vector.
For a C++03 technique to build such a collection on the fly in each call, see my other answer; for C++11, if you do not need to support Visual C++ you can use curly braces initializer lists as actual arguments.

A: Is cstdarg what you are looking for? This is the standard C++ way to generate functions with variable numbers of arguments.

A: You should be able achieve passing variable arguments using va_list.

A: As a general C++03 solution you can provide a setter that returns a reference to the object that it's called on, so that it can be called again. And again. And so on, called chaining.
It's the same scheme as iostreams use for operator<<.
E.g.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

void foo( char const s[] )
{
    cout << s << endl;
}

class StringBuilder
{
private:
    string      s_;

    template< class Type >
    string fastStringFrom( Type const& v )
    {
        stringstream stream;
        stream << v;
        return stream.str();
    }

    char const* fastStringFrom( char const* s )
    {
        return s;
    }

    string const& fastStringFrom( string const& s )
    {
        return s;
    }

public:
    template< class Type >
    StringBuilder& operator<<( Type const& v )
    {
        s_ += fastStringFrom( v );
        return *this;                   // Supports chaining.
    }

    operator string const& () const { return s_; }
    operator char const* () const { return s_.c_str(); }
};

int main()
{
    typedef StringBuilder S;

    foo( S() << "6*7 = " << 6*7 << "." );   // Any number of arguments.
}

Instead of converting the argument values to text, you just do whatever it is that you need. For example, with a fixed set of possible types you can store the arguments in a collection.
If you do not need to support the Visual C++ compiler, then alternatively you can use a C++11 variadic template.

A: You can:

*

*if you're using C++11 you can use variadic templates, otherwise...

*provide overloads

*use arguments which default to some sentinel values you can recognise ala f(const T& v1 = missing, const T& v2 = missing, ...) { if (v5 != missing) ...

*create a simple helper template that can optionally be constructed from the data type and has a bool to track whether it was

*

*you may need to support types without default constructors by either using new/delete (simple and safe but slow) or having an aligned buffer you placement new into, manually destroy etc. (fiddly and easier to get wrong but faster)

*some compilers have variadic macro support

*if you're prepared to change the calling syntax a bit, you can use any number of things:

*

*accept a vector (using a union or variant if the types differ)

*accept an array (possibly using the template <size_t N> void f(T (&data)[N]) { ... } trick to have the compiler provide the array size to you automatically)

*some kind of lhs object to which extra values can be supplied using an operator such as operator, or operator<<


text:
Q: React native Linking.getInitialURL() return null when opening the app from Android gmail I'm opening up my app's reset password screen from an email that in the Gmail app(Android). If I tick "Open Web links in Gmail" setting in Gmail general settings, the link that I have in the email does not redirect to the correct screen. But if I un-tick above setting it is working fine.
This is in my splash screen
  componentDidMount() {
    Linking.addEventListener('url', this.handleUrl);
    Linking.getInitialURL().then((ev) => {
      //ev is null in above case
      if (ev) {
        this.handleUrl(ev);
      }
    }).catch(err => {
        console.warn('An error occurred', err);
    });

  }

  handleUrl = (url) => {
    const eveUrl = this.evaluateUrl(url);
    Linking.canOpenURL(eveUrl).then((supported) => {
      if(supported) {
        this.addRoutesToDeepLinking(eveUrl); //navigate to correct screen
      }
    })
  }

This is totally working fine in iOS with Gmail app and also it is working fine in other email clients like Outlook with Android.
(I'm using firebase dynamic links)
AndroidManfest.xml>
 <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:host="xxx.page.link" android:scheme="https"/>
        </intent-filter>

And,
android:launchMode="singleTask"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Number of arrays with adjacent elements coprime? An array of integers is called m-coprime if the following conditions are both satisfied:

*

*All the integers in the array are positive divisors of m.

*Each pair of adjacent elements in the array is coprime.

Let the size of the array be n.
For a given n and m, how many such arrays exist?
A similar question whether all pairs are coprime exists but this variant is expected to have a solution. he link to the question : here
Example:
For n = 2 and m = 6; we get 9 such arrays.
The combinations are : (1,1) ; (1,2) ; (1,3) ; (1,6) ; (2,1) ; (2,3) ; (3,1) ; (3,2) ; (6,1) ;
Could someone point out the flow in which the number of such arrays is calculated?


text:
Q: How can I play with local teammate on PC? Is there a way to play Two Headed gigant in Magic 2014 with a local teammate against remote opponents?
We are sitting in front of a PC with my friend and we would like to play with guys from the internet. When I create a game and select "Play with local teammate" I get:
"magic 2014 at least one controller is required"
What does it mean? Is that even possible on PC? Do I need to connect another mouse or something?

A: You need a separate controller for the other player, the safest bet would be a actual controller like a Xbox 360 controller. You then need to configure this correctly in the game settings before hosting.


text:
Q: Unidentified variable after being declared I'm getting this error
Fatal error: Non-static method Connect::connect() cannot be called statically in D:\xampp\htdocs\Panel\core\init.php on line 63

Here is my code
<?php
class Connect{
    public $db_host = "localhost";
    public $db_user = "root";
    public $db_pass = "";
    public $db_name = "panel";

    public function connect(){
            if(mysql_connect($db_host, $db_user, $db_pass)){
                    if(mysql_select_db($db_name)){
                            return true;
                    }else{
                            die(mysql_error());
                    }
            }else{
                    die(mysql_error());
            }
            return false;
    }
}
?>

How do I make the function static?
I tried adding 'static' to the function scope, but I got another error
Thanks :)

A: You have to pass the variables to function as parameter
function connect($db_host, $db_user, $db_pass,$db_name)

And call this function as
connect($db_host, $db_user, $db_pass,$db_name);

Edit
By seeing your pastebin, you are calling class variables, you have to use $this->variale_name to access them.
<?php
class Connect{
    public $db_host = "localhost";
    public $db_user = "root";
    public $db_pass = "";
    public $db_name = "panel";

    public function connect(){
            if(mysql_connect($this->db_host, $this->db_user, $this->db_pass)){
                    if(mysql_select_db($this->db_name)){
                            return true;
                    }else{
                            die(mysql_error());
                    }
            }else{
                    die(mysql_error());
            }
            return false;
    }
}
?>

PDO
<?php
class Connect{
    private $db_host = "localhost";
    private $db_user = "root";
    private $db_pass = "";
    private $db_name = "panel";
    private $dbh = false;
    public function connect(){
        if ($this->dbh === false)
            $this->dbh = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name, $this->db_user, $this->db_pass);
        return $this->dbh;
    }
}
?>

A: You have to declare the variables inside the function like this
<?php

function connect(){

    $db_host = "localhost";
    $db_user = "root";
    $db_pass = "";
    $db_name = "panel";

    if(mysql_connect($db_host, $db_user, $db_pass)){
        if(mysql_select_db($db_name)){

        }else{
            die(mysql_error());
        }
    }else{
        die(mysql_error());
    }
}
?>

Or you can pass the parameters in the function like this
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "panel";

connect($db_host,$db_user, $db_pass, $db_name);

function connect($db_host,$db_user, $db_pass, $db_name){

        if(mysql_connect($db_host, $db_user, $db_pass)){
            if(mysql_select_db($db_name)){

            }else{
                die(mysql_error());
            }
        }else{
            die(mysql_error());
        }
    }
    ?>

A: $db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "panel";

These variables are global and can't be accessible in function connect. If you have to use these global variables then use keyword global . Then these vars will be available within the function.
 function connect(){
        global $db_host, $db_user, $db_pass, $db_name ;
        if(mysql_connect($db_host, $db_user, $db_pass)){
            if(mysql_select_db($db_name)){

            }else{
                die(mysql_error());
            }
        }else{
            die(mysql_error());
        }
    }


text:
Q: Apply css style to mat-snackbar in angular I'm wondering why I've been stuck with this all afternoon, and I find it embarrassing that something so trivial is so hard to do in angular material.
I'm trying to apply a custom style to a snackbar once a button is clicked, this is my code :
this.errormessagecard.open(error.error.message,'Esci', {panelClass : 'error-snackbar'});

I've literally tried everything:
In my component.css
.error-snackbar{
  background-color: red!important;
}

error-snackbar{
  background-color: red!important;
}

::ng-deep .error-snackbar{
  background-color: red!important;

And the same thing in my styles.css
What I get is always the same result, which is this:
Snackbar result
Nothing change, why??


text:
Q: How to make a folder named "private folder" in gallery android 4+ version [programmatically] i'm making an app in which there is a case in which i want to make a folder in gallery named "private folder" (when user clicks on the button "Create Folder") and then programmatic-ally want to insert a image in it say "mypic.png" ... can anyone help plzzz

A: You can create directories in external memory like this:
File mydir = new File(Environment.getExternalStorageDirectory() + "/privatefolder/");
mydir.mkdirs();

then you can save your files in it in different ways. this is a one of them which you have already a filepath and you want to copy that image to your folder:
String oldFilePath = "Your old FilePath";
String newFilePath = new File(Environment.getExternalStorageDirectory() + "/privatefolder/" + "Your image name.jpg");

File newFile = copyFile(oldFilePath , newFilePath);

public static File copyFile(String from, String to) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) {
            int end = from.toString().lastIndexOf("/");
            String str1 = from.toString().substring(0, end);
            String str2 = from.toString().substring(end+1, from.length());
            File source = new File(str1, str2);
            File destination = new File(to, str2);
            if (source.exists()) {
                FileChannel src = new FileInputStream(source).getChannel();
                FileChannel dst = new FileOutputStream(destination).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
            return destination;
        }

    } catch (Exception e) {
        return null;
    }
    return null;
}

also don't forget to add this permission in manifest:
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Edit:
for saving from drawables to sdcard:
//first get a bitmap from your image. if your image name is "photo" do it like this
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.photo);

//then creat your directory. and then copy your image (in this code image format is PNG)
File mydir = new File(Environment.getExternalStorageDirectory() + "/privatefolder/");
mydir.mkdirs();
File file = new File(mydir, "photo.PNG");
FileOutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();

used some of this answer code.


text:
Q: Displaying a returned value when a button is pressed? I have some code here that calculates the maxValue of an array:
 public static int getMaxValue(int[] marks){
     int maxValue = marks[0];
     for(int i=1;i < marks.length;i++){
         if(marks[i] > maxValue){
             maxValue = marks[i];
         }
     }
     return maxValue;
 }

I want to display the maxvalue when a button is pressed by the user. This is what I have so far but it does not work:
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {

    maxValue mv = new maxValue ();
    analyzeTextArea.setText("Maximum:" + maxValue.toString());

}

Thanks for any help!

A: Since your method is static, you can simply use the name of the class that contains it to call it.
analyzeTextArea.setText("Maximum:" + YourClassNameHere.getMaxValue());

You can't instantiate a method.

A: I think you're looking for something like this...
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {
    analyzeTextArea.setText("Maximum:" + getMaxValue(arrayOfValues));
}

To call a method, you don't need to do anything other than call methodName(inputValues) - you can't create an instance of the method by doing new methodName()
If the method is in a different class, and it is a static method like your case, you can do this...
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {
    analyzeTextArea.setText("Maximum:" + MyClass.getMaxValue(arrayOfValues));
}

Otherwise if the method is in a different class and it isn't static, then you create an instance of the class first, then call the method...
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {
    MyClass example = new MyClass();
    analyzeTextArea.setText("Maximum:" + example.getMaxValue(arrayOfValues));
}


text:
Q: VM428:7 Uncaught TypeError: Cannot read properties of null (reading 'CodeMirror') at :7:17 The code is running nicely but I don't understand where I get this error:
VM428:7 Uncaught TypeError: Cannot read properties of null (reading 'CodeMirror')
    at <anonymous>:7:17

A: Remove blackbox extension and react development tool extension from chrome

A: Just Remove blackbox extension from your chrome and its done


text:
Q: Get Full-Text Feed with Delphi I'm developing a Delphi program that reads the source of a feed through the component Indy idHTTP.. but the feed does not appear complete, appears only its summary, I mean the feed does not show the "content" tag.
I think it is possible to get full-text feeds because I have found some sites on the Internet (like http://fulltextrssfeed.com/) that can show the full-text feed, even for feeds that show only the summary.
What should I do to be able to read the full-text feed via Delphi?
Is there a specific Delphi component to do this or can I do it with idHTTP?
Any help will be very very appreciated
Thanks you All!

A: *

*Delphi has other built-in controls for TCP/IP besides Indy.  Try one, and see if you get different results.  Even as an experiment, it would only take about 30 seconds (drag drop component onto a form, set the URL, fetch the results, and see what you get).  Correct?

*If the site in question isn't giving you a full-text feed, I'm not aware of any Delphi component that will automagically get it for you.  Here's a good link about some heuristics to get it yourself from the partial RSS contents:
How to programmatically determine whether an RSS feed is a full feed or a partial feed
And a tutorial on parsing the RSS, using Delphi:
Reading and manipulating XML files with Delphi

*Finally, there seem to be a number of web apps out there which CAN get the full-text RSS for you:
http://fulltextrssfeed.com/feed.php
http://www.fullrssfeed.com/
http://www.unsum.com/converter
Perhaps you can integrate one of these services into your app?

A: Seems that when RSS/Atom feed has no full-text content, the way to get it is to go into the feed's URL, and extract the full-text via innerHTML/outerHTML.. See below a good example:
PHP sources (AGPL v3 license):
http://code.fivefilters.org/p/full-text-rss/source/tree/master/
I could do it on Delphi, though it will take some time to get done..
On the other hand, as Paulsm4 said above, it may be good integrate one of these services into your app.
So..well.. for now I'm thinking to provide both options(logic to get full-text, and integration) in my app. :)

A: For many web applications, the document returned from the web server can depend on additional headers in the HTTP GET request, for example the Accept header.
By default, Indy will set it to text/html, *.*.
Try setting it to application/rss+xml, the server then should reply with the full RSS content:
...
IdHTTP1.Request.Accept := 'application/rss+xml';
Response := IdHTTP1.Get(url);
...


text:
Q: Java: Paths.get(URI) throws IllegalArgumentException but Paths.get(URI.toString) does not. Why? I was using URI as a parameter for Paths.get(). I used it in other parts of my code, however, there is one path that could not be resolved. It threw an IllegalArguementException: Missing Scheme. The path name uses "/" and "-", however, those are not reserved characters.
So I tried using the SAME URI but as a string. So basically Paths.get(destinationURI) doesn't work but Paths.get(destinationURI.toString) does.
Does anyone understand why that is the case? I REALLY would like to know.
Thanks in advance.


text:
Q: Is boot history stored on motherboard? I know that boot and login history is stored both on macOS (/var/log/) and Windows systems on the hard drive.
Now the MacBooks hard drive has been formatted (MacBook Air 2018). Is it still possible to get information about when the device has been booted? Is boot history stored somewhere on the mainboard?

A: No. The only chip that stores static information is the BIOS chip and it does not store boot history


text:
Q: Given that $|3x|+|2y| \leq 1$ then the maximum value of $9x+4y$ is ?. Suppose that $|3x|+|2y| \leq 1$ then the maximum value of $9x+4y$ is?.
I thought of drawing the region satisfied the constraint given on the $xy$ plane.
here is the region enclosed the lines -
I recall a theorem stating that maximum value of the function under the given constraints occurs at the boundaries. Is this correct?.  I tried to substitute the following four points into the equation $9x+4y$ and got the maximum value as $3$ and I think the minimum value is $-3$ similarly. Is this correct?
Any other way or approach of solving this?

A: $9x+4y \le |9x+4y| \le 2|3x|+2|2y|+|3x| \le 2+|3x| \le 2+1=3$ and for $x=1/3$ and $y=0$ we have $9x+4y=3$.

A: The gradient of $9x+4y$ is $(9,4)$. Move along that from $-\infty$ to reach the constraint, pass through it and exit from the other side. The last point visited by this process is the maximal point which is $(\dfrac{1}{3},0)$ and the maximum is $3$
Here is a sketch


text:
Q: How to copy and paste without change excel's cell category I have a spreadsheet where all cells are text category, when I copy and paste from another spreadsheet into mine, all the cells affected have their category changed and sometimes the format of data too, the problem is that is not required for the client to know how to special paste so he could insert only values, so by not knowing how to perform this he ends up breaking this whole system functionlality.
Is there a way to configure cell as not available for category changes, or automatically copy only values as text instead of overwriting the whole cell.
I need my cells as they are, having it's cells category always as text


text:
Q: What's the best way to delete a QNetworkReply? I'm writing an embedded RESTful API client using the Qt5 Embedded layer of OpenEmbedded project. I want my client to be able to send a simple async request to notify my server on what's going on and an other scenario is that my client needs to synchronize data from the server.
To do so I wrote two functions, one to send the request and another to get the response. So if I don't care about the response, I only use the first one.
To be able to use the response with the second one, I use a QNetworkReply * as a member of my class. To keep the QNetworkReply alive, I also set the QNetworkAccessManager as a member of my class.
#include <QtNetwork>

class ApiClient : public QObject
{
    Q_OBJECT

public:

    ApiClient(QObject *parent = 0);

private:

    QString host;
    QString key;
    quint32 replyTimeout;
    QNetworkAccessManager manager;
    QNetworkReply *reply;

    void sendRequest(const QString &method, const QVariantMap &params = QVariantMap());
    QVariantMap getResponse() const;
};

The apiclient.cpp file:
#include "apiclient.h"

ApiClient::ApiClient(QObject *parent) : QObject(parent)
{

}

void ApiClient::sendRequest(const QString &method, const QVariantMap &params)
{
    QUrl url(QString("%1/%2/").arg(host).arg(method));

    QUrlQuery query;
    query.addQueryItem("key", key);

    if (!params.empty())
    {
        QMapIterator<QString, QVariant> it(params);
        while (it.hasNext())
        {
            it.next();
            query.addQueryItem(it.key(), it.value().toString());
        }
    }

    url.setQuery(query);
    qDebug() << "url: " << url.toString();

    reply = manager.get(QNetworkRequest(url));
}

QVariantMap ApiClient::getResponse() const
{
    if (!reply)
    {
        qFatal("No request sent!");
    }

    QTimer timer;
    timer.setSingleShot(true);

    QEventLoop loop;
    connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    timer.start(replyTimeout);
    loop.exec();

    if (timer.isActive())
    {
        timer.stop();

        if (reply->error())
        {
            qFatal("Wrong reply!");
        }

        int code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        if (code != 200)
        {
            qFatal("Invalid server response!");
        }

        QJsonDocument result = QJsonDocument::fromJson(reply->readAll());

        if (result.isNull())
        {
            qFatal("Invalid JSON!");
        }

        reply->deleteLater();
        return result.object().toVariantMap();
    }

    disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    reply->abort();
    reply->deleteLater();
    return QVariantMap();
}

Is that a good way to proceed? How should I manage the QNetworkReply pointer when other signals are emitted (i.e. error(), sslErrors(), ...)?

A: QNetworkReply will always emit finished(), even when an error occured.
deleteLater() could even be called in a slot connected to that signal, so that part should be fine.
But I would recommend to look into a more asynchronous approach of handling the request, nested event loops like the on in your getResponse() can lead to "interesting" behavior, because you can basically get into re-entrancy situations in a single threaded program.


text:
Q: How to send data via Javascript - Jquery How to send data via Javascript - Jquery

A: If you want to send some data to a server side script your could use AJAX. jQuery has great support through $.ajax(), $.post(), $.get(), $.getJSON():
$.ajax({
    url: '/script',
    data: { key1: 'value 1', key2: 'value 2' },
    success: function(result) {
        alert('data successfully sent');
    }
});

A: $.post() or $.send() www.jquery.com

A: $.ajax({
  url: url_page,
  data: ({id: 1, data: 1212}),
  dataType: 'json'
});


text:
Q: Changing VS2010 environment variables for WIX I need to build two branded versions of my WIX based installer. The only difference between the the versions is a single bitmap containing the company contact details. I'd like to keep a single WIX project so I have less projects to maintain. I'm using an environment variable to alter which bitmap is inserted into the installer
Source="$(env.CompanyName) contact.png"

This works fine, however I cannot change the environment variable from within VS2010. VS2010 is compiling the WIX installers using the environment variables that were set when VS2010 started. I have to restart VS2010 to get it to pick up the new environment variable value.
I have 36 nested projects so I don't want to have to set the build variables within each project - that's why I'm trying to use an environment variable.
Does anyone know how to change one of the environment variables used by the current VS2010 instance? Or perhaps there is a better way?

A: I do this and significantly more customization in a single WiX project.  I have a different project configuration for each variant.  So rather than "Debug" and "Release", I have for example "Debug", "East" and "West".  This only applies to the setup project.  The code projects still use "Debug" and "Release".  The WiX compiler can read the configuration value.
<?if   $(var.Configuration)="West"?>
  <?define CompanyName="West Coast Office"?>
<?elif $(var.Configuration)="East"?>
  <?define CompanyName="East Coast Office"?>
<?else?>
  <?define CompanyName="Debugging purposes"?>
<?endif?>

Source="$(var.CompanyName) contact.png"

Alternatively, you can add it to the setup project's preprocessor variables (Project Properties, Build, General), but again, you'll require multiple configurations:
CompanyName=West Coast Office

And in your Product.wxs:
Source="$(var.CompanyName) contact.png"

To add the configurations in Visual Studio:

*

*Open the menu Build, Configuration Manager...
Create solution configurations

*Under Active solution configurations select <New...>

*Type the Name (eg. East), Copy settings from Release, and do not create new project configurations.

*Repeat steps 2 and 3 for the other office (eg. West).
Create setup project configurations

*Next to the setup project, open the Configuration drop down and select <New...>

*Type the Name East, Copy settings from Release, and do not create new project configurations.

*Repeat steps 5 and 6 for West.
Delete setup project's Release configuration

*Next to the setup project, open the Configuration drop down and select <Edit...>

*Select Release and press Remove, followed by Yes and Close.
Delete solution's Release configuration

*Under Active solution configurations select <Edit...>

*Select Release and press Remove, followed by Yes and Close.
Assign the project configurations to the solution configurations

*Under Active solution configurations select East.

*Set the setup project's Configuration to East and every other project's configuration to Release.  Tick Build next to each project (assuming you need all of them.)

*Repeat steps 12 and 13 for West.

Now when you select each solution configuration, you should have the following settings:
Solution       Debug    East     West
------------------------------------------
Main Project   Debug    Release  Release
Setup Project  Debug    East     West

Finally, go into the setup project's properties and ensure everything is correct for the East and West configurations.  Take note of the output folder.  If that is still bin\Release, then the two configurations will overwrite eachother's output.  Set it to bin\East and bin\West respectively.


text:
Q: Geometry - locus of points ☕ Hello
I was doing an example when this question came to my mind.
The question I was dealing with: two dots (A and B) exist on the paper. Draw a circle with a radius of X which passes through the points (A and B )
The answer: so I know that the center of the circle must be on the perpendicular bisector of line segment A and B
 My question : can the center of the circle be that far which part of the circle becomes exactly on the line
And can the center of our circle be that far which it doesn't even pass through the points ?


text:
Q: Unable to find a string matching a regex pattern While trying to submit a form a javascript regex validation always proves to be false for a string.
Regex:- ^(([a-zA-Z]:)|(\\\\{2}\\w+)\\$?)(\\\\(\\w[\\w].*))+(.jpeg|.JPEG|.jpg|.JPG)$
I have tried following strings against it
abc.jpg,
abc:.jpg,
a:.jpg,
a:asdas.jpg,

What string could possible match this regex ?

A: This regex won't match against anything because of that $? in the middle of the string.
Apparently using the optional modifier ? on the end string symbol $ is not correct (if you paste it on https://regex101.com/ it will give you an error indeed). If the javascript parser ignores the error and keeps the regex as it is this still means you are going to match an end string in the middle of a string which is supposed to continue.
Unescaped it was supposed to match a \$ (dollar symbol) but as it is written it won't work.
If you want your string to be accepted at any cost you can probably use Firebug or a similar developer tool and edit the string inside the javascript code (this, assuming there's no server side check too and assuming it's not wrong aswell). If you ignore the $? then a matching string will be \\\\w\\\\ww.jpg (but since the . is unescaped even \\\\w\\\\ww%jpg is a match)
Of course, I wrote this answer assuming the escaping is indeed the one you showed in the question. If you need to find a matching pattern for the correctly escaped one ^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(\.jpeg|\.JPEG|\.jpg|\.JPG)$ then you can use this tool to find one http://fent.github.io/randexp.js/ (though it will find weird matches). A matching pattern is c:\zz.jpg

A: If you remove escape level, the actual regex is
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpeg|.JPEG|.jpg|.JPG)$

After ^start the first pipe (([a-zA-Z]:)|(\\{2}\w+)\$?) which matches an alpha followed by a colon or two backslashes followed by one or more word characters, followed by an optional literal $. There is some needless parenthesis used inside.
The second part (\\(\w[\w].*))+ matches a backslash, followed by two word characters \w[\w] which looks weird because it's equivalent to \w\w (don't need a character class for second \w). Followed by any amount of any character. This whole thing one or more times.
In the last part (.jpeg|.JPEG|.jpg|.JPG) one probably forgot to escape the dot for matching a literal. \. should be used. This part can be reduced to \.(JPE?G|jpe?g).
It would match something like

A:\12anything.JPEG
\\1$\anything.jpg

Play with it at regex101. A better readable could be
^([a-zA-Z]:|\\{2}\w+\$?)(\\\w{2}.*)+\.(jpe?g|JPE?G)$

Also read the explanation on regex101 to understand any pattern, it's helpful!

A: If you are just looking for a regular expression to match what you got there, go ahead and test this out:
(\w+:?\w*\.[jpe?gJPE?G]+,)

That should match exactly what you are looking for. Remove the optional comma at the end if you feel like it, of course.


text:
Q: Rails: How can I share a common object across different actions (that is unique to each user) I am building a rails3 application and I'm using the excellent 'gmail' gem to do some work with gmail. Each user enters his/her username and password and the gem creates a connection to gmail that can be used to fetch emails or send new emails.
How can I share this connection variable across actions in the same controller without having to create a new connection every time?
ex. user logs in with his details:
@gmail = Gmail.connect(email, pass)

then user clicks on a link that calls a different action, for example to read new emails:
@newemails = @gmail.inbox.count(:unread)

well the problem is that I cannot reuse this @gmail connection object in the 'unread' action as it is nil. I cannot store this in a session variable or in the database as it is not a string. And I cannot store this in a @@class_variable as the connection variable is not global across all sessions - each user must have its own connection obviously.
What is the best way to share this object across different actions?
Many thanks for your help,
Alex


text:
Q: Date Picker in Ui5 allows to enter integers I have a date picker in my XML view and it allowed to enter integer and even saved. How to validate if the user entered in right date format.
<DatePicker value="{model>Date}" valueFormat="yyyyMMdd"
            displayFormat="dd/MMM/YYYY" change="Change"/>

A: Try this, THI.
Hope it helps.
    onChange: function(oEvent) {
        var bValid = oEvent.getParameter("valid");
        var oDP = oEvent.getSource();

        if (!bValid) {
            sap.m.MessageToast.show("Entered date range isn't valid");
            oDP.setValueState("Error");
            return;
        }
    },


text:
Q: Allow zero, allow number, and maximum two number after point I need to write regex validation.
Accepted numbers:
0
0.3
0.21
78.21
8934
Not Allowed:
00
0.323
-1
021
^(?:0,\d\d|[1-9]\d*(?:,\d\d)?|)$

I had that regex, but it doesn't accept '0', and number '0.2'.

A: Seems the following ticks your boxes:
^(?:0|[1-9]\d*)(?:\.\d\d?)?$

See the online demo

*

*^ - Start line anchor.

*(?: - Open non-capture group:

*

*0 - A literal "0".

*| - Or:

*[1-9]\d* - A single digit ranging 1-9 followed by 0+ digits.

*) - Close non-capture group.

*(?: - Open 2nd non-capture group:

*

*\.\d\d? - Match a literal "." followed by a digit and an optional 2nd digit.

*)? - Close non-capture group and make it optional.

*$ - End line anchor.


text:
Q: how to get the text content of an element with javascript i am getting the the element on the web page by the xpath using the evaluate function.
var ele = document.evaluate(request.path, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var node = ele.snapshotItem(0);
alert(node.textContent);

But this gives undefined, may anyone help me with this ?


text:
Q: Did Olympe (Madame Maxime) love Hagrid? At moments it seems as though the two are truly in love but at others it seems like she's using him. She gets all mad at Hagrid for saying the truth, and lies to him. Maybe she just wanted to get away from Hagrid. The reason she wanted to make up with him was to find out about the 3rd task early (at least, to my understanding,) and after Hagrid comes back in Order of the Phoenix, there was no Olympe Maxime.

A: She thought he was "kind of cute", but not "sophisticated" enough.
Shortly after the release of Book Seven, J.K. Rowling did a book reading event at Carnegie Hall. One of the questions she was asked there was about if Hagrid ever gets married.
There's no surviving recording of the event, but here are three different accounts from people present:

Q: Did Hagrid ever get married and have children?
[Aww from crowd] JKR: Oh, did Hagrid ever get married and have children? No. [awwws again] I may change that immediately due to the look on your face. Yes! He had 22! – No, no, Hagrid never did marry and have children. I'm sorry. I'm really sorry. Oh I feel terrible now. I'll write another book! [Ovation] Realistically, Hagrid's pool of potential girlfriends is extremely limited. Because with the giants killing each other off, the number of giantesses around is infinitesimal and he met one of the only, and I'm afraid, she thought he was kind of cute, but she was a little more, how should I put it, sophisticated than Hagrid. So no, bless him. [Awws] I kept him alive, come on! [Applause.]
The Leaky Cauldron (said to be accurate in meaning but not phrasing)

Did Hagrid ever get married….No.
Crowd does sad: "Awwwwww…."
No, Hagrid never did get married, actually.  I'm sorry.
Realistically, Hagrid's pool of potential girlfriends is extremely limited. With Giants killing each other constantly the number of Giantesses around is infinitesimal. And he met one of the only ones.  And I'm afraid she though he was kind of cute, but she was a little more – how can I put it? – sophisticated than Hagrid. So no, bless him, no.
iamstarmom livejournal (based on a recording)

Question: Did Hagrid ever marry and have children?
Answer: No. His pool of potential mates was small. Madame Maxime thought he was cute, but in the end she was more sophisticated than he was, and they didn't really connect. (The lady who asked this question - at sixty-three, she was the oldest person to ask a question - was unhappy with this answer, and Rowling joked, "Hey, at least he survived!")
eldritchhobbit livejournal (based on "notes")


text:
Q: plotly dash graph error, my graph cutooff

Why my graph only see legend????
I think this data is long sentence so cut graph n just show legend
I want to graph clearly

A: Looks like you need to explicitly define the size of your figure, making it wide enough so the legend doesn't cover it. It might also help to create a shorter label in your legend or move the legend to the top or bottom so it doesn't cover your figure.
To change the size of your figure, you can do so in fig.update_layout() or when exporting the image in fig.write_image().
updating image:
fig.update_layout(
    autosize=False,
    width=1920,
    height=1080)

exporting image:
fig.write_image('figure.pdf', width=1920, height=1080)


text:
Q: Executing R script from command button in Microsoft Access and passing data from Microsoft Access to R I would like to send a query to R and execute R script from a command button in Microsoft Access.  Has anyone done this before and can suggest how to implement this?
Data are stored in Microsoft Access and the query is based on a button the user clicks on in Microsoft Access.
Thanks

A: Simply call a Shell command using the automated Rscript.exe. However first, you may need to export your query data into a format R can read such as csv or txt file. Alternatively, have R connect to database via RODBC.
In the command line call you can send parameters such as query name (for RODBC SQL statement) or csv/txt path for R to receive by concatenating the shell string with space-separated values. Then use commandArgs() list in R to receive values.
Also, double quotes are needed if path names have any space. And if you have Rscript in your environmental variable, PATH, you can use the Rscript command directly. Otherwise, enter full path where Rscript.exe resides (usually in installation bin folder). Examples commented out:
Private Sub QueryCmdButton_Click()
  DoCmd.TransferText acExportDelim, , "qryToExport", "C:\Path\To\CSV.csv"

  Shell "Rscript ""C:\Path\To\R\script.R""", vbNormalFocus
  ' Shell "C:\Path\To\Rscript.exe ""C:\Path\To\R\script.R""", vbNormalFocus
  ' Shell "Rscript ""C:\Path\To\R\script.R""" & " " & qryName & " " & csvPath, vbNormalFocus

  MsgBox "Successfully processed R script!", vbInformation
End Sub

Or a more sophisticated Shell call to receive a return code for error handling:
Sub RunRscript()
   Dim shell As Object
   Dim path As String
   Dim waitTillComplete As Boolean: waitTillComplete = True
   Dim style As Integer: style = 1
   Dim errorCode As Integer

   DoCmd.TransferText acExportDelim, , "qryToExport", "C:\Path\To\CSV.csv"

   Set shell = VBA.CreateObject("WScript.Shell")

   path = "RScript ""C:\Path\To\R\script.R"""
   errorCode = shell.Run(path, style, waitTillComplete)

   Set shell = Nothing
End Sub

A: You can run R code from Microsoft Access using VBA, see https://www.r-bloggers.com/a-million-ways-to-connect-r-and-excel/
To create a command button for your VBA code, see https://social.technet.microsoft.com/Forums/office/en-US/d3640d72-e91f-4d86-a52e-6d3a66888bf8/how-to-create-a-button-in-access-2010-that-runs-vba-code?forum=officesetupdeployprevious
In your R code, you can access Microsoft Access database using ODBC, see http://rprogramming.net/connect-to-ms-access-in-r/
If you have issue with 64-bit Windows and R, see How to connect R with Access database in 64-bit Window?


text:
Q: Is there a function or tool to get the size of a row in Cassandra? Can I get more info about the column of certain row in Cassandra ? Like the size of a row or a column?
Or some information about the size of the row like using a tool like nodetool ?
Maybe something based on the primary key / clustering key ?
Because in Astra Cassandra I have only access to CQL Console ...
<uat>root@cs01:~# nodetool cfstats mykeyspace.series;
Total number of tables: 249
----------------
Keyspace : mykeyspace
        Read Count: 18547
        Read Latency: 0.36771666576804873 ms
        Write Count: 3147
        Write Latency: 0.11854496345726087 ms
        Pending Flushes: 0
                Table: series
                SSTable count: 11
                Space used (live): 17919747207
                Space used (total): 17919747207
                Space used by snapshots (total): 0
                Off heap memory used (total): 16091840
                SSTable Compression Ratio: 0.13888102122935306
                Number of partitions (estimate): 177144
                Memtable cell count: 0
                Memtable data size: 0
                Memtable off heap memory used: 0
                Memtable switch count: 7
                Local read count: 11399
                Local read latency: NaN ms
                Local write count: 1753
                Local write latency: NaN ms
                Pending flushes: 0
                Percent repaired: 0.0
                Bloom filter false positives: 1
                Bloom filter false ratio: 0.00000
                Bloom filter space used: 282544
                Bloom filter off heap memory used: 282456
                Index summary off heap memory used: 81176
                Compression metadata off heap memory used: 15728208
                Compacted partition minimum bytes: 36
                Compacted partition maximum bytes: 14530764
                Compacted partition mean bytes: 622218
                Average live cells per slice (last five minutes): NaN
                Maximum live cells per slice (last five minutes): 0
                Average tombstones per slice (last five minutes): NaN
                Maximum tombstones per slice (last five minutes): 0
                Dropped Mutations: 0
----------------

Many thanks !

A: Given that Astra DB is a fully-managed Cassandra instance, you will not be able to run operator commands such as nodetool against it. That's just the nature of fully-managed services.
The best you can do is to look at the metrics of your DB's health dashboard. However, this won't really help you if you're not able to write the data to your DB.
As a friendly note, you shouldn't ask multiple questions in the same post. I would suggest you create a new post for your first question that includes (1) sample data, (2) sample schema, and (3) minimal code which replicates the problem. Cheers!


text:
Q: how to make RabbitMQ in docker get messages when it is going to local RMQ I have RabbitMQ Erlang 13.1.2 and RabbitMQ 3.11.2 installed in my local and I have  deployed a docker container with RabbitMQ instance runnning as well. I cant unistall / stop my local RabbitMQ as I dont have admin rights at the moment.
I am running a WebSocket SpringBoot App in which MessageBroker Rabbit is configured as follows
@Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config
            .setApplicationDestinationPrefixes("/app")
            .enableStompBrokerRelay("/topic")
            .setRelayHost("localhost")
            .setRelayPort(61613)
            .setClientLogin("admin")
            .setClientPasscode("admin");
    }

The Issue is When I change credentials to guest which is my local RMQ server. All the messages go to local RMQ server  and it works fine but when I change it to admin my docker RMQ  user it shows
<<< ERROR
message:Bad CONNECT
content-type:text/plain
version:1.0,1.1,1.2
content-length:32

Access refused for user 'admin'

both local and docker instance run on localhost with same ports exposed I dont know how to get messages sent to docker instance.

A: It is not possible to bind two network services on the same host to one port. One of them simply would not start. So you either forgot to publish RabbitMQ port when you started docker container, or container uses some other port. To start RabbitMQ docker container, exposing a port you should use --publish / -p option of the docker run command:
docker run -d --hostname rmq --name some-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3

In this example RabbitMQ instance, running inside docker, will be available on the host through default ports. See docker documentation for the additional info.


text:
Q: nvidia driver displaying odd bios,uuid under Grid K2 I have a number of servers that have GRID K2 nvidia Tesla cards in.
Initially these were working fine.  But I recently upgraded the kernel driver and have found a problem where CUDA based apps were no longer detecting GPU's being present.
On closer inspection details from /proc/drivers/nvidia/gpus/*/information
Are no longer giving valid GPU UUID & Video BIOS detail.
Instead I'm getting the following.  While on a working node I get normal detail (no, ?'s).
Bus Location:    0000:89:00.0
Model:           GRID K2
IRQ:             46
GPU UUID:        GPU-????????-????-????-????-????????????
Video BIOS:      ??.??.??.??.??
Bus Type:        PCIe
DMA Size:        37 bits
DMA Mask:        0x1fffffffff
Bus Location:    0000:8a:00.0

I have tried cold rebooting the machines to the previous known configuration working version (these servers are netbooted) and the problem is also persisting with the old drivers.
What could be going wrong here?  Are the cards toast?


text:
Q: How find and remove DOM element from directive? I would like to make my own tag maanger. I use bootstrap typeahead and add directive to this element and listen broadcast on select action.
I can not find a way to remove tag element that had been added previously. I can not do two things: pass my suctom id and find andremove this DOm element even if id is known.
Can you help with that please?
mainApp.directive("tagsManager", ['$compile', function($compile) {
    return {
        restrict: 'A',
        link: function( scope, element, attrs ) {
            console.log("Tags in directive: " + scope.tags);
            scope.$on('tags.new', function(event, tag) {
                console.log("New tag is arrived: " + tag.name);
                var templ = "
tag.name
"
                    .replace(/tag.name/, tag.name).replace(/tag.name/, tag.name);
                var el = angular.element(templ);
                el.attr("bind-data", tag);
//                $scope.items = teamSharedObj.teams;
                $compile(el)(scope);
                element.after(el);
            });
            scope.tagClick = function (tag) {
                console.log("Tag: " + tag);
                // TODO find a way to get id of this element and rempve it
            }
        }
    }
}])

A: I would get rid of the directive you started as it can easily be replaced with ng-repeat, and simpler code.
In controller:
$scope.tags=[];
$scope.typeAheadOnSelect = function( tag){
    /* perhaps do an ajax update to server here? */
    $scope.tags.push(tag);
}
/* example of removing from array */
$scope.deleteTag=function(tag){
   /*server update by ajax, then */
   $scope.tags.splice( $scope.tags.indexOf(tag), 1);
}

In Markup:

{{tag.name}}

Note that the only modifications being made are to the data models, angular will handle adding / removing the DOM elements internally.


text:
Q: OpenResty rewrite_by_lua vs. rewrite_by_lua_file - syntax errors I am using OpenResty Nginx, and have a snippet of Lua script in the Nginx conf. (sample below, but truncated for brevity). This works fine when it is in the nginx.conf file.
rewrite_by_lua '

    -- Load Memcached module
    local memcached = require "resty.memcached"
    local memc, err = memcached:new()
    if not memc then
        ngx.log(ngx.ERR, "Failed to instantiate memc: ", err)
        return
    end
'

However, if I extract this script in to a file, memcached.lua and then include it in the nginx config with rewrite_by_lua_file, I am unable to restart nginx and get notifications about syntax errors such as:
unexpected "," in /etc/nginx/sites-enabled/memcached.lua
unknown directive "--" in /etc/nginx/sites-enabled/memcached.lua
If I remove the ngx.log line completely the syntax error disappears.
How come the syntax is valid in the nginx conf but not when I extract it to a separate file? I've read somewhere about bytecode but not sure if that is related?
EDIT
Here is the full output of the .lua file. This exact code works if it's embedded directly in to the nginx.conf file via rewrite_by_lua
cat /etc/nginx/sites-enabled/memcached.lua
-- Define Memcached key
local memcached_key = "saas_" .. ngx.var.host

-- Load Memcached module
local memcached = require "resty.memcached"
local memc, err = memcached:new()
if not memc then
    ngx.log(ngx.ERR, "Failed to instantiate memc: ")
end

-- Set Memcached timeout
memc:set_timeout(1000)

-- Connect to Memcached daemon
local ok, err = memc:connect("127.0.0.1", 11211)
if not ok then
    ngx.log(ngx.ALERT, "Failed to connect to Memcached: ", err)
end

-- Query for branch name in Memcached
local branch, flags, err = memc:get(memcached_key)
if err then
    ngx.log(ngx.NOTICE, "Failed to get account from Memcached: ", err)
end

-- If branch not found in Memcached, ask MySQL instead
if not branch then

    -- Load MySQL module
    local mysql = require "resty.mysql"
    local db, err = mysql:new()
    if not db then
        ngx.log(ngx.ALERT, "Failed to instantiate MySQL: ", err)
        return
    end

    -- Set MySQL timeout
    db:set_timeout(1000) -- 1 sec

    -- Connect to MySQL daemon
    local ok, err, errno, sqlstate = db:connect{
        path = "/var/run/mysqld/mysqld.sock",
        database = "dbname",
        user = "dbuser",
        password = "dbpass" }
    if not ok then
        ngx.log(ngx.ALERT, "Failed to connect to DB: ", err, ": ", errno, " ", sqlstate)
        return
    end

    -- Define subdomain string by extracting it from the http hostname
    local subdomain = string.match(ngx.var.host, "([%w-]+).")
    local quoted_subdomain = ngx.quote_sql_str(subdomain)

    -- Execute an SQL query to get the branch name based on the subdomain
    local sql = "SELECT branch FROM saas_account WHERE account = " .. quoted_subdomain
    local res, err, errno, sqlstate = db:query(sql, 1)
    if not res then
        ngx.log(ngx.ALERT, "Bad result from DB: ", err, ": ", errno, ": ", sqlstate, ".")
        return
    end

    -- Check we got a result
    if not res[1] then
        ngx.log(ngx.NOTICE, "No docroot was returned for subdomain: ", subdomain)
        ngx.var.branch = "chaletops"
    -- Assign the result from MySQL to the Nginx variable
    else
        ngx.var.branch = res[1].branch

        -- Store the result from MySQL back in to Memcached with a lifetime of 1 hour (3600 seconds)
        local ok, err = memc:set(memcached_key, ngx.var.branch, 3600)
        if not ok then
            ngx.log(ngx.WARN, "Failed to set branch in Memcached: ", err)
            -- return
        end
    end

    -- Save MySQL KeepAlive connection
    local ok, err = db:set_keepalive(10000, 100)
    if not ok then
        ngx.log(ngx.ALERT, "Cannot set MySQL keepalive: ", err)
        return
    end

    ngx.log(ngx.NOTICE, "Loading branch from MySQL: ", ngx.var.branch)

-- Else we did get a result from Memcached
else

    -- Assign the result from Memcached to the Nginx variable
    ngx.var.branch = branch

    ngx.log(ngx.NOTICE, "Loading branch from Memcached: ", ngx.var.branch)

end

-- Save Memcached KeepAlive connection
local ok, err = memc:set_keepalive(10000, 100)
if not ok then
    ngx.log(ngx.ALERT, "Cannot set Memcached keepalive: ", err)
    -- return
end

SOLUTION
TL:DR - put the .lua file outside of your Nginx configuration directory.
After being asked to post the exact error messages, I had to recreate the problem. For reference and Google searchers the error messages are like this:
2015/12/17 10:04:02 [emerg] 6903#0: unexpected "," in /etc/nginx/sites-enabled/memcached.lua:18
This time I copied the Lua code out of my nginx.conf and put it in a file called memcached.lua and saved it in my project directory. I then added the following include to my nginx.conf in place of the Lua script:
rewrite_by_lua_file /path/to/my/project/memcached.lua;
Immediately it starts working!
Previously I had included it by symlinking it from my project directory in to /etc/nginx/sites-enabled/memcached.lua (assuming it would be better for it to actually live alongside the .conf that includes it) and then just used rewrite_by_lua_file memcached.lua; as it was relative the .conf file.
So I initially wondered if it was because the rewrite_by_lua_file function could not follow symlinks or something, but then it dawned on me that it was nothing to do with the Lua include statement, but OBVIOUSLY (now!) because of the symlink being in /etc/nginx/sites-enabled so Nginx was automatically trying to load the file as though it was a normal Nginx configuration file.
This is because Nginx (on Ubuntu/Linux Mint) is configured to import all config files using the path /etc/nginx/sites-enabled/* in to it's main config.
I think the reason I made this simple error is that on later versions of Ubuntu with Apache, a similar process happens but with Apache (which I am much more used to) you have an include path of /etc/nginx/sites-enabled/*.conf - i.e. it specifically requires a .conf file extension, which is why I incorrectly assumed that Nginx would not try to include my .lua file.


text:
Q: Safe PHP database config Recently I have started learning PHP. I have created website that uses single PHP file (ex. config.php) to keep inside it database info, passwords etc.
For example, my config.php looks like that:
 <?php
        return array(
            "ip"=>"localhost",
            "user"=>"rootusr",
            "password"=>"abc",
        );
    ?>

I am accessing to this from other files by $conn = include("config.php"); and echo $conn[ip]; etc.
My question is:
IS IT SAFE METHOD? Is anyone able (excluding me) to access this data from other server? To include my config.php and use it on his own?
How can I do it better or make it safer?
Thanks for help! :)

A: You can set it up on a .htaccess file to restrict access to the file from the web like so:
<Files "config.php">
Order Allow,Deny
Deny from all
</Files>

This means, the file will only be accessible by PHP (on your server)/someone else with access to your server's www directory, and this is a secure enough way to do what you're trying to do.

A: To be more secure you can also move your config.php outside of document root or public html. For example:
Project_root
  config.php
  public_html/ <- (document root)
    index.php


text:
Q: Cant use pyinstaller to make exe when using xmldiff module The Error:
Traceback (most recent call last):
  File "main.py", line 9, in <module>
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 476, in exec_module
  File "adapter\device.py", line 5, in <module>
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 476, in exec_module
  File "adapter\adapter.py", line 29, in <module>
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 476, in exec_module
  File "xmldiff\main.py", line 9, in <module>
  File "pkg_resources\__init__.py", line 909, in require
  File "pkg_resources\__init__.py", line 795, in resolve
pkg_resources.DistributionNotFound: The 'lxml>=3.1.0' distribution was not found and is required by xmldiff
[273952] Failed to execute script 'main' due to unhandled exception!

Hook file:

*

*hooks

*

*hook-xmldiff.py

from PyInstaller.utils.hooks import collect_all

def hook(hook_api):
    packages = [
        'lxml',
        'six'

    ]
    for package in packages:
        datas, binaries, hiddenimports = collect_all(package)
        hook_api.add_datas(datas)
        hook_api.add_binaries(binaries)
        hook_api.add_imports(*hiddenimports)

pyinsataller line:
pyinstaller -F --additional-hooks-dir hooks main.py

both lxml and six modules are installed already.


text:
Q: can't display the console on glassfish 4 with java 8 144 and use eclipse How do I display the console on glassfish 4 using jdk 8 in eclipse?

A: Right click on workspace provided by Eclipse > Select "Run As" > Java Application.


text:
Q: stress-ng limit cpu usage for vm stressor I'm trying to test a server under specific workloads. I'm using stress-ng to simulate a x% cpu load: stress-ng -c 1 -l x
I also trying to use stress-ng to simulate a memory load of x megabytes: stress-ng -vm 1 --vm-bytes xM. This command creates a vm stressor that allocates roughly the amount of memory requested. However, it also generates a 100% cpu utilisation. My guess is that this is due to the stressor continuously accessing the allocated memory to force it to be mapped to real memory.
Is there any way to limit the amount of CPU used by the memory stressor?

A: stress-ng always hits systems hard. For example, the --cpu-method option has documentation for the best one to "make a CPU run hot".  "It was designed to exercise various physical subsystems of a computer as well as the various operating system kernel interfaces."
Profile what exactly it does if you are curious. Easy on Linux, installing debug symbols then perf top is a good start. Both on the stress tests, and other applications.
Regarding  -vm, mmap(), touching pages, and munmap() in a tight loop is going to be brutal to the virtual memory system, and be memory bottlenecked. Instructions per clock is probably going to be terrible, and not show what the CPU can do when kept fed with data. Symptoms at the host metrics level will include a very large % of system CPU time.
stress-ng -vm 1 --vm-hang 0 will sleep virtual memory (VM) workers indefinitely, after touching the memory. Try this if you want to allocate a large anonymous memory area, but not do anything with it. Questionable utility, I suspect, but you can do it.
This will not perform like practical applications do:

*

*stress-ng does not do useful work; this is not a benchmark.

*Memory or CPU workers are not I/O bound waiting for slow disks or network.

*CPU method algorithms, while diverse and real world, are not what you might see from say a transactional database.

*No file I/O, if relevant to this application. stress-ng has file stressors, but not surprisingly they will hit the system hard.

Still useful to be sure hosts don't fall over under stress.

A: In general one can limit the cpu usage with -l <percent> so if it should use 6 Cores on 50 Percent usage, I do:
stress-ng -c 6 -l 50

There should be mentioned that the documentation states: "This option only applies to the --cpu stressor option and not to all  of  the
cpu class of stressors." Manpage


text:
Q: Custom MKAnnotationView Callout
Possible Duplicates:
Custom MKPinAnnotation callout bubble similar to default callout bubble
How to customize the callout bubble for MKAnnotationView?

Does anyone know, or have code that shows, how to create a custom MKAnnotationView Callout? I mean the actual text bubble and not the pin. Thanks in advance.

A: you cannot make a custom MKAnnotationView, you can only custom the callout views left and right, it's just a view, so you can put anything you want.
If you want a custom MKAnnotationView you will need to capture the touch and handle the rest.


text:
Q: How to set child process' environment variable in Makefile I would like to change this Makefile:
SHELL := /bin/bash
PATH  := node_modules/.bin:$(PATH)

boot:
    @supervisor         \
      --harmony         \
      --watch etc,lib       \
      --extensions js,json      \
      --no-restart-on error     \
        lib

test:
    NODE_ENV=test mocha         \
      --harmony             \
      --reporter spec       \
        test

clean:
    @rm -rf node_modules

.PHONY: test clean

to:
SHELL := /bin/bash
PATH  := node_modules/.bin:$(PATH)

boot:
    @supervisor         \
      --harmony         \
      --watch etc,lib       \
      --extensions js,json      \
      --no-restart-on error     \
        lib

test: NODE_ENV=test
test:
    mocha                   \
      --harmony             \
      --reporter spec       \
        test

clean:
    @rm -rf node_modules

.PHONY: test clean

Unfortunately the second one does not work (the node process still runs with the default NODE_ENV.
What did I miss?

A: I would re-write the original target test, taking care the needed variable is defined IN THE SAME SUB-PROCESS as the application to launch:
test:
    ( NODE_ENV=test mocha --harmony --reporter spec test )

A: I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make.
SHELL := /bin/bash

.PHONY: test tests
test tests:
    PATH=./node_modules/.bin/:$$PATH \
    JSCOVERAGE=1 \
    nodeunit tests/

A: Make variables are not exported into the environment of processes make invokes... by default.  However you can use make's export to force them to do so.  Change:
test: NODE_ENV = test

to this:
test: export NODE_ENV = test

(assuming you have a sufficiently modern version of GNU make >= 3.77 ).

A: As MadScientist pointed out, you can export individual variables with:
export MY_VAR = foo  # Available for all targets

Or export variables for a specific target (target-specific variables):
my-target: export MY_VAR_1 = foo
my-target: export MY_VAR_2 = bar
my-target: export MY_VAR_3 = baz

my-target: dependency_1 dependency_2
  echo do something

You can also specify the .EXPORT_ALL_VARIABLES target to—you guessed it!—EXPORT ALL THE THINGS!!!:
.EXPORT_ALL_VARIABLES:

MY_VAR_1 = foo
MY_VAR_2 = bar
MY_VAR_3 = baz

test:
  @echo $$MY_VAR_1 $$MY_VAR_2 $$MY_VAR_3

see .EXPORT_ALL_VARIABLES


text:
Q: How to Change Intel OEM Bios Information (e.g. Serial Number, Manufacturer?) We purchase some of our systems (desktops mainly) through a small third-party OEM. They don't include serial number, manufacturer info., etc. in the BIOS however and this makes it difficult for systems monitoring and inventorying software to distinguish one system from another - especially if we do a clean wipe on the system. MAC addresses are semi-reliable, but not truly unique.
I'd like to add some info. - such as manufacturer and serial number / asset tag into the bios (there are fields for it), but I can't edit it through the normal BIOS menu. Any idea on how this can be accomplished?

A: You can try using IPMI commands to write the relevant information into the VPD… but good luck finding out exactly where you need to write. That's likely information specific to the particular motherboard model.
I just needed to figure this out for my own purposes ;)
You should be able to use either:
ipmitool fru edit/read/write ...
or
flshupdt (from Intel, for Intel motherboards)
to update the FRU data.
However, your statement:

MAC addresses are semi-reliable, but not truly unique

is incorrect - MAC addresses should be, by definition, unique. That would be an appropriate value to key off for inventory purposes.


text:
Q: Switching activities on lockscreen shows lockscreen So I'm making an app for my company, for a android tablet to be used like a "kiosk". Users should only be able to use this one app, and be able to do nothing else on the tablet.
I've found a solution by using WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED on the activities. However, when I switch to another activity in my app, the leaving activity fades out, shows the lock screen quickly and then the next activity appears.
I'm guessing that this is because the FLAG_SHOW_WHEN_LOCKED is in onCreate(), as opposed to earlier in the Activity creation process.
Is there anywhere else I can put this flag, or any other way to prevent the lockscreen to be shown between activities? It's not a huge issue, but it is a poor user experience.
It is a Samsung Galaxy Tab 10.1 Running ICS 4.0.3.

A: I was able to best fix this by using Fragments and using FragmentManager to swap out the fragments in the activity, so the lockscreen was never shown, since I never left the activity. The android developer guide has a good example for this.
http://developer.android.com/reference/android/app/Fragment.html


text:
Q: How to test file uploads to an API using Mockery and PHPUnit I'm using PHPUnit to test my API but I'm unsure as to how to test file uploads.
I watched this Laracast lesson which has given me a good insight into how to use Mockery to mock the uploads, but in my case I'm trying to test an API and, for whatever reason, I can't get my test to Green.
My test code:
namespace App;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Mockery as m;

class ApiResourcesControllerTest extends \TestCase
{
    /** @test */
    function a_user_can_upload_a_resource()
    {
        $file = m::mock(UploadedFile::class, [
            'getClientOriginalName' => 'test.jpg'
        ]);

        $file->shouldReceive('move') // the uploaded file is moved
             ->once()
             ->with('uploads', 'now-test.jpg');

        $files = ['file' => $file]; // endpoint expects Input::file('file);

        // this endpoint definitely works
        $this->call('POST', 'api/resources/upload', [], [], $files);
        $this->dump(); // for the mean time just dump the response
    }
}

function time()
{
    return 'now';
}

I know that the api/resources/upload endpoint works just fine, but my test code returns the following error:
Mockery\Exception\InvalidCountException: Method move("uploads", "now-test.jpg") from Mockery_0_Symfony_Component_HttpFoundation_File_UploadedFile should be called exactly 1 times but called 0 times.

Where am I going wrong?
Examples of mocking file uploads to an API would be appreciated.


text:
Q: Different output when executing script manually and via cron/jenkins job I have a shell script which opens sqlplus and select some data from db containing chinese characters. When I execute it manually, the output contains those characters. When I do it via cron or jenkins job, it displays question marks instead of chinese characters. Any advice ?

A: It was enviroment variable issue. I just added . $HOME/.bash_profile beofre main script execution in crontab.
00 10 * * * . $HOME/.bash_profile; /home/scripts/script.sh


text:
Q: Synonym returning ORA-00904 error I'm at my wits' end with this error.
I have a view which uses a function contained in a package in another schema. I've created a synonym to said package, and on my local dev DB, the view compiles correctly. On the build server, the view gives compilation errors.
When I run the select of the view manually, Oracle throws an ORA-00904 error on the synonym in the query. I just can't understand why it works in one place and not the other. The code on both servers is identical, as it's coming from our source control repository.

A: As phlogratos suggested, it was a privileges issue. As the user didn't have execute permissions on the package in the separate schema, it was causing this error.
The underlying problem was an issue with our script that applies grants, but it's good to know that references like this without permissions fail in this manner.


text:
Q: Call Python from .NET I have some code written in Python which can not be transferred to a .NET language. I need to call one of these functions from my .NET WinForms application.
Now, I do it by starting the Python script as a separate process and pass parameters to it as command line arguments. It works, but I don't really like this solution. I'd like to improve it to a better one.
Is there any better way to call a function of a .py script from a .NET application? What is the best way to do it?
Note: IronPython is NOT an option for this Python script

A: Besides the COM option, you could make your Python script instantiate a xmlrpc server -
it is quite transparent and you never have to deal with "xml" on your own code.
Then, on .net side, you simply connect to your python app via xmlrpc - if there is no suitable way to do that in C#, just write a client function in IronPython.
The SimpleXMLRPCServer example on Python documentation is enough for that:
http://docs.python.org/library/simplexmlrpcserver.html

A: I think you need to re-evaluate Carlos' answer.
See the section Implementing COM Objects with Python in Mark Hammond's book Python Programming on Win32.
You should be able to create a COM object, then have .Net interact with it.
From the book the following will create a COM server with a single method.
# SimpleCOMServer.py - A sample COM server - almost as small as they come!
#
# We expose a single method in a Python COM object.
class PythonUtilities:
    _public_methods_ = [ 'SplitString' ]
    _reg_progid_ = "PythonDemos.Utilities"
    # NEVER copy the following ID
    # Use "print pythoncom.CreateGuid()" to make a new one.
    _reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}"

    def SplitString(self, val, item=None):
        import string
        if item != None: item = str(item)
        return string.split(str(val), item)

# Add code so that when this script is run by
# Python.exe, it self-registers.
if __name__=='__main__':
    print "Registering COM server..."
    import win32com.server.register
    win32com.server.register.UseCommandLine(PythonUtilities)

The book goes on to say ".. you can do this by executing the code as a normal Python script. The easiest way to do this is to open the source file in PythonWin and use the Run command from the File menu. "
I think you need the ActivePython distribution from Activestate to do it.
See this question Consuming Python COM Server from .NET

A:
It works, but I don't really like this solution, I'd like to improve it to a better one.

No, AFAIK there isn't a better solution, especially if IronPython is a no-no for you. So you could still keep this as a temporary workaround while waiting for the script to be migrated to .NET or until you find that someone already wrote a library on .NET that provides you with similar functionality.

A: Create a COM .dll from a .py script and use Interop in your .NET code.
Have a look here: http://docs.python.org/faq/windows.html

A: PythonNet should help with this one. It enables you to call python code from C#.
A cleaner way is to expose the python script via a Flask REST API and consume that from your .NET Application. Don't forget to put proper authentication in place.

A: This might be a lot more work than launching the Python process, but here's an alternate solution.
You can embed Python into another program.  The API is for C and Interop from .NET will probably be a major pain.  If you're into a bit of a safer way to handle the native Python API, you can look into Boost.Python, which, among its less advertised features, has support for embedding.
With these tools, you can write a C++ managed DLL that uses Boost.Python to load the Python interpreter and execute any Python script.  Thus, you can execute any Python code directly in the hosting process, eliminating the use of an external process and any form of IPC.
Edit: AFAIK, all you have to add to your installation procedure is the deployment of the Python DLL and Boost.Python DLL.


text:
Q: Given a random value and its expected value, how can you determine if another random variable exists? Suppose there exists a random variable $X$ with $E[X] = 1$, can $E[2^{-X}] = \frac{1}{4}$ exist? Can $E[2^X] = 8$ exist? Is there a general method to solve this type of problem?

A: By Jensen's inequality, if the expectations involved are finite, and if $f(t)$ is a convex function, we have $f(E[X]) \le E[f(X)]$.  This limits the possible values.
Now note $2^{-t}, 2^t$ are both convex, so work out the bounds implied by Jensen.


text:
Q: Spring Webflow action-state else I have a problem with a webflow action-state. The structure I want is:
if...else if....else if .....else
In my action state (see below),

*

*I call getTestTypeName();

*This method returns a string. There could be ten valid values
although currently there are only two.

*However, I may also get an invald String which is not an error but
needs to be sent to a specified view-state.

*How do I do this. Currently, I get an error

<action-state id="selectPostITSAction">
    <evaluate expression="testEntranceViewService.getTestTypeName(flowScope.vwUser)" />

        <transition on="ProgramChoiceTemplate" to="paymentGateway" />

 <transition on="CPCFeedbackTemplate" to="report" >
  <evaluate  expression="testEntranceViewService.reactivateTestOnHold(vwUser, flowRequestContext)"
    result="flowScope.vwUser" />
 </transition>

 <transition on="error" to="entry" />

</action-state>

"Prototype Test Template1467832258812" is an invalid option but I cannot handle with webflow. I get this error is

ExceptionNo transition was matched on the event(s) signaled by the [1] action(s) that executed in this action state 'selectPostITSAction' of flow 'flow-entry'; transitions must be defined to handle action result outcomes -- possible flow configuration error? Note: the eventIds signaled were: 'array['Prototype Test Template1467832258812']', while the supported set of transitional criteria for this action state is 'array[ProgramChoiceTemplate, CPCFeedbackTemplate, error]'org.springframework.webflow.engine.NoMatchingTransitionException

A: Ok, got it
The answer is to have a transition with no "on="
See below

<action-state id="selectPostITSAction">
    <evaluate expression="testEntranceViewService.getTestTypeName(flowScope.vwUser)" />

        <transition on="ProgramChoiceTemplate" to="paymentGateway" />

 <transition on="CPCFeedbackTemplate" to="report" >
  <evaluate  expression="testEntranceViewService.reactivateTestOnHold(vwUser, flowRequestContext)"
    result="flowScope.vwUser" />
 </transition>

  <transition  to="expectedError" >

 <transition on="error" to="entry" />

</action-state>


text:
Q: IQueryable losing the ORDER BY Can anyone explain why this is happening?
Dim lReturn As IQueryable(Of Inventory) = context.Inventories.OrderBy(Function(o) o.SortOrder)

'' --- In the sql profiler, I can see Order by is added
'' Dim lst = lReturn.ToList

If Not loggedInUser.IsAdmin Then
    lReturn = lReturn.Where(Function(x) x.AdminOnly = False)
    '' --- In the sql profiler, I can see Order by is added
    '' Dim lst = lReturn.ToList

    lReturn = From f In lReturn
              Group Join a In context.AssignServices On f.ID Equals a.Id Into fas = Group
              From a In fas.Where(Function(x) x.AgentId = loggedInUser.CompanyId).DefaultIfEmpty()
              Where a.Assign = True OrElse f.isVisibleToAllAgents = True
              Select f
    '' --- In the sql profiler, I can see **Order by is not included**
    Dim lst = lReturn.ToList     ''*Problem is here*

End If

lReturn has already contained the Order By in the beginning which is a Lambda expression. If the user is not admin the last Linq query does not include order by for some reason.
I am using the sql profiler to find out how the query looks and it is as follows
exec sp_executesql N'SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name],
.........
[Extent1].[SortOrder] AS [SortOrder]
FROM  [dbo].[Inventories] AS [Extent1]
LEFT OUTER JOIN [dbo].[AssignService] AS [Extent2] ON ([Extent1].[ID] = [Extent2].[Id]) AND ([Extent2].[AgentId] = @p__linq__0)
WHERE (0 = [Extent1].[AdminOnly]) AND ([Extent2].[Assign] = 1 OR [Extent1].[isVisibleToAllAgents] = 1) ,N'@p__linq__0 int',@p__linq__0=112

Is it a regular behavior? or Am I missing something?

A: LINQ based ORMs have loosed rules around what particular order by patterns are supported. What's always supported (according to my experience) is ordering at the end of the query with only Where and Select operations after it.
Probably the order by gets lost at the join. Doesn't surprise me.


text:
Q: Cocos2d (iOS) + SneakyInput. The best way to handle joystick (joypad) events? I have seen at least two ways:
1)to handle the touch screen events
2)to schedule a repeatable task which will send a joypad state to an object. The original link:
link

A: I have chosen the second way. But additionally I use a timer instance for repeating pressing button event.
I have also created a constants which mean all the possible joypad states (sneakyinput joypad states are represented by numbers by default)


text:
Q: Extract text from dynamic Web page using R I am working on a data prep tutorial, using data from this article: https://www.nytimes.com/interactive/2021/01/19/upshot/trump-complete-insult-list.html#
None of the text is hard-coded, everything is dynamic and I don't know where to start. I've tried a few things with packages rvest and xml2 but I can't even tell if I'm making progress or not.
I've used copy/paste ang regexes in notepad++ to get a tabular structure like this:

Target
Attack

AAA News
Fake News

AAA News
Fake News

AAA News
A total disgrace

...
...

Mr. ZZZ
A real nut job

but I'd like to show how to do everything programmatically (no copy/paste).
My main question is as follows: is that even possible with reasonable effort? And if so, any clues on how to get started?
PS: I know that this could be a duplicate, I just can't tell of which question since there are totally different approaches out there :\

A: I used my free articles allocation at The NY Times for the month, but here is some guidance. It looks like the web page uses several scripts to create and display the page.
If you uses your browser's developer tools and look at the network tab, you will find 2 CSV files:

*

*tweets-full.csv located here: https://static01.nyt.com/newsgraphics/2021/01/10/trump-insult-complete/8afc02d17b32a573bf1ceed93a0ac21b232fba7a/tweets-full.csv

*tweets-reduced.csv located here: https://static01.nyt.com/newsgraphics/2021/01/10/trump-insult-complete/8afc02d17b32a573bf1ceed93a0ac21b232fba7a/tweets-reduced.csv
It looks like the reduced file creates the table quoted above and the tweets-full is the full tweet. You can download these files directly with read.csv() and the process this information as needed.
Be sure to read the term of service before scraping any webpage.

A: Here's a programatic approach with RSelenium and rvest:
library(RSelenium)
library(rvest)
library(tidyverse)
driver <- rsDriver(browser="chrome", port=4234L, chromever ="87.0.4280.87")
client <- driver[["client"]]
client$navigate("https://www.nytimes.com/interactive/2021/01/19/upshot/trump-complete-insult-list.html#")
page.source <- client$getPageSource()[[1]]

#Extract nodes for each letter using XPath
Letters <- read_html(page.source) %>%
  html_nodes(xpath = '//*[@id="mem-wall"]/div[2]/div')

#Extract Entities using CSS
Entities <- map(Letters, ~ html_nodes(.x, css = 'div.g-entity-name') %>%
                  html_text)

#Extract quotes using CSS
Quotes <- map(Letters, ~ html_nodes(.x, css = 'div.g-twitter-quote-container') %>%
                            map(html_nodes, css = 'div.g-twitter-quote-c') %>%
                            map(html_text))

#Bind the entites and quotes together. There are two letters that are blank, so fall back to NA
map2_dfr(Entities, Quotes,
         ~ map2_dfr(.x, .y,~ {if(length(.x) > 0 & length(.y)){data.frame(Entity = .x, Insult = .y)}else{
                                                        data.frame(Entity = NA, Insult = NA)}})) -> Result

#Strip out the quotes
Result %>%
  mutate(Insult = str_replace_all(Insult,"(^")|([ .,!?]?")","") %>% str_trim) -> Result

#Take a look at the result
Result %>%
  slice_sample(n=10)
                   Entity                                                              Insult
1             Mitt Romney                                       failed presidential candidate
2         Hillary Clinton                                                             Crooked
3  The "mainstream" media                                                           Fake News
4               Democrats                                             on a fishing expedition
5           Pete Ricketts                                             illegal late night coup
6  The "mainstream" media                                                   anti-Trump haters
7     The Washington Post do nothing but write bad stories even on very positive achievements
8               Democrats                                                                weak
9             Marco Rubio                                                         Lightweight
10     The Steele Dossier                                                      a Fake Dossier

The xpath was obtained by inspecting the webpage source (F9 in Chrome), hovering over elements until the correct one was highlighted, right clicking, and choosing copy XPath as shown:


text:
Q: Pros and cons of using Murmur3 hash as a primary key in database I'm working on creating database, there are multiple tables such as Apps, Space, Builds, Processes.
The app which I'm going to use this database for is like a real-time dashboard for platform monitoring, and the database will update every second with new information.
Rows will be repeated with apps_guid whenever new information is received and that is the reason I can not use apps_guid as a primary key.
I'm planning to use Murmur3 hash as a primary key in these tables and use to check duplicates.
I know Cassandra uses it as a primary key but not sure how it will preform in relational databases, is it a good idea? do you have any better recommendations?
Apps Column:
--
id int IDENTITY
app_guid binary
name varchar(255)
state varchar(255)
created_at datetime
updated_at datetime
type varchar(255)
stack varchar(255)
apphash binary PK
timestamp datetime

A: It's never a good idea to use a hash function for a primary key.
Cassandra doesn't use it this way, it can use murmur to define the partition/shard where the record goes, which is totally different.
Hash functions have collisions. It's OK for them because they are not supposed to be used to guarantee uniqueness. You get a fixed output for a variable size input. It's quite self-explanatory why collisions are fine for this class of functions.
There are different algorithms that can generate a unique ID even for a very high volume of ingestion/input.
You can either create a separate GUID(different from your apps_guid) or look into more sophisticated algorithms like:

*

*FlakeId(example)

*ksuid(https://github.com/segmentio/ksuid)

But there are others...
Also check Instagram's approach; nice article from Segment and this paper.


text:
Q: Proper Way to Shift Integer Into List Index Range I need to retrieve the item at index i from list l. However, sometimes i falls outside of the range of the list index and throws an IndexError. I need to shift i to always be inside the range of the list index by leaps of len(l). The following code achieves just that.
l = ['a', 'b', 'c', 'd', 'e']

i = 6

while i >= len(l):
    i -= len(l)
while i < 0:
    i += len(l)

item = l[i] # item = 'b'

For my use case, i never falls more than len(l) out of range in either direction, so I'm able to shorten to this one liner by using if statements instead of while statements.
l = ['a', 'b', 'c', 'd', 'e']

i = -3

i = i-len(l) if i >= len(l) else i+len(l) if i < 0 else i

item = l[i] # item = 'c'

I'm thinking there must be some builtin function that achieves just this result, without a long, logical sentence. Is there a proper way to do this?

A: Seems like a perfect use case for the modulo operator.
item = l[i % len(l)]

A: How about i = max(0, min(i, len(lst)-1))
lst = list(range(5))

i = 25
i = max(0, min(i, len(lst)-1))
print(lst[i])

i = -25
i = max(0, min(i, len(lst)-1))
print(lst[i])

Output
4
0

A: No, there's no built-in function to do this.  But it's simple to create one.
def clamp(x, size):
    return max(0, min(x, size-1))


text:
Q: How to know if Kubernetes job is done? I use Python kubernetes-client, and want to wait if the job is done:
api_instance.create_namespaced_job("default", body, pretty=True)

This call just makes a submit job, it will return the response even though the job is still running. How can I wait for the job to finish?

A: I found the solution. You can recognize the job is complete by watching the jobs and observing the events:
from kubernetes import client, config, watch

config.load_kube_config()
api_client = client.BatchV1Api()
print("INFO:    Waiting for event to come up...")
w = watch.Watch()
for event in w.stream(api_client.list_job_for_all_namespaces):
    o = event['object']
    print(o)
    if (o.status.... = "Complete"): ....

A: The only way I managed to do this is calling in the loop:
api_instance.read_namespaced_job_status()

...and check the result status.
You can reach the same by calling kubectl wait but it's not python. You can clone kubectl sources (in Go) and find how the hell they do it there.

A: from kubernetes import client, watch

def wait_for_job(self):
    logger.info("Waiting for job to complete...")
    w = watch.Watch()
    # timeout_seconds=0 -> will run watch for infinite time, but doesn't raise exception when wait is over
    # _request_timeout=timeout -> it is max timeout for request
    for event in w.stream(
        client.BatchV1Api().list_namespaced_job,
        namespace=self.namespace,
        label_selector=f"job-name={self.job_name}",
        timeout_seconds=0,
        _request_timeout=self.active_deadline_seconds
    ):
        o = event["object"]

        print(o.metadata.name)
        if o.status.succeeded:
            w.stop()
            return

        if not o.status.active and o.status.failed:
            w.stop()
            raise Exception("Job Failed")


text:
Q: Python - Split array into multiple arrays I have a array contains file names like below:
['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png', '003_1.png', '003_2.png', '003_3.png', '003_4.png', ....]

I want to quickly group these files into multiple arrays like this:
[['001_1.png', '001_2.png', '001_3.png'], ['002_1.png', '002_2.png'], ['003_1.png', '003_2.png', '003_3.png', '003_4.png'], ...]

Could anyone tell me how to do it in few lines in python?

A: If your data is already sorted by the file name, you can use itertools.groupby:
files = ['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png',
        '003_1.png', '003_2.png', '003_3.png']

import itertools

keyfunc = lambda filename: filename[:3]

# this creates an iterator that yields `(group, filenames)` tuples,
# but `filenames` is another iterator
grouper = itertools.groupby(files, keyfunc)

# to get the result as a nested list, we iterate over the grouper to
# discard the groups and turn the `filenames` iterators into lists
result = [list(files) for _, files in grouper]

print(list(result))
# [['001_1.png', '001_2.png', '001_3.png'],
#  ['002_1.png', '002_2.png'],
#  ['003_1.png', '003_2.png', '003_3.png']]

Otherwise, you can base your code on this recipe, which is more efficient than sorting the list and then using groupby.

*

*Input: Your input is a flat list, so use a regular ol' loop to iterate over it:
for filename in files:

*Group identifier: The files are grouped by the first 3 letters:
group = filename[:3]

*Output: The output should be a nested list rather than a dict, which can be done with
result = list(groupdict.values())

Putting it together:
files = ['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png',
        '003_1.png', '003_2.png', '003_3.png']

import collections

groupdict = collections.defaultdict(list)
for filename in files:
    group = filename[:3]
    groupdict[group].append(filename)

result = list(groupdict.values())

print(result)
# [['001_1.png', '001_2.png', '001_3.png'],
#  ['002_1.png', '002_2.png'],
#  ['003_1.png', '003_2.png', '003_3.png']]

Read the recipe answer for more details.

A: Something like that should work:
import itertools

mylist = [...]
[list(v) for k,v in itertools.groupby(mylist, key=lambda x: x[:3])]

If input list isn't sorted, than use something like that:
import itertools

mylist = [...]
keyfunc = lambda x:x[:3]
mylist = sorted(mylist, key=keyfunc)
[list(v) for k,v in itertools.groupby(mylist, key=keyfunc)]

A: You can do it using a dictionary.
list = ['001_1.png', '001_2.png', '003_3.png', '002_1.png', '002_2.png', '003_1.png', '003_2.png', '003_3.png', '003_4.png']

dict = {}
for item in list:
  if item[:3] not in dict:
    dict[item[:3]] = []
  dict[item[:3]].append(item)

Then you have to sort the dictionary by key value.
dict = {k:v for k,v in sorted(dict.items())}

The last step is to use a list comprehension in order to achieve your requirement.
list = [v for k,v in dict.items()]
print(list)

Output
[['001_1.png', '001_2.png'], ['002_1.png', '002_2.png'], ['003_3.png', '003_1.png', '003_2.png', '003_3.png', '003_4.png']]

A: Using a simple iteration and dictionary.
Ex:
l = ['001_1.png', ' 001_2.png', ' 003_3.png', ' 002_1.png', ' 002_2.png', ' 003_1.png', ' 003_2.png', ' 003_3.png', ' 003_4.png']
r = {}
for i in l:
    v = i.split("_")[0][-1]
    if v not in r:
        r[v] = []
    r[v].append(i)
print(r.values())

Output:
[['001_1.png', ' 001_2.png'], [' 003_3.png', ' 003_1.png', ' 003_2.png', ' 003_3.png', ' 003_4.png'], [' 002_1.png', ' 002_2.png']]

A: If your list is ordered like this here is a short script for this task.
myList = []
for i in a:
    if i[:-4].endswith('1'):
        myList.append([i])
    else:
        myList[-1].append(i)

# [['001_1.png', '001_2.png', '003_3.png'], ['002_1.png', '002_2.png'], ...]

A: #IYN

mini_list = []
p = ['001_1.png', '001_2.png', '001_3.png', '002_1.png','002_2.png', '003_1.png', '003_2.png', '003_3.png', '003_4.png']
new_p = []

for index, element in enumerate(p):
    if index == len(p)-1:
        mini_list.append(element)
        new_p.append(mini_list)
        break

    if element[0:3]==p[index+1][0:3]:
        mini_list.append(element)

    else:
        mini_list.append(element)
        new_p.append(mini_list)
        mini_list = []

print (new_p)

The code above will cut the initial list into sub lists and append them as individual lists into a resulting, larger list.
Note: not a few lines, but you can convert this to a function.
def list_cutter(ls):
    mini_list = []
    new_list = []

    for index, element in enumerate(ls):
        if index == len(ls)-1:
            mini_list.append(element)
            new_list.append(mini_list)
            break

        if element[0:3]==ls[index+1][0:3]:
            mini_list.append(element)

        else:
            mini_list.append(element)
            new_list.append(mini_list)
            mini_list = []

    return new_list


text:
Q: How to specify dependencies in qt_add_qml_module (CMake for Qt 6.2) When using qt_add_qml_module to specify a QML module, how do you handle Qt modules that it depends on (e.g. QtMultimedia)?

If I have class Synthesizer that extends QML, but which has no dependencies, the following works fine:
qt_add_qml_module(Synth
    URI Synth
    VERSION 1.0
    SOURCES
        Synthesizer.h Synthesizer.cpp
)

target_include_directories(Synthplugin
     PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}
)

target_link_libraries(myapp
    PRIVATE Qt6::Quick
    Synth
)

However if Synthesizer uses QtMultimedia classes, then this is insufficient, and results in errors like:
Undefined symbols for architecture arm64:
  "QAudioSink::start()", referenced from:
      Synthesizer::start() in Synthesizer.cpp.o

A: There is no ideal solution to that issue, AFAIK... but there are solutions.
On most systems, you can ignore unresolved symbols using compiler options (it can be useful when building a shared library, such as a QML plugin, where the symbols will be resolved later when building the executable). With gcc it looks like:
add_link_options(-Wl,--unresolved-symbols=ignore-all)

This is however not available on all systems. It seems like this isn't an option when building for Windows (see Cygwin g++ --unresolved-symbols=ignore-all).
For that case, you have another solution, which consists in using link_libraries:
link_libraries(Qt6::Multimedia)

qt_add_qml_module(Synth
  URI Synth
  VERSION 1.0
  SOURCES Synthesizer.h Synthesizer.cpp
)

...

The downside is that link_libraries applies for all the targets within the current directory or sub-directories... so you might've to restructure your makefiles. But it does the trick.

A: I now have a solution that I have been using for a while (but had forgotten this question lay unanswered).
First, make sure the Multimedia package is loaded. e.g.
find_package(Qt6 6.2 COMPONENTS Qml Quick Multimedia REQUIRED)

Then, after your qt_add_qml_module() link it to the Synth target:
target_link_libraries(Synth PRIVATE Qt6::Multimedia)

Also note that your target_include_directories() should be using the target Synth not Synthplugin and I would make it PRIVATE as there is no need to make it public. i.e.
target_include_directories(Synth PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})


text:
Q: Confused with how javascript return works I am trying to write the following code using jquery. This reads json from a website and creates a string which I want to return but it always returns "undefined". What am I missing here?
  function getTenders(wardName){
  output = "";
  $.getJSON('http://192.168.1.105:3000/getTenders.json?name='+wardName, function (obj) {
    //console.log(body); // Print the google web page.
    for(var i=0; i < obj.length; i++){
      var pid = "Project id: " + obj[i].id;
      var status = "Status: " + obj[i].status;
      var title = "Title: " + obj[i].title;
      var cost = "Estimated Cost: Rs " + obj[i].estimated;
      output += pid + "\n" + status + "\n" + title + "\n"  + cost + "\n\n";
    }
    console.log("Output: "+ output) // This prints correct output
    return output // Returning output here
  });
}

// But this shows undefined

console.log(printTenders("Somevalue")) // This outputs undefined. How can that happen?


text:
Q: Checkbox input undefined when unchecked - AngularJS I have an issue with my AngularJS checkbox where they become undefined when they are unchecked. Can't figure out why this is happening.
<input type="checkbox" name="available" ng-model="formData.available" ng-true-value="1" ng-false-value="0" required>

With the above code; default on page load is 0. when Its checked it becomes 1. When I uncheck it it becomes undefined
Any help appreciated.

A: Thanks to the comments I've realised that the required option is not necessary and was the cause of the issue. Thanks guys!

A: If you need the required attribute set ng-model-options="{ allowInvalid: true }" so undefined becomes false on the model.
https://docs.angularjs.org/api/ng/directive/ngModelOptions