text:
Q: Which event gets dispatched when Update Cart action is triggered in magento 2? I am trying to modify the subtotal in the checkout/cart page when the item gets updated using the Update Cart action button on the product page. After the product has been successfully added to the cart for the very first time, I tried to intercept the below events when I click on the Edit button from the checkout/cart page then I click on Update Cart button from product page. I really want to learn this concept it would be really helpful for me if someone can guide me. Though I will try my best to solve and update here.
checkout_cart_update_items_before
checkout_cart_update_items_after
checkout_cart_product_update_after

checkout_cart_update_items_before and checkout_cart_update_items_after does not get called at all not sure why no errors or warnings. Well, I was able to intercept checkout_cart_product_update_after where I added my custom code and results in me the highlighted part in the image. Now I am trying to update the subtotal by adding that digitization fee to it. So the subtotal should show around $30 on the checkout/cart page after the subtotal has been updated. Also, this is a configurable product that I am working with
\app\code\Noname\Checkout\etc\events.xml
<event name="checkout_cart_product_update_after">
        <observer name="noname_cart_product_update_after" instance="Noname\Checkout\Observer\CartUpdateProductAfter" />
    </event>

\app\code\Noname\Checkout\Observer\CartUpdateProductAfter.php
<?php
namespace Noname\Checkout\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class CartUpdateProductAfter implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer){
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        /** @var \Noname\Core\Helper\CustomerHelper$customerSession */
        $customerSession = $objectManager->create("\Noname\Core\Helper\CustomerHelper");

        //THIS BELOW CODE ADD A CUSTOM EXTRA OPTION TO THE ITEM

        $item = $observer->getQuoteItem();
        $additionalOptions = array();
        if ($additionalOption = $item->getOptionByCode('additional_options')){
            $additionalOptions = (array) unserialize($additionalOption->getValue());
        }
        $infoBuyRequest = $item->getBuyRequest()->getData();
        $digitizationfee = $infoBuyRequest['digitizationfee'];
        $additionalOptions[] = [
            'label' => 'Digitization Fee',
            'value' => $digitizationfee
        ];

        if(count($additionalOptions) > 0) {
            $item->addOption(array(
                'product_id' => $item->getProductId(),
                'code' => 'additional_options',
                'value' => serialize($additionalOptions)
            ));

            $customerSession->getSessionManager()->setData("last_updated_item",$item->getQuoteId());
        }
    }
}
?>


text:
Q: Country border between two points I am trying to extract country borders between two points, using Python. The border is a Shapely Polygon.exterior or LinearRing, the start and end points are Shapely Points.
My idea is the following:

*

*Get the closest points or projections for both points along the border

*These points split the border into two splines (or LineStrings). Select the shorter one, based on length (ideally reprojected to meters, but it might be overkill).

*Decide if the first and/or the last point of the selected spline is needed, to avoid zig-zag like splines at the ends. The given start and end points must be included in the final spline.

*Calculated border is: start_point + calculated_spline + end_point

So far I'm a bit stuck with the following concepts:

*

*Shapely doesn't support projection on LinearRing, only LineString. How can I calculate the closest points efficiently on a LinearRing? I believe projection isn't needed, as I'll be selecting whether to keep the end points in step 3. Should I just loop over all points of the LinearRing and select the closest one?

*How can I split a LinearRing into two LineStrings, based on two of their points?

*Is it true that when comparing relative segment lengths of a LinearRing, I can just measure their length in WGS84?

*When I have the LineString, should I use .project for deciding weather the endpoints should be included, to avoid zig-zag like splines?

A: I have a solution that works.
A LinearRing is also a LineString so use directly a LineString and you can project your points (using Shapely:Coordinate of the closest point on a line)
line = LineString(list(polygon.exterior.coords))
pt1  = line.interpolate(line.project(point1))
pt2  = line.interpolate(line.project(point1))

Now we need to know on what segments of the line are the points and construct the resulting lines from the first point to the second following the original polygon contour (using Determine if shapely point is within a linestring/multilinestring)
def pair(list):
   '''Iterate over pairs in a list -> pair of points '''
   for i in range(1, len(list)):
       yield list[i-1], list[i]

def extract(line, pp1,pp2):
    sol = []
    for seg_start, seg_end in pair(line.coords):
       a = Point(seg_start[0], seg_start[1])
       b = Point(seg_end[0], seg_end[1])
       # after first point found use original segments until second point was reached
       if len(sol) > 0:  # first point found
            if  LineString([a, b]).distance(pp2) < 1e-8: #second point found
                sol.append(list(LineString([a, pp2]).coords))
                return(MultiLineString(sol))
            else:
               sol.append(list(LineString([a, b]).coords))
       # find first point and construct first line
       if  LineString([a, b]).distance(pp1) < 1e-8:
            sol = [list(LineString([pp1, b]).coords)]  #c.append(list(LineString([pp1, b]).coords))

result = extract(line, pt1,pt2)

But here are some problems:

*

*you need to know if the polygon is oriented counter-clockwise or not (in a shapefile, the geometries are counter-clockwise)

*you need to know the positions of the points in relation to one another (what is the first point ?)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Override vendor/magento/module-ui/view/base/web/js/modal/confirm.js Magento2 Can anyone help how to over ride
vendor/magento/module-ui/view/base/web/js/modal/confirm.js

file in theme.
Thanks

A: create below path in your theme,
app/design/frontend/{Vendorname}/{themename}/Magento_Ui/web/js/modal/confirm.js

Run
php bin/magento setup:static-content:deploy

And Run
php bin/magento setup:upgrade

A: Rakesh Jesadiya solution worked for me on Magento 2.3, but I had to run the setup:upgrade before the setup:static-content:deploy


text:
Q: std::deque - произвольный доступ Оказывается есть произвольный, а есть последовательный доступ через итераторы.
К примеру итераторы на std::vector и std::deque - поддерживают итераторы с произвольным доступом.
Итераторы std::list - только с произвольным.
С std::vector - понятно - все элементы - располагаются непрерывно в памяти.
Тепер понятно и с std::list - это список с произвольным расположением в памяти, который содержит указатель на предыдущий и последующий элементы - отсюда и последовательный доступ.
Но, если std::deque - точно так же, как и std::vector - поддерживает произвольный доступ - то чем он отличается от std::vector ?

A: Главное отличие deque от vector - возможность О(1) вставки-удаления не только в конец, но и в начало (в отличие от О(n) для вектора - из-за необходисости полностью перемещать все данные).
Цена этого - то, что дек работает немного медленнее, и все свои данные НЕ хранит последовательно одним блоком в памяти.
P.S. Понравилась диаграмма он Harry, я ее тут добавлю.


text:
Q: Kaggle API issue "Could not find kaggle.json. Make sure it's located in......" I am trying to use the Kaggle API to extract data from the kaggle website. I am using Ubuntu 18.04. When I enter the following command:
kaggle competitions download -c home-credit-default-risk

I get the following error:
Traceback (most recent call last):
  File "/home/hduser/anaconda3/bin/kaggle", line 5, in <module>
    from kaggle.cli import main
  File "/home/hduser/anaconda3/lib/python3.7/site-packages/kaggle/__init__.py", line 23, in <module>
    api.authenticate()
  File "/home/hduser/anaconda3/lib/python3.7/site-packages/kaggle/api/kaggle_api_extended.py", line 149, in authenticate
    self.config_file, self.config_dir))
OSError: Could not find kaggle.json. Make sure it's located in /home/hduser/.kaggle/kaggle.json. Or use the environment method.

This is strange because I have the kaggle.json file saved in the correct directory and I have all permissions granted for it.
ls ~/.kaggle

returns:
kaggle.json

Am I missing something here?

A: I had the same problem.
Using Google's GCP notebook and after several attempts, I managed to resolve it as follows:
Generate the API file (JSON) through the Kaggle platform.
Execute:
https://adityashrm21.github.io/Setting-Up-Kaggle/

A: I have solved this. For some reason the following command works and not the one posted above.
~/.local/bin/kaggle competitions download -c home-credit-default-risk


text:
Q: Running time calculation in multi threading In my code:
public class thread1 implements Runnable {

public static void main(String[] args) {
    thread1 d = new thread1();
    new Thread(d).start();
    Thread t1 = new Thread(d);
    t1.start();
}

@Override
public void run() {
    for (int i = 0; i < 3; i++) {
        sleep1();
        sleep2();
    }
}

void sleep1() {
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

synchronized void sleep2() {
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

I ran my code and calculate its running time to finished.
The minimum time to finished was 7 seconds.
Why?
It should be 6 seconds, Because
3loops * 2seconds = 6seconds.

A: Because of context switching. sleep() is not a guaranteed amount of time, but is subject to other things going on in the system. It will try to come back, but may not succeed. Also, probably rounding in your IDE.

A: Program running time also accountable. You have put 6 secs to thread sleep. So Next thread will be executed. So context switching takes place.


text:
Q: Video from pipe->YUV with libAV->RGB with sws_scale->Draw with Qt I need to decode video from pipe or socket, then convert it set of images and draw with Qt(4.8.5!!).
I'm using default example of libAV and adding to it what i need.
Here is my code:
    AVCodec *codec;
    AVCodecContext *codecContext= NULL;
    int frameNumber, got_picture, len;
    FILE *f;
    AVFrame *avFrame, *avFrameYUV, *avFrameRGB;
    uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
    AVPacket avpkt;

    av_init_packet(&avpkt);

    f = fopen("/tmp/test.mpg", "rb");
     if (!f) {
         fprintf(stderr, "could not open /tmp/test.mpg\n");
         exit(1);
     }

     /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */
     memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);

     /* decode until eof */
     avpkt.data = inbuf;
     avpkt.size = fread(inbuf, 1, INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE, f);

    /* find the mpeg1 video decoder */
    codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);
    if (!codec) {
        fprintf(stderr, "codec not found\n");
        exit(1);
    }

    codecContext = avcodec_alloc_context3(codec);
    codecContext->get_format = &my_get_format;
    avFrameYUV = avcodec_alloc_frame();
    avFrameRGB = avcodec_alloc_frame();

    if(codec->capabilities&CODEC_CAP_TRUNCATED)
        codecContext->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */

    /* For some codecs, such as msmpeg4 and mpeg4, width and height
       MUST be initialized there because this information is not
       available in the bitstream. */

    /* open it */
    if (avcodec_open2(codecContext, codec, NULL) < 0) {
        fprintf(stderr, "could not open codec\n");
        exit(1);
    }

    /* the codec gives us the frame size, in samples */

    int srcX = 352;  //Size of output picture in example
    int srcY = 288;
    struct SwsContext *swsContext = sws_getContext(srcX, srcY, AV_PIX_FMT_YUV420P,
                                                srcX, srcY, PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL);
    frameNumber = 0;
    for(;;) {
        if (avpkt.size == 0)
            break;
        avpkt.data = inbuf;
        while (avpkt.size > 0) {
            len = avcodec_decode_video2(codecContext, avFrameYUV, &got_picture, &avpkt);
            if (len < 0) {
                fprintf(stderr, "Error while decoding frame %d\n", frameNumber);
                exit(1);
            }
            if (got_picture) {
                printf("saving frame %3d\n", frameNumber);
                fflush(stdout);

                sws_scale(swsContext, avFrameYUV->data, avFrameYUV->linesize, 0, dstY, avFrameRGB->data, avFrameRGB->linesize);

                myImage = new QImage(avFrameRGB->data[0], srcX, srcY, QImage::Format_RGB32);

                emit update(myImage); // Here i draw it to the screen
                usleep(50000);
                frameNumber++;
            }
            avpkt.size -= len;
            avpkt.data += len;
        }
    }

    avpkt.data = NULL;
    avpkt.size = 0;
    len = avcodec_decode_video2(codecContext, avFrameYUV, &got_picture, &avpkt);
    if (got_picture) {
        printf("saving last frame %3d\n", frameNumber);
        fflush(stdout);
        frameNumber++;
    }

    avcodec_close(codecContext);
    av_free(codecContext);
    avcodec_free_frame(&avFrameRGB);
    avcodec_free_frame(&avFrameYUV);

Now it doesn't work: "[swscaler @ 0xb0005460] bad dst image pointers" misstake, but the questions are:
-What i'm doing wrong globaly?
-Do i need a AVPicture? Like here ?
-Is QImage - best stuff do draw frame?
-I give sws_scale() two different initialized frames and it crashes. Why?

A: I would so something like this:
AVPicture m_Rgb;
int srcX = codecContext->width;
int srcY = codecContext->height;
struct SwsContext *swsContext = sws_getContext(srcX, srcY, codecContext->pix_fmt, srcX, srcY, PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL);
m_Rgb.linesize[0] = srcX * 4;
m_Rgb.data[0]     = (uint8_t*)malloc( m_Rgb.linesize[0] * srcY );
sws_scale(swsContext, avFrameYUV->data, avFrameYUV->linesize, 0, srcY, m_Rgb.data, m_Rgb.linesize );

QImage image( m_Rgb.data[0], srcX, srcY, QImage::Format_RGB32 );
image = image.copy(); // This makes a deep copy of the pixels. Currently image just has a copy of the m_Rgb.data[0] pointer

You can reuse m_Rgb over and over, and just delete it at the end.


text:
Q: google actions: reprompts not showing I am trying to get the system to prompt if the user is silent or not entered any response. This is using actions sdk.
As per the documentation (https://developers.google.com/actions/assistant/reprompts), I set the conversation object in the json as:
"inDialogIntents": [
    {
      "name": "actions.intent.NO_INPUT"
    }
  ]

Then, in the functions code I have the following:
app.intent('no_input', conv => {
  conv.ask('Hello');
});

Yet there has been no response even after waiting for a few minutes. I even tried
app.intent(actions.intent.NO_INPUT, conv => {
  conv.ask('Hello');
});

but the code has not been called. Can someone share what needs to be done to get this working? Thanks.

A: Here's a more detailed version of my comment:
First of all, smartphones DO NOT have no-input support, as they close the mic automatically when the user doesn't say anything and they also make it visually clear. So if you're testing on a smartphone, that's the reason you're not seeing your reprompts.
As for testing of the no-input prompts, it can be rather hard to test on a Google Home. Maybe you don't have access to one or you don't want to wait awkwardly staring at your device. For these reasons we have "No Input" button in the Simulator:

You can use this button to simulate a No Input prompt. If that still doesn't solve your problem, then you can assume there's something wrong with your code.


text:
Q: onCancelled() doesn't run even after cancel() is invoked and doInBackground() has finished I am having trouble with my AsyncTask class.
I am cancelling a task inside doInBackground() method and according to AsyncTask documentation, onCancelled() runs when cancel() is invoked and doInBackground has finished.
The task is successfully cancelled as I confirmed it using isCancelled() method, but onCancelled() method doesn't run after it.
from AsyncTask documentation,
protected void onCancelled ()

Applications should preferably override onCancelled(Object).
This method is invoked by the default implementation of onCancelled(Object).

Runs on the UI thread after cancel(boolean) is invoked
and doInBackground(Object[]) has finished.

This is my code for doInbackgroud() (not entire code is shown for simplicity) ,
  protected String doInBackground(Void... params) {
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        // do Something
                    } else {
                        mProgressDialog.dismiss();
                        Log.e("Status",isCancelled() + ", before cancel");
                        cancel(true);
                        Log.e("Status",isCancelled() + ", after cancel");
                    }
     return description.toString();
   }

and here is onCancelled() method,
I have tried this,
protected void onCancelled(String result) {
    Log.e("Status",isCancelled() + " oncancelled");
    Toast.makeText(c, "failed to load data !", Toast.LENGTH_LONG).show();
}

and this,
@Override
protected void onCancelled() {
    super.onCancelled();
    Log.e("Status",isCancelled() + " oncancelled");
    Toast.makeText(c, "failed to load data !", Toast.LENGTH_LONG).show();
}

and this,
@Override
protected void onCancelled(String result) {
    super.onCancelled();
    Log.e("Status",isCancelled() + " oncancelled");
    Toast.makeText(c, "failed to load data !", Toast.LENGTH_LONG).show();
}

the if part of doInbackground() works fine and runs onPostExecute(), but when the else condition is met then onCancelled() method is not executed even though the task is cancelled successfully.
This is the output in Logcat for else condition.
false, before cancel
true, after cancel

It confirms that the task was cancelled.
Why onCancelled() method is not executed if the task is cancelled successfully. ?

A: The issue is resolved,
the problem is,  doInBackground() method returns a String
return description.toString();

and the value of that String is set inside if block, but when else block is executed, the value of description.toString() isn't set and thus remains null, which caused doinBackground method to return a null value when else block is executed.
I am not sure why it caused the onCancelled() method to not execute and not throw any error or exception.
I returned another String inside else block and it fix the problem.
                  else {
                        mProgressDialog.dismiss();
                        Log.e("Status",isCancelled() + ", before cancel");
                        cancel(true);
                        Log.e("Status",isCancelled() + ", after cancel");
                        return "Something";
                    }


text:
Q: Why CoreData make entity fault after save? My steps:

*

*Create entity via .init(context: NSManagedObjectContext)

*Save context if it has changes. Save is succeded.

*Use this entity to set some values. Example: let newString = "test == \(entity.id.intValue)"
The problem that after step 2 the id value of the entity time to time become 0.
I did debug and there are two types of output:

*

*<Entity: 0x60000023def0> (entity: Entity; id: 0x600002777d40 <x-coredata:///UserEntity/tC5203E3F-0F4A-4937-B44A-45CD578382AA10>; data: <fault>)

*<Entity: 0x6000003c9f40> (entity: Entity; id: 0xab5e4a90b6dee4ba <x-coredata://3EC29A9F-A81A-49EC-B4BE-23004ECF10FF/UserEntity/p88>; data: { ...has data }
Also in the first situation isFault is true, is second it is false.
I can't understand why saving of the context can make entities fault?

A: I assume that the bug is probably somewhere in your code which you are NOT showing in your question. That is why I am just going to give you the function to fetch the value in the entity. If the code I post wont help then perhaps its the timing issue.
static let persistentContainer: NSPersistentContainer = {

let container = NSPersistentContainer(name: "YOUR_APPs_NAME")
container.loadPersistentStores { (_, error) in
  if let error = error as NSError? {
    fatalError("Unresolved error \(error), \(error.userInfo)")
  }
}

static var context: NSManagedObjectContext { return persistentContainer.viewContext }

func loadUserIsVerified() -> Id {

    var id : Id!
    let context = CoreDataStack.persistentContainer.viewContext
    let fetchRequest: NSFetchRequest< Id > = Id.fetchRequest()

    do {
        let ids = try context.fetch(fetchRequest)
        if(sessions.count > 0) {
            id = ids.first
        }
    } catch {
        print("Something happened while trying to retrieve tasks...")
    }
    return id
}


text:
Q: Changing specified values on numpy array in a certain dimension Wondering if there is an easy way to do this:
Say I have an numpy array with the shape (2,3,2), for example:
x =
[[[ 0, 1],
  [ 2, 3],
  [ 4, 5]],

 [[ 6, 7],
  [ 8, 9],
  [10,11]]]

If I wanted to replace all the entries that corresponded to axis=1 and position=0, with zero, I could do this easily:
x[:,0,:] = 0
x =
[[[ 0  0]
  [ 2  3]
  [ 4  5]]

 [[ 0  0]
  [ 8  9]
  [10 11]]]

However, what If I had a list of axes that I wanted to perform these operations on. Is there a built-in numpy function for this? Ideally it'd look something like this:
array_replace(array=x,axis=1,pos=0,replace_val=0)
Which would give the same array as above.
I can think of a way to do this by flattening matrices and calculating where the positions of each variable would be based on the dimension of each array, but I'm wondering if there is already something built into numpy.

A: You can construct a tuple of slices and then use the specific axis for the position. So you can define such function as:
def array_replace(array, axis, pos, replace_val):
    array[(slice(None),) * axis + (pos,)] = replace_val

So what we do is constructing a 1-tuple with a slice object (slice(None),). A slice object is what Python generates behind the curtains for a colon :. So x[:,0,:] is a simple representation for x[(slice(None),0,slice(None))].
Next we repeat this slice axis times (the number of times before the specified axis), followed by the position we want. The remaining slices are optional, so we do not specify these here. We then use numpy's broadcasting to assign the replace_val to all these indices.
This then generates:
>>> x
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5]],

       [[ 6,  7],
        [ 8,  9],
        [10, 11]]])
>>> array_replace(array=x, axis=1, pos=0, replace_val=0)
>>> x
array([[[ 0,  0],
        [ 2,  3],
        [ 4,  5]],

       [[ 0,  0],
        [ 8,  9],
        [10, 11]]])


text:
Q: when Jbutton is clicked either button is move or label text is changed. I just want to perform both import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JavaGUI extends JPanel {

    private Control control = new Control();
    private Keys keys = new Keys("Original starting value.");

    public JavaGUI() {
        this.setLayout(new GridLayout(0, 1));
        this.add(keys);
        this.add(control);

        private class Control extends JPanel {

            public Control() {
                this.add(new JButton(new AbstractAction("Update") {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("Command: " + e.getActionCommand());
                        keys.string = String.valueOf(System.nanoTime());
                        //keys.label.setText(keys.string);  //remove comments cause button move
                        JButton j = (JButton) e.getSource();
                        j.setLocation(j.getX() + 10, j.getY() + 10);
                    }
                }));
            }
        }

        private class Keys extends JPanel {

            private String string;
            private JLabel label = new JLabel();

            public Keys(String s) {
                this.string = s;
                label.setText(s);
                this.add(label);
            }
        }

        private void display() {
            JFrame f = new JFrame("JavaGUI");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(this);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }

        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {

                @Override
                public void run() {
                    new JavaGUI().display();
                }
            });
        }
    }

A: You are using a GridLayout so you can't just move components around randomly. I suggest you read the Swing tutorial on Laying Out Components Within a Container for an understanding of how layout management works.

A: I'll give all. The error was, that you set the String string, not the JLabel label.
Such behaviour, of something not having a GUI effect, could also have been caused by a missing invokeLater in actionPerformed.
You made classes for the used objects to set specific properties. That is a burocratic waste, hence I have rewritten it a bit.
If you resize the window, you'll see that the GridLayout manager again layouts, so that the JButton appears at its original position. You can use absolute positionwing with setLayout(null) using individual setLocations.
public class JavaGUI extends JPanel {

    private JPanel control;
    private JLabel keys;

    public JavaGUI() {
        setLayout(new GridLayout(0, 1));

        keys = new JLabel("Original starting value.");
        keys.setHorizontalAlignment(SwingConstants.CENTER);
        add(keys);

        control = new JPanel();
        control.setPreferredSize(new Dimension(200, 100));
        control.setMinimumSize(new Dimension(200, 100));
        control.setLayout(null);
        JButton button = new JButton(new AbstractAction("Update") {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Command: " + e.getActionCommand());
                keys.setText(String.valueOf(System.nanoTime()));
                //keys.label.setText(keys.string);  //remove comments cause button move
                JButton j = (JButton) e.getSource();
                j.setLocation(j.getX() + 10, j.getY() + 10);
            }
        });
        button.setBounds(10, 10, 90, 24);
        control.add(button);
        add(control);
    }

    public static void main(String[] args) {
        final JFrame f = new JFrame("JavaGUI");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JavaGUI());
        f.pack();
        f.setLocationRelativeTo(null);

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                f.setVisible(true);
            }
        });
    }
}

P.S. I have seen considerably worse code. This is actually neat code with only the superfluous classes.


text:
Q: Why is .gitignore not ignoring .DS_Store? In this case I want to ignore the files iOS uses, and in particular this file
.DS_Store

I created a .gitignore file as such
touch .gitignore

and put in a  single line
/.DS_Store

I push to a bare repo which has a hook to checkout to a full repo.
The file keeps showing up in my full repo.

A: You can also remove committed .DS_Store files like this: git rm --cached .DS_Store

A: As you mentioned in your comment, you've already committed the .DS_Store file.  To fix this, just remove the file and make a commit.  Then, as long as you have your .gitignore file set up and stored in your repo, you shouldn't see any more problems with .DS_Store files.


text:
Q: How to open log4j2 logs with Apache Chainsaw I'm having hard time opening my logs with Apache Chainsaw v2.
I wasn't able to succesfully open my logs with zeroconf, neither with default xmllayout. It worked like a charm for me in .net. But in Java it's a nightmare.
Main class:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Start {

    public static Logger logger = LogManager.getLogger(Start.class);

    public static void main(String[]args){
        logger.info("Example log info");
        logger.trace("Example log trace");
        logger.debug("Example log debug");
        logger.error("Example log error");
        logger.fatal("Example log fatal");
        logger.warn("Example log warn");
        return;
    }
}

Log4j2 configuration
    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ALL" advertiser="multicastdns">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="custom layout %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="log4j2Chainsaw" fileName="output.log" bufferedIO="false" advertiseURI="file:///C:/Users/gswiec/IdeaProjects/Log4j2ChainsawExample/output.log" advertise="true">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
        <File name="xmlLayoutForChainsaw" fileName="output.xml" bufferedIO="false" >
           <XmlLayout/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="trace">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="log4j2Chainsaw"/>
            <AppenderRef ref="xmlLayoutForChainsaw"/>
        </Root>
    </Loggers>
</Configuration>

Here is pom, all needed dependencies seems to be there.
 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>swiec.eu</groupId>
    <artifactId>Log4j2ChainsawExample</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--Log4j2 and apache chainsaw zeroconf dependencies-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>javax.jmdns</groupId>
            <artifactId>jmdns</artifactId>
            <version>3.4.1</version>
        </dependency>

        <!--XmlLayout dependencies-->
        <dependency>
            <groupId>com.fasterxml.woodstox</groupId>
            <artifactId>woodstox-core</artifactId>
            <version>5.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.9.0</version>
        </dependency>
    </dependencies>

</project>

Whole example project is available at https://github.com/swiec/eu.swiec.log4j2apacheexample
I would appreciate your help, also if you suggest different approach to get logs more readable. Apache chainsaw doesn't seems to be live project, I'm not sure if it's good idea using it.

A: You should test with an app that doesn't start and immediately exit, or it won't have time to advertise & have Chainsaw receive events.
I just added this to your Start.java file:
import java.util.Scanner;
...
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        int i = in.nextInt();

I also updated your log4j config - you need to use %m not %msg for the PatternLayout used to generate output.log
        <File name="log4j2chainsawappender" fileName="output.log" bufferedIO="false" advertiseURI="file://Users/scott/eu.swiec.log4j2apacheexample/output.log" advertise="true">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %m"/>

I then started Chainsaw v2 (very latest version in git), and started your app.
Once your app was started, I selected Chainsaw's 'connect to, log4j2chainsawappender', and a new tab appeared and correctly formatted your log events, parsing 'Start' as your logger, correct severity levels etc.


text:
Q: How to implement a global incrementing id for multiple tables in SQL? I decided back when I was coding to have different tables for each type of content. Now I am stuck solving this. Basically my notification system ranks the newest content by its timestamp currently. This is inaccurate however because there is a small chance that someone would submit content at the same time as another person, and incorrect ranking would occur.
Now if I had all my content in a single table, I would simply rank it by an auto-incrementing variable. Is there a way to implement this auto-increment integer across multiple tables (e.g. When something is inserted into table1, id=0, something is inserted into table2, id=1). Or do I have to recode all my stuff into a single table.
NOTE:
The reason I have content in multiple tables is because its organized and it would reduce load stress. I don't really care about the organization anymore, because I can just access the data through a GUI I coded, I'm just wondering about the load stress.
EDIT:
I'm using PHP 5 with MySQL.

A: Your question, particularly the need for ID spanning over multiple tables, is clearly signalizing that your database design needs change. You should make one table for all content types (as a generalization), with autoincrementing ID. Then, for each particular content type, you can define other table (equivalent of inheritance in OOP) with extra fields, and foreign key pointing to the basic table.
In other words, you need something like inheritance in SQL.

A: You can create a table with auto increment id just to keep track of ids. Your program would do an insert on that table, get the id, use it as necessary.
Something along the lines of:
function getNextId() {
    $res = mysql_query("INSERT INTO seq_table(id) VALUES (NULL)");
    $id = mysql_insert_id();
    if ($id % 10 == 0) {
        mysql_query("DELETE FROM seq_table");
    }
    return $id;
}

Where seq_table is a table that you've to create just to get the ids. Make it a function so it can be used whenever you need. Every 10 ids generated I delete all generated ids, anyway you don't need them there. I don't delete every time since it would slow down. If another insert happen in the meantime and I delete 11 or more records, it doesn't affect the behaviour of this procedure. It's safe for the purpose it has to reach.
Even if the table is empty new ids will just keep on growing since you've declared id as auto-increment.
UPDATE: I want to clarify why the ID generation is not wrapped in a transaction and why it shouldn't.
If you generate an auto id and you rollback the transaction, the next auto id, will be incremented anyway. Excerpt from a MySQL bug report:

[...] this is not a bug but expected behavior that happens in every RDBMS we know. Generated values are not a part of transaction and they don't care about other statements.

Getting the ID with this procedure is perfectly thread safe. Your logic after the ID is obtained should be wrapped in a transaction, especially if you deal with multiple tables.
Getting a sequence in this way isn't a new concept, for instance, the code of metabase_mysql.php which is a stable DB access library has a method called GetSequenceNextValue() which is quite similar.

A: In a single table, you could have a field for the content type and clustered index that includes the content type field.  This effectively keeps all of one content type in one place on the disc, and another content type in another place, etc.  (It's actually organised into pages, but this physical organisation is still true.)
Assuming that each content type has the same fields, this would likely meet your needs and behave similarly to multiple tables.  In some cases you may even find that, with appropriate indexes, a single table solution can be faster, more convenient and maintainable, etc.  Such as trying to create global unique identifiers across all content types.

If you're unable to merge these back into a single table, you could create a central link table...
CREATE TABLE content_link (
  id            INT IDENTITY(1,1),         -- MS SQL SERVER syntax
  content_type  INT,
  content_id    INT                        -- The id from the real table
)

As you insert into the content tables, also insert into the link table to create your globally unique id.

More simply, but even more manually, just hold a single value somewhere in the database.  Whenever you need a new id, use that centrally stored value and increment it by one.  Be sure to wrap the increment and collection in a single transaction to stop race conditions.  (This can be done in a number of ways, depending on your flavor of SQL.)
EDIT
A couple of MySQL example lines of code from the web...
START TRANSACTION;
INSERT INTO foo (auto,text)
    VALUES(NULL,'text');         # generate ID by inserting NULL
INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text');  # use ID in second table
COMMIT TRANSACTION;

Personally, I'd actually store the value in a variable, commit the transaction, and then continue with my business logic.  This would keep the locks on the tables to a minimum.

A: You could have a separate ID table, insert into that, and use the newly-inserted ID.
e.g.
CREATE TABLE ids (INT UNSIGNED AUTO INCREMENT PRIMARY KEY, timeadded DATETIME);

In the script:
<?php
$r = mysql_query('INSERT INTO ids (timeadded) VALUES (NOW())');
$id = mysql_insert_id();
mysql_query("INSERT INTO someOtherTable (id, data) VALUES ('$id', '$data)");

Add error checking etc. to taste.
The MySQL manual states:

The ID that was generated is maintained in the server on a
  per-connection basis. This means that the value returned by the
  function to a given client is the first AUTO_INCREMENT value generated
  for most recent statement affecting an AUTO_INCREMENT column by that
  client. This value cannot be affected by other clients, even if they
  generate AUTO_INCREMENT values of their own. This behavior ensures
  that each client can retrieve its own ID without concern for the
  activity of other clients, and without the need for locks or
  transactions.

(Source) So I don't think concerns about ACID complians are a problem.


text:
Q: AttributeError: 'str' object has no attribute 'ndim', unable to use model.predict() I was trying to make an Image Captioning model in a similar fashion as in here
I used ResNet50 instead off VGG16 and also had to use progressive loading via model.fit_generator() method.
I used ResNet50 from here and when I imported it by setting include_top = False, It gave me features of photo in shape of {'key': [[[[value1, value2, .... value 2048]]]]}, where "key" is the image id.
Here's my code of caption generator function:-
def createCaptions(tokenizer, photoData, MaxLength, model):
    for key, feature in photoData.items():
        inSeq = "START"
        for i in range(MaxLength):
            sequence = tokenizer.texts_to_sequences([inSeq])[0]
            sequence = pad_sequences([sequence], maxlen = MaxLength)
            ID = model.predict([np.array(feature[0][0][0]), inSeq])
            ID = word_for_id(ID)
            if ID is None:
                break
            inSeq += " " + ID
            if ID == "END":
                break
        print(inSeq)

The function word_for_id is :-
def word_for_id(integer, tokenizer):
    for word, index in tokenizer.word_index.items():
        if index == integer:
            return word
    return None

I had generated photoData via:-
features = {}
for images in os.listdir(args["image"]):
    filename = args["image"] + '/' + images
    image = load_img(filename, target_size = inputShape)
    image = img_to_array(image)
    image = np.expand_dims(image, axis = 0)
    image = preprocess(image)
    pred = resnet.predict(image)
    image_id = images.split('.')[0]
    features[image_id] = pred
    print('>{}'.format(images))

features is my photoData dictionary.
When I try to generate captions:-
caption = createCaptions(tokenizerTrain, features, 34, model)

I get the following error:-
Traceback (most recent call last):
  File "CaptionGenerator.py", line 111, in <module>
caption = createCaptions(tokenizerTrain, features, 34, model)
  File "CaptionGenerator.py", line 101, in createCaptions
ID = model.predict([np.array(feature[0][0][0]), inSeq])
  File "/home/aditya/.virtualenvs/cv/lib/python3.5/site-packages/keras/engine/training.py", line 1817, in predict
check_batch_axis=False)
  File "/home/aditya/.virtualenvs/cv/lib/python3.5/site-packages/keras/engine/training.py", line 76, in _standardize_input_data
data = [np.expand_dims(x, 1) if x is not None and x.ndim == 1 else x for x in data]
  File "/home/aditya/.virtualenvs/cv/lib/python3.5/site-packages/keras/engine/training.py", line 76, in <listcomp>
data = [np.expand_dims(x, 1) if x is not None and x.ndim == 1 else x for x in data]
AttributeError: 'str' object has no attribute 'ndim'

Where did I go wrong?
Please help.
Thanks in advance.

A: You pass inSeq = "START" to model.predict as a string:
ID = model.predict([np.array(feature[0][0][0]), inSeq])

without pre-processing it. You will need to encode it to an array.


text:
Q: Multi-tenacy in Nifi (HDF)? I have a HDF cluster composed of 3 nodes where Nifi is installed. My goal is to achieve multi-tenacy (maybe not the best word) on the Nifi level. Meaning that I want 2 things :

*

*Have different groups of users work on different flows repecting some access policy.

*Force the flows to be executed by different users on the unix system level. This might seem weird, but the destinations (hdfs, hive...) of my flows require different users to write on them. And having one nifi user can be problematic.

So far I have succeded in achieving the firt point using the security and authorization configuration in nifi. However, I don't know how to achieve the second point. Is it even possible ? Is there some sort of multiple instance configuration in hdf or nifi ? Can the flows be executed by different users on the unix system level ?
Any help is appreciated ...
Thank you for your answers

A: Apache NiFi supports multi-tenant authorization. To achieve multi-tenancy from a resource/system perspective you'll need to run multiple instances of NiFi. This will allow the separate processes to run as different users and be configured with different settings that affect resource consumption.
If the different dataflows managed by the different groups need to be connected, you can use a RemoteProcessGroup to point to the other instance to send and receive flowfiles.


text:
Q: Laravel. Не записываются данные в базу Делаю на проекте 3 типа содержимого: категории, статьи и страницы. Категории и статьи создал, между собой связал и все хорошо. Со страницами проблема. В общем. Создал контроллер Admin/PagesSontroller.
Функция записи в базу при создании страницы:
public function store(Request $request)
    {

        $pages = DB::table('pages')->insert($request);

        return redirect()->route('admin.page.index');
    }

Рут:
Route::resource('/page', 'PagesController', ['as'=>'admin']);

Через миграции создал в базе колонки:
id  title   slug    published   created_by  modified_by     meta_title  meta_description    meta_keyword    created_at  updated_at

Вся суть. После заполненни формы вылетает ошибка https://prnt.sc/qz12j5
Ранее пробовал контроллер так:
 public function store(Request $request)
    {
        $pages = DB::table('pages')->where($request->all());

        return redirect()->route('admin.page.index');
    }

Но так данные никуда не записывались.

A: В ошибке все написано, аргумент insert должен быть массив, а вы передаете обьект.


text:
Q: What do you call a matrix of the form $\left(\begin{smallmatrix} a & -b \\ b & a \end{smallmatrix}\right)$? I'm reviewing a piece of python code that uses the term "rotations" for these matrices, but of course that's not quite accurate. What's a good, more accurate term of similar accessibility?
Here are my candidates so far:

*

*scaling-and-rotation matrix: Clunky, but the best I've got right now.

*scaled rotation: Less clunky than the above. This term might sound like we're scaling the amount of rotation.

*conformal matrix: Technically correct, but far fewer people will understand the meaning compared to "rotation matrix". Also, it's a bit ingenuous since the term conformal prototypically refers to nonlinear maps that behave infinitesimally like these matrices.

*angle-preserving matrix: A more accessible form of conformal matrix. Less knowledgeable readers may be distracted trying to figure out which $2\times2$ matrices are angle-preserving. (Readers who understand the term conformal matrix will probably already know this.)

*[multiplication by a] complex number: Not as accessible as "rotation". Also a bit clunky since it identifies a complex number with its representation.

*sum of a scaling and antisymmetric matrix: Worst suggestion so far, especially since antisymmetric matrices don't show up anywhere in the code or code comments.

Is there any standard, accessible term for such linear transformations? I'd also appreciate thoughts on whether I'm mistaken about how accessible and/or clunky the terms above are.

A: If $a,b \in \mathbb R$ then $\left(\begin{smallmatrix} a & -b \\ b & a \end{smallmatrix}\right)$ can be written as $\left(\begin{smallmatrix} r\cos \phi & -r\sin \phi \\ r\sin \phi & r\cos \phi \end{smallmatrix}\right)=\left(\begin{smallmatrix} r & 0\\0 & r \end{smallmatrix}\right)\left(\begin{smallmatrix} \cos \phi & -\sin \phi \\ \sin \phi & \cos \phi \end{smallmatrix}\right)$. In German this is called Drehstreckung. I tried to find translations to English and found rotation-dilation, spiral similarity, similarity transformation.

A: I don't think there is any "standard" or "canonical" term for such matrices in cited references.
Writing something like

Let $P$ be a matrix of the form $\left(\begin{array}{cc}
a & -b \\
b & a
\end{array}\right)$, where $a,b$ are real numbers, ...

in an article is clear enough. Whether one needs a specific "name" for such matrices depends on what one wants to do with them, as long as it does not obstruct the clear delivery of mathematical communication. For instance, this Wikipedia article called it "matrix representation of complex numbers". One may want to call it like that if one wants to emphasize its relation to complex numbers. Bob's daughter in high school may want to call it a "kitty" matrix in her report of exploring special matrices.
If it were for commenting on a piece of Python code as you mentioned at the beginning, I may simply delete it if it only describes a subset of the matrices.


text:
Q: auto evaluation of variables in pyspark in zeppelin I just installed Zeepelin 0.5.5 (using AWS EMR provided 'Zeppelin Sandbox'). In python blocks (%pyspark), how can I have an automatic display (evaluation) of the last variable of the block ?
I mean, in scala blocks, if I do a
%spark
sc

I get :

res1: org.apache.spark.SparkContext = org.apache.spark.SparkContext@6a78beae

But in python blocks, I have to do a print().
Why this difference ? How can I have an autoeval in python ?


text:
Q: MySQL corruption even after full dump and re-import We have a production issue where MySQL has started spitting InnoDB corrupt page errors and falling over.
The error message seem to relate to indexes so I assume the data itself is ok and when I restarted the server with innodb_force_recovery=1 I was able to dump the lot using mysqldump.
However, re-importing hasn't fixed the error, dropping/recreating the database didn't help either and I've even gone as far as moving the innodb files out the way and letting MySQL recreate them before re-importing.
No joy, corruptions keep re-occuring within a few minutes and the server dies again.
The weird thing is the database is a mix of ISAM and InnoDB tables and I had a couple of errors in the ISAM tables as well on some attempts.
Is this likely to be something data-related, something corrupt deeper in MySQL that isn't cleared by the above or signs of a hardware fault underneath it all?
EDIT: This is Mysql 5.0.51 running on Ubuntu 8.04

A: Paolo, can you please provide the mysql error log?  If one isn't available, you can add one by adding this line to your my.cnf file
[mysqld]
log-error=/var/log/mysql/mysql.err
One possible idea to narrow down your research.
You already know how to remove the ibdata and iblog files to create new ones.   If you just want to test your mysql installation.

*

*Remove the Innodb_force_recovery or comment it out

*Backup your databases : mysqldump --all-databases -u root -p | gzip -9 > all_databases.sql.gz

*Move your MySQL data directory somewhere else: mv /var/lib/mysql{,.bak}

*Create a new MySQL data directory: mkdir /var/lib/mysql

*Give rights to the MySQL user: chown -R mysql:mysql /var/lib/mysql

*Start MySQL: /etc/init.d/mysql start

*Run a tail -f on the mysql log you added to my.cnf: tail -f /var/log/mysql/mysql.err
If MySQL isn't running then something else on the system level isn't right.  As Gopinath's link mentionned.  Is there enough disk space: df -h and inodes: df -i? Is you file system healthy? A system reboot or using fsck on the disk partition where MySQL is installed, would detect and possibly fix file system problems.
If MySQL comes back, then you can restore your databases:
zcat all_databases.sql.gz | mysql -u root -p
Send us the logs after completing the steps I sent, and we'll take it from there.

A: Hi Paolo might be issue with the innodb_force_recovery=1 which you has used in force recovery. try using value 4. There might be some back ground process running. With innodb_force_recovery=4  value set to 4, No background process is allowed to modify the database so that we can safely do the recovery process.
Please follow the below link for in detail :
http://tech.amikelive.com/node-36/mysql-50-recovering-crashedcorrupted-innodb-database/


text:
Q: How to create a second index.php? I need a duplicate of index.php, but slightly modified. I added a "vote it up" plugin. So, I want the user to select how to display posts - by new or by popular. I know what to add to second index.php, but how to create a second index.php, thats the problem.

A: You can create a new page, using a modified template file - and send users to that page if they choose to display posts "by popular"

A: When i do this kinds of modification i always use child theme Because its the easy way to doing it. And if i mess the child theme up i can just copy files form the main theme anytime.
If you never tried the child theme. This might be the right time for you. ;) Just make a child theme copy the index.php file form original theme and place it to the child theme directory and edit.

A: Elaborating on Rachel Baker's answer:
Copy the index.php file and name it something like popular.php. At the very top, paste the following:
<?php
/*
Template Name: Posts by Popular
*/
?>

Now, go in to the WordPress admin and create a new page, called something like "By Popular". On the right-hand side, select the "Posts by Popular" template where it says "Template" (screenshot). Publish the page, and when you view it you should see your new page.
Create a link to this page in the nav menu or wherever, and then your users will be able to access the new page.

A: If the OP is asking about creating a secondary index.php using a different theme, then it's not so simple: WP loads theme-specific constants right at load time and won't have it any other way. The only way to temporarily force a different theme is to create a plugin that will override the 'stylesheet' and optionally 'template' options, like this:
if ($GLOBALS['USE_SECONDARY_THEME']) {
    add_filter('stylesheet',function() { return 'mytheme-secondary'; });
    add_filter('template',function() { return 'mytheme'; }); // if the secondary theme is a child of mytheme
}

And then, in index-secondary.php, do
$USE_SECONDARY_THEME=true;

right before the usual
require_once( $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php' );

that should be in a WordPress index file.


text:
Q: How to handle HTTP Response 500 error code through Ajax ".fail()" trigger? I was running some jQuery code when suddenly I saw through Firebug Console that when I force a 500 error, the code inside .fail() method, is not being fired:
$.ajax({
   url: "someAction.do",
   data: "param1=param&param2=param",
   dataType: "xml"
}).done(function(xml){
   //some stuff with my data
}).fail(function(xml){
   //some other different stuff with my data that is not being fired

});

In the other hand, in a Java Action, I set the HttpResponse Status to "500" when an error occurs, for example, POSTING an invalid field trough the Ajax call, like searching in a database for an email that is not present, and then show the error trough ajax:
<xml version=bla,bla...>
    <item>
      <name>message</name>
      <value>Invalid input data</value>
    </item>
   </xml>.
Any ideas why? I just want to use the new methods fail() and done(). I know I could do this using the statusCode handler.
But I allways like to follow new trends if I could. At least I would like to try that.
Thank you very much!

A: An alternative approach , substitute direct call to .done() or .fail() by filtering responses through .always() initially , then calling .done() or .fail() through filtering deferred ; maintaining ability to process actual net errors with same fail() callback
// simulate server-side responses
var error = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<item>"
            + "<name>message</name>"
            + "<value>Invalid input data</value>"
            + "</item>";

var success = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<item>"
            + "<name>message</name>"
            + "<value>Success</value>" + "</item>";
// params
$.ajaxSetup({
    beforeSend : function(jqxhr, settings) {
        var d = decodeURIComponent(settings.data)
                    .match(/data=+.*/)[0]
                    .split(/=|&/);
        var params = {};
        params[d[0]] = {};
        params[d[0]][d[1]] = d[2];
        params[d[0]][d[3]] = d[4];
        jqxhr.data = params;
    }
});

var request = function (url, _xmlResponse, data1, data2) {
    var _response = new $.Deferred(),
        _request = $.ajax({
            url: url,
            type: "POST",
            data: {
                // responses
                xml: _xmlResponse,
                // params
                data: "param1="+ data1 +"&param2="+ data2
            },
            dataType: "xml"
        });
    // check `responseText` for "Invalid" ,
    // check `textStatus` for actual net error , "error"
    _request.always(function (xml, textStatus, jqxhr) {
        console.log(xml, textStatus, jqxhr, "check");
        // simulate server-side processing, cont.
        // if both object passed to server ,
        // `param1` and `param2` _do not_ have property
        // with value of at `params` ,  `""` empty string - generic "error" ,
        // _and_  returned `responseText` contain "Invalid" ,
        // _or_ `textStatus` : `error` , `reject` `dfd` , call `.fail()`
        // else `resolve `dfd` , call `.done()`

        // check params
        var test = [xml["data"] || jqxhr["data"]].every(function(v, k) {
          return !(v.data["param1"] !== "" && v.data["param2"] !== "" )
        }) ;
        // check `xml` responseText for node for "Invalid" text ,
        // generate `.fail()`
        var check = $(xml.children)
        .find("value").is(":contains(Invalid)");
        return check && test || textStatus === "error"
               // call `.fail()`
               ? _response.reject([xml, textStatus, jqxhr])
               // call `.done()`
               : _response.resolve([xml, textStatus, jqxhr])
    });

    return _response
    .done(function (xml) {
        // do `done()` stuff
        console.log(xml[0], xml[1], xml[2]);
        var msg = $(xml[0].children).find("value").html();
        $("#success")
        .html(msg + ", "
                  + xml[2].data.data.param1
                  + xml[2].data.data.param2
             );
        return this.promise()
    })
    .fail(function (xml) {
        // do `.fail()` stuff
        console.log(xml[0], xml[1], xml[2], "fail");
        var msg = $(xml[0].children).find("value").html()
                  || xml[1] + ", " + xml[2];
        $("#error")
        .html(msg);
        return this.promise()
    });
};

Could then call request() , without _xmlResponse param , which should handle both generated .fail() (if responseText contains "Invalid") and  net error .fail() calls (e.g., statusCode 500; textStatus error) , and .done() calls .
request("someAction.do", "param1_param", "param2_param");

Optionally, chain returned promise from request at .always() , as data array containing request return values ; after being processed at .done() or fail()
request("someAction.do", "param1_param", "param2_param")
.always(function(data) {
  // do `.done()` , `.fail()` stuff ,
  // `data, textStatus, jqxhr`
  console.log(data[0], data[1], data[2])
})

jsfiddle http://jsfiddle.net/guest271314/ek15krb5/

A: I think that depends on the parameter  "xml", if:
1. xml is a real xml object ,it'll trigger 'done';
2. xml is not a xml object ,it'll trigger 'fail'
Even if you return a 500 error code ,it is still a valid xml object, So it'll trigger "done"


text:
Q: Load desktop version of website in iphone It might seem duplicate to you, but as long as my problem is not solved I should ask here for help. I have tried previous given answers but nothing is working for me. So please help me out.
I want to force my UIWebView to load desktop versions of all websites(not the mobile version) and I am using this code, but still I am getting mobile versions of websites.
NSURL *urlValue = [NSURL URLWithString:@"any url here"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlValue];
    NSString *newUserAgent = @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7";
    [request setValue:newUserAgent forHTTPHeaderField:@"User_Agent"];
    [webView loadRequest:request];

There might be some problem with my User_Agent string. So your kind help is required.


text:
Q: Responsive Menu not working after adding second list to php I am working on a wordpress website using a responsive template with one menu line on top right corner. I added a second menu with social icons by moving it from another location to the top (inside  as second  in header.php). Now responsive is not working anymore, no toggle, nothing.
I assume the problem is that I have two identical id (cssmenu) that cause confusion in the js file, correct? As I am not familiar with js, can someone give me a hint how to change it?

<?php
get_template_part( 'inc/partials/content', 'header-social');
?>

                    <?php
                    global $wp_customize;
                    if ( !empty( $wp_customize ) && $wp_customize->is_preview() && !get_theme_mod( 'louis_content_set', false ) ) {
                        ?>

                                Home

                                More Free Themes

                                Blog

                                Contact

                                Members

                                Signup

                    <?php
                    } else {
                        wp_nav_menu( array(
                                'theme_location' => 'primary',
                                'container'      => false,
                                'items_wrap'     => '
%3$s
',
                                'depth'          => 0,
                                'fallback_cb'    => 'louis_fallback_menu',
                            )
                        );
                    }
                    ?>

js file:
(function($) {

  $.fn.menumaker = function(options) {

      var cssmenu = $(this), settings = $.extend({
        title: "Menu",
        format: "dropdown",
        sticky: false
      }, options);

      return this.each(function() {
        cssmenu.prepend('
' + settings.title + '
');
        $(this).find("#menu-button").on('click', function(){
          $(this).toggleClass('menu-opened');
          var mainmenu = $(this).next('ul');
          if (mainmenu.hasClass('open')) {
            mainmenu.hide().removeClass('open');
          }
          else {
            mainmenu.show().addClass('open');
            if (settings.format === "dropdown") {
              mainmenu.find('ul').show();
            }
          }
        });

        cssmenu.find('li ul').parent().addClass('has-sub');

        multiTg = function() {
          cssmenu.find(".has-sub").prepend('');
          cssmenu.find('.submenu-button').on('click', function() {
            $(this).toggleClass('submenu-opened');
            if ($(this).siblings('ul').hasClass('open')) {
              $(this).siblings('ul').removeClass('open').hide();
            }
            else {
              $(this).siblings('ul').addClass('open').show();
            }
          });
        };

        if (settings.format === 'multitoggle') multiTg();
        else cssmenu.addClass('dropdown');

        if (settings.sticky === true) cssmenu.css('position', 'fixed');

        resizeFix = function() {
          if ($( window ).width() > 768) {
            cssmenu.find('ul').show();
          }

          if ($(window).width() <= 768) {
            cssmenu.find('ul').hide().removeClass('open');
          }
        };
        resizeFix();
        return $(window).on('resize', resizeFix);

      });
  };
})(jQuery);

(function($){
$(document).ready(function(){

$("#cssmenu").menumaker({
   title: "Menu",
   format: "multitoggle"
});

});
})(jQuery);


text:
Q: Understanding this capistrano deploy file I have a config/deploy.rb file that looks like this:
# require './config/boot'
# config valid only for Capistrano 3.2
lock '3.9.0'

set :application, 'arthousecoop'
set :repo_url, 'git@github.com:arthousecoop/arthousecoop.git'
set :ssh_options, {forward_agent: true}

set :deploy_to, '/home/sbp/rails'

set :linked_files, %w{config/database.yml}
set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}

# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }

namespace :deploy do
  # before :deploy, 'rvm1:install:gems'
  # before :deploy, 'deploy:check_revision'
  # after :finishing, 'deploy:cleanup'

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      within release_path do
        execute :bundle, 'exec thin restart -C /etc/thin/sbp.yml'
      end
    end
  end

  after :publishing, :restart
  before :restart, 'rvm:hook'
  after :finished, 'airbrake:deploy'

  # after :restart, :clear_cache do
  #   on roles(:web), in: :groups, limit: 3, wait: 10 do
  #     # Here we can do anything such as:
  #     # within release_path do
  #     #   execute :rake, 'cache:clear'
  #     # end
  #   end
  # end

end

*

*What does the linked_files and linked_dirs sections do?

The documentation says:

:linked_files default: [] Listed files will be symlinked from the
  shared folder of the application into each release directory during
  deployment. Can be used for persistent configuration files like
  database.yml. See Structure for the exact directories.

I don't really get what that means? What does symlink mean?

*What does the on roles section mean? What does the on method do?
task :restart do
on roles(:app), in: :sequence, wait: 5 do
  within release_path do
    execute :bundle, 'exec thin restart -C /etc/thin/sbp.yml'
  end

is release_path a Capistrano method?


text:
Q: How to set ODBC connection in MapBasic i am trying to set code for ODBC connection in Mapbasic. Instead of using Username and password i wanted to set code for Window authentication.my sample code is
Register table "tablename"
Type ODBC
Table "Select * From Database.tablename"
CONNECTION
"DSN=Database; UID=Username; PWD=Password"
into "C:\temp.table.tab"

so in this case instead of UID and PWD i wanted to set as window authentication to connect to database...anybody knows this.

A: Use "trusted_connection" attribute in your connection string. Set it to 'Yes'
Register table "tablename"
Type ODBC
Table "Select * From Database.tablename"
CONNECTION
"DSN=Database;Trusted_Connection=Yes"
into "C:\temp.table.tab"

Trusted_Connection: Trusted_Connection={yes | no}.
Determines what information the SQL Server Wire Protocol driver will use for login validation.
When set to yes, the SQL Server Wire Protocol driver uses Windows NT Authentication Mode for login validation. The UID and PWD keywords are optional.
When set to no, the SQL Server Wire Protocol driver uses a SQL Server username and password for login validation. The UID and PWD keywords must be specified.


text:
Q: Android OpenGL ES 2.0: Do I need to check if VBOs are supported before using? I want my code to perform well in all devices supporting Es 2.0. In my code, I am using VBOs, reading documentation reveals that it requires the implementation of extension "GL_ARB_vertex_buffer_object".
However, glGetString(GL_EXTENSIONS) does not list the above mentioned extension string for the device I am using (Samsung Tab) though it supports it.

A: To my knowledge, the VBO extension is only meant for OpenGLES 1.1. OpenGLES 2.0 supports this by default. This tutorial, which I consider one of the best, makes no consideration to test the device before running the VBOs.

A: In all my Android apps I use OpenGL ES 2.0 with VBO without any additional checks.
And VBOs work on Galaxy Tab.

A: In OpenGLES2 you do not have to check for VBO extension.
In OpenGLES2 you do have to check for vertex_array_object if you want to use VAO as well.
Here is a database of extensions from various devices.


text:
Q: SSH Fingerprint with Golang How can I get my own ssh fingerprint with Go?
Finger, err := ssh.**
log.Println(Finger)
// 12:f8:7e:78:61:b4:bf:e2:de:24:15:96:4e:d4:72:53

A: A key signature is is just a cryptographic hash of the unencoded key data in ssh wire format.
Here is a basic example of parsing an ssh key from the OpenSSH format public key, and getting an MD5 fingerprint:
key, err := ioutil.ReadFile("/path/to/id_rsa.pub")
if err != nil {
    log.Fatal(err)
}

parts := strings.Fields(string(key))
if len(parts) < 2 {
    log.Fatal("bad key")
}

k, err := base64.StdEncoding.DecodeString(parts[1])
if err != nil {
    log.Fatal(err)
}

fp := md5.Sum([]byte(k))
fmt.Print("MD5:")
for i, b := range fp {
    fmt.Printf("%02x", b)
    if i < len(fp)-1 {
        fmt.Print(":")
    }
}
fmt.Println()

A: Another way to do this is to parse the key using the ssh package and then use FingerprintLegacyMD5 in order to generate the fingerprint. See this answer:
https://stackoverflow.com/a/46430102/1601137

A: In case that you need a fingerprint of an rsa.PublicKey you can use the ssh.FingerprintLegacyMD5() function (or the ssh.FingerprintSHA256() one).
The only issue is that you have to convert the rsa.PublicKey to an ssh.PublicKey which can be done via the ssh.NewPublicKey() function.
func getFingerprint(key *rsa.PublicKey) string {
    pubKey, _ := ssh.NewPublicKey(key)
    return ssh.FingerprintLegacyMD5(pubKey)
}


text:
Q: How to call a modal window in kendo grid column template? currently I am working to display a modal window once you click on a link in Kendo Grid. Below is my code:
{
    field:"filename",
    title: "File Name",
    width: 60,
    template: '#:filename#'
},

What is happening now is that, the file, which is a json, is just displayed as its file name, but what I need to show is the content inside the file. Is there any way that this could be done? Would appreciate any help given.
I have tried  which opens in a new tab, but I need it to open in a new modal window instead.

A: Your template is invalid. You can't add a pure javascript code to a string. It is not the way it works. You are probably getting errors in your console. Also, you have some other flaws in your code:

*

*You should not add more than one element with the same id in your dom like you're doing with . Change it a class instead.

*If you open a window in that span, it will break the column's content. Check this.
What I would suggest is this code:
Template:
template: '#:filename#'

Click event:
$("#grid").on("click", "a.open-modal", function() {
    $("

").appendTo($("#win")).kendoWindow();
});

Where #win is a div element in your body.
Demo
In the click event - which is attached to the grid and filtered by the link's class .open-modal - it just creates a new div, appends it to div#win and then call kendoWindow on it.
Update

*

*To get window centered when showing, just use center() method;

*To get the data of the clicked row, get the tr from the clicked link, then use dataItem() method from grid with it.
Demo


text:
Q: Where are the other polynomials without $\alpha$ as a root mapped? I'm reading Lang's Undergraduate Algebra, here:

Specifically here:

I am confused at how the homomorphism ($F[t]\to F(\alpha)$) is defined. It seems that if $\alpha$ is a root of some polinomial $p$, then it is mapped into $0$. But where are the other polinomials mapped? There are polynomials with roots $\beta,\gamma, etc$ and no $\alpha$ root, where are they mapped?


text:
Q: how we can show selected area in imgareaelect code is:
    <!DOCTYPE html>

 <meta charset="utf-8">
<title>jQuery UI Tooltip - Default functionality</title>
<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />

        <link rel="stylesheet" href="http://deepliquid.com/projects/Jcrop/css/jquery.Jcrop.css" type="text/css" />
        <link rel="stylesheet" href="http://deepliquid.com/projects/Jcrop/demos/demo_files/demos.css" type="text/css" />

<link rel="stylesheet" href="/resources/demos/style.css">

<input type="file" id="choose" multiple="multiple"   />

First of all I am uploading an image then checking the min criteria of an image.
If the image passes the criteria then I am showing it on page. Then I am selecting an area to create thumbnail.
However, when I select an area of the image, I am not able to show the selected area in a new div.
All things are working. But it is unable to show selected area. I thing problem in my code is (how to pass src of an image to img tag or div tag)
hope you understand the question.

A: divHtml=$('
',{'id':ANYID}).css({
                    float: 'right',
        position: 'relative',
        overflow: 'hidden',
        width: thumbWidth + 'px',
        height: thumbHeight + 'px'
            });
imgHtml=$('',{'src':IMGSRCPATH, 'alt':ALTVALUE, 'title':TITLEVALUE});

var appendVal = divHtml.append(imgHtml).insertAfter($('#uploadPreview'));

Please try this.


text:
Q: Open Google Maps App in iOS 6 I would like to open Google Map App in iOS 6 programmatically.
I tried to open the maps in by passing url -  maps.....
but it is still opening in the Safari

A: [[UIApplication sharedApplication] canOpenURL:
[NSURL URLWithString:@"comgooglemaps://"]];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:
@"comgooglemaps://?center=40.765819,-73.975866&zoom=14&views=traffic"]];

reference:  https://developers.google.com/maps/documentation/ios/urlscheme

A: try this
The domain must be maps.apple.com.
A parameter cannot be q=* if the value is a URL (so KML is not picked up).
The parameters cannot include view=text or dirflg=r.
https://developer.apple.com/library/safari/#featuredarticles/iPhoneURLScheme_Reference/Articles/MapLinks.html#//apple_ref/doc/uid/TP40007894-SW1


text:
Q: Auto increment the VARCHAR value obtained from Database? I am getting the value of DRSYSCODE from DB, Now i need to auto increment the value while insertion
Am getting the value in this Format MOB000571 now on insertion i need to increment to MOB000572, for this am using the below code but am unable to achieve it, In return am getting the value only 1 ,Please help me in this
$sql1="SELECT DRSYSCODE FROM DOCTORDETAILS  ORDER BY DRSYSCODE DESC LIMIT 1";
    $query=mysql_query($sql1);
    if (!$sql1) { // add this check.
    die('Invalid query: ' . mysql_error());
    }
    $output_array2=array();
    while($row=mysql_fetch_assoc($query))
    {
    $ids=$row['DRSYSCODE'];

    }
    echo $ids;
    if($ids){
        $su=1;
        echo $num =$ids+$su;
        $unique=$num;
    }

    echo $unique;

A: Try like this,
$pieces = explode("MOB", $string);
$autoinc_add = 1+$pieces[1];
$your_latest_autoincrement_value = str_pad($autoinc_add, 6, '0', STR_PAD_LEFT);
echo $your_latest_autoincrement_value;

A: Instead of $num =$ids+$su; use this:
$num = 'MOB' . str_pad($su + substr($ids, 3), 6, '0', STR_PAD_LEFT);

A: Your problem is that you are trying to add 1, an integer to a string of text. You need to break up the string of text into the text part and the number part first into two separate variables (unless the 'MOB' is always the first three characters, or unless there are always three characters followed by six digits in your DRSYSCODE) then add 1 to the number part and then concatenate them together again before inserting. For example, if the DRSYSCODE is always AAAxxxxxx ('A' being characters and 'x' being digits), you could do something like:
if($ids){
    $alpha = substr($ids, 0, 3); // Get the first three characters and put them in $alpha
    $numeric = substr($ids, 3, 6); // Get the following six digits and put them in $numeric
    $numeric++; // Add one to $numeric
    $numeric = str_pad($numeric, 6, '0', STR_PAD_LEFT); // Pad $numeric with leading zeros
    $newids = $alpha.$numeric; // Concatenate the two variables into $newids
    }

I hope this helps. I see other places in your code where it could be simplified but that isn't part of your question. All the best to you.

A: I think that you should split your id in two part, first one is the letters (MOB, in this case) and the second part is the numbers (000571) and then you should be able to add 1 to the numbers and then concatenate both letters and the incremented numbers. This is because you're trying to add 1 to a string, not an interger or a float value. String are only for characters which means you can't do math on them.
I would replace the if(ids) {...} part by this
if($ids){
    $su=1;
    $splitedid = preg_split('/(?<=[a-zA-z])(?=[0-9]+)/',$ids); //Split in chars and numbers
    $zeros = substr_count($splitedid[1], '0'); //Count the number of zeros before the number
    $num = $splitedid[1]+$su; //Add one to the number
    $unique = $splitedid[0]; //Set $unique as the chars (MOB in your case)
    for ($i=0; $i < $zeros; $i++) { //Add to $unique the zeros that were in front of the number
      $unique .= '0';
    }
    $unique .= $num; //Add the number (572 = 571 + 1) to $unique so $unique is 'MOB000572'
}

Hope it helps !


text:
Q: Get the ID of an element where the class contains a given string I am currently trying to figure out a way to get the ID of an element, depending on whether its class contains something.  I'm not sure if there's a better way to do it than I currently am, but having looked around nothing fits exactly the need I have.  The code I currently have is, where I am looking for a div element whose class contains the string "one" but is not limited to that.  Currently there is only one element containing this string but the alert provides me with [Object NodeList] (I may well be overcomplicating this):
$idToMove = document.querySelectorAll('div[class^="one"]');
        alert($idToMove);

A: document.querySelectorAll() Returns a node list (kind of like an array), if you are sure there will only ever be one you have a couple options.
1) Use .querySelector instead:
// returns the first node that matches
var elm = document.querySelector('div[class~="one"]');
console.log(elm.id);

2) Access the first element in the returned list:
// returns all nodes that match
var elms = document.querySelectorAll('div[class~="one"]');
console.log(elms[0].id);

Make sure to null check returns of .querySelector and length check returns of .querySelectorAll.
Notice also, that I use ~= and not ^=. You can read on the MDN about the difference between all the equality operators. But for these two:

[attr~=value]
  Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".
[attr^=value]
  Represents an element with an attribute name of attr and whose first value is prefixed by "value".

A: First get element from DOM and than from that element get id attribute:
1- If you need only first element then use querySelector like this:
let elms = document.querySelector('div[class~="one"]')[0].id
console.log(elms)

2- If you need all element those have this class then use querySelectorAll like this:
let elms = document.querySelectorAll('div[class~="one"]')

for(let i=0; i<elms.length; i++)
{
console.log(elms[i].id)
}

A: I think with "*" it works in more cases
document.querySelector('div[class*="words"]')

A: i tried it works absolutely amazing
window.frames[0].document.querySelector('td[id*="sss"]')


text:
Q: the_content and wp_link_pages Many plugins seem to be adding a filter/action hook to the_content to display related posts, advertisements and such. The problem is I these appear before the post pagination so it the pagination is pushed down below.
Is it possible to display the post pagination right after the content? It appears wp_link_pages can only be used inside the loop.

A: I guess you have:
the_content();
wp_link_pages();

in your theme file. So you can instead try the following (PHP 5.4+):
/**
 * Append the wp_link_pages to the content.
 */
! is_admin() && add_filter( 'the_content', function( $content )
{
    if( in_the_loop() )
    {
        $args = [ 'echo' => false ];        // <-- Adjust the arguments to your needs!
        $content .= wp_link_pages( $args );
    }
    return $content;
}, 10 );                                    // <-- Adjust the priority to your needs!

and then adjust the arguments and priority to your needs. Notice the echo parameter, it's set to false, because we need to return the output. You then have to remove wp_link_pages() from your (child) theme file.
Update:
If we don't want to remove the extra wp_link_pages() by hand, we can use the wp_link_pages filter to only display the output, within our the_content filter callback:
/**
 * Append the wp_link_pages to the content.
 */
! is_admin() && add_filter( 'the_content', function( $content )
{
    if( in_the_loop() )
    {
        $args = [ 'echo' => false, '_show' => true ];  // <-- Adjust the arguments to your needs!
        $content .= wp_link_pages( $args );
    }
    return $content;
}, 10 );                                              // <-- Adjust the priority to your needs!

/**
 * Only display wp_link_pages() output when the '_show' argument is true.
 */
add_filter( 'wp_link_pages', function( $output, $args )
{
    return ! isset( $args['_show'] ) || ! wp_validate_boolean( $args['_show'] ) ? '' : $output;
}, 10, 2 );

where we've introduced the extra _show argument for this purpose.


text:
Q: Scaling phoenix on heroku I dont have a tonne of experience with heroku, and even less with phoenix, so this may be a stupid question... but want to make sure I am  making a good choice on hosting :)
From what I understand, the way you scale phoenix is add another server, launch another node, and connect them, then let BEAM / OTP work its magic to handle work load balancing. On heroku, dynos can't really talk together over a local network, which from what I understand is something that BEAM requires to cluster. So adding dynos will result in a more "traditional" scaling model, where you have an external load balancer balancing connections between unconnected nodes, with the db being shared state.
My question here is how big of an impact will this have? Is it more only an issue when you are hitting serious levels of load / scale, or will it mean spending a lot more money on infrastructure then is necessary?

A: You'll get the best performance on a host that supports clustering, but Phoenix has a PubSub adapter system exactly for deployments like heroku:
https://github.com/phoenixframework/phoenix_pubsub
One line config change and mix.exs deps entry and you'll have multinode channels on heroku via our Redis adapter.

A: This is very open question, so I am sure my answer won't be comprehensive.
In your situation the most important question is: will I Phoenix use channels?
If you use plain old HTTP, it can be mostly stateless. There are lots of methods to simulate stateful connection like storing sessions in cookies. At the end of the day, it doesn't matter if your backend servers are connected with each other, because each of them is doing independent computations. Your load balancer can randomly select any server and it will always work. This cool feature of http enables this protocol to scale so well. You can definitely use Heroku in that scenario and it will work great.
If you use Phoenix channels, things get complicated. You still want to be able to connect to any of the servers, but you will probably send messages to other users real time and they can be connected to other servers. Phoenix solves this problem for you by clustering using BEAM and this will be hard on Heroku. Or even impossible.
To sum up: it is not a question of small scale/big scale. It is a question of features. Scaling channels will require clustering, scaling plain old HTTP will not.


text:
Q: Can we have a markdown help button for comments? I've been reading discussions about editing and previewing comments.
Why do I want this? If I get wrong some of the syntax in a comment, it becomes infuriating to try to guess at it, when the only help is offered by the help button near the answer input controls, which aren't always near where the comment input controls are. If I even think of that. Which I usually don't. It would be nice to have a help button right there where it's obvious. As another user pointed out in one of the linked questions, this kind of problem is exacerbated by the inability to edit comments (currently a planned feature) or preview them before posting.
Since the set of markdown in comments is restricted and comment previewing was a declined feature, I propose that some help be supplied near the input controls for posting a comment. A "?" button would be appropriate, with a small in-page popup that summarizes the allowed syntax.

A: click the help link under [add comment] to see a summary of the available formatting options.


text:
Q: (Py)OpenCl: wrong scan result after 16th element So I've started working on a Hillis - Steele scan algorithm so get the running sum of an array, and it seems to work fine for arrays with less than 17 elements (N < 17), but after that I often get incorrect results, though not always. The larger N, the higher probability of returning an incorrect result, which gets to 100% incorrectness after N = 40 or so. The array starts to deviate from the true values after the 16th element.
Here's my code:
__kernel void scan(__global double * a, __const int N, __global double * sum_a, __global double * temp) {

    //
    // Hillis - Steele scan algorithm
    //

    int id = get_global_id(0); // Thread id

    temp[id] = a[id]; // Copying the content of a to a temporary array
    barrier(CLK_GLOBAL_MEM_FENCE); // Waiting for all threads to finish

    for(int offset = 1; offset < N; offset *= 2) { // At each increment, double 'offset'

        if(id >= offset)
            temp[id] += temp[id - offset]; // Add 'id' to a neighbour a distance 'offset' away
        else
            temp[id] = temp[id]; // Copy the previous value

        barrier(CLK_GLOBAL_MEM_FENCE); // Synchronising
    }
    sum_a[id] = temp[id]; // Storing final result
}

Does anyone have any idea what is going wrong here?

A: In OpenCL, you can only synchronize between work items in a work group, not globally. Your kernel appears to depend on global synchronization.


text:
Q: how to redirect to login page when session in expired in asp.net mvc 3? i have the situation -i'm calling controller throught ajax in javascript script which return partial view.now when session end the login page view is loaded in div but i want to redirect to login page not to load login view in div.

A: It will be easier if you use forms authentication. However, this link will help you : http://geekswithblogs.net/shahed/archive/2007/09/05/115173.aspx

A: Try refer to this post
It will help to create one attribute for login which will help to check every time when the action of any controller is called and perform the task accordingly.


text:
Q: Jenkins dsl pipeline def variable I'm trying to define a variable into a jenkins pipeline dsl script by reading 3 files and concatenating the output. The 3 files content is:

file1 content is: 127
file2 content is: 0
file3 content is: 1

def var1 = readfile('file1')
def var2 = readfile('file2')
def var3 = readfile('file3')

def concatVar = "${var1} + '_' + ${var2} + '_' + ${var3}"
printin ${concatVar}

The output I expect would be
printIn${concatVar}
127_0_1

instead my output is:
printIn ${concatVar}
127
_0
_1

I know that I am wrong somewhere, but I don't know how to do it. Is there any of you familiar with the Jenkins pipepile dsl/groovy syntax?
Thanks guys

A: Try this..
def var1 = readfile('file1').trim()
def var2 = readfile('file2').trim()
def var3 = readfile('file3').trim()

def concatVar = "${var1} + '_' + ${var2} + '_' + ${var3}"
println ${concatVar}

I found that readFile does not clip off the end of line character


text:
Q: RunAsUser issue & Clicking external IP of load balancer -> Bad Request (400) on deploying Django app on GKE (Kubernetes) and db connection failing: Probem:
I have 2 replicas for my app, library. I have configured a service to talk to my two replicas. I have a dockerfile that starts my app at port # 8080. The load balancer and the app containers all seem to be running. However, I am not able to connect to them. Every time I click on the external IP shown I get "Bad Request (400)"
This log from the container seems to indicate somethingw ith the db connection going wrong...

2019-12-07 07:33:56.669 IST
      Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py",
  line 217, in ensure_connection self.connect() File
  "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py",
  line 195, in connect self.connection =
  self.get_new_connection(conn_params) File
  "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py",
  line 178, in get_new_connection connection =
  Database.connect(**conn_params) File
  "/usr/local/lib/python3.8/site-packages/psycopg2/init.py", line
  126, in connect conn = _connect(dsn,
  connection_factory=connection_factory, **kwasync)
  psycopg2.OperationalError: could not connect to server: Connection
  refused

$ kubectl get services
NAME          TYPE           CLUSTER-IP      EXTERNAL-IP    PORT(S)        AGE
kubernetes    ClusterIP      10.19.240.1     <none>         443/TCP        61m
library-svc   LoadBalancer   10.19.254.164   34.93.141.11   80:30227/TCP   50m

$  kubectl get pods
NAME                       READY   STATUS    RESTARTS   AGE
libary-6f9b45fcdb-g5xfv    1/1     Running   0          54m
library-745d6798d8-m45gq   3/3     Running   0          12m

In settings.py
ALLOWED_HOSTS = ['library-259506.appspot.com', '127.0.0.1', 'localhost', '*']

Here is the library.yaml file I have to go with it.
# [START kubernetes_deployment]
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: library
  labels:
    app: library
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: library
    spec:
      containers:
      - name: library-app
        # Replace  with your project ID or use `make template`
        image: gcr.io/library-259506/library
        # This setting makes nodes pull the docker image every time before
        # starting the pod. This is useful when debugging, but should be turned
        # off in production.
        imagePullPolicy: Always
        env:
            # [START cloudsql_secrets]
            - name: DATABASE_USER
              valueFrom:
                secretKeyRef:
                  name: cloudsql
                  key: username
            - name: DATABASE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: cloudsql
                  key: password
            # [END cloudsql_secrets]
        ports:
        - containerPort: 8080

      # [START proxy_container]
      - image: gcr.io/cloudsql-docker/gce-proxy:1.16
        name: cloudsql-proxy
        command: ["/cloud_sql_proxy", "--dir=/cloudsql",
                  "-instances=library-259506:asia-south1:library=tcp:3306",
                  "-credential_file=/secrets/cloudsql/credentials.json"]
        volumeMounts:
          - name: cloudsql-oauth-credentials
            mountPath: /secrets/cloudsql
            readOnly: true
          - name: ssl-certs
            mountPath: /etc/ssl/certs
          - name: cloudsql
            mountPath: /cloudsql
      # [END proxy_container]
      # [START volumes]
      volumes:
        - name: cloudsql-oauth-credentials
          secret:
            secretName: cloudsql-oauth-credentials
        - name: ssl-certs
          hostPath:
            path: /etc/ssl/certs
        - name: cloudsql
          emptyDir:
      # [END volumes]
# [END kubernetes_deployment]

---
    # [START service]
    # The library-svc service provides a load-balancing proxy over the polls app
    # pods. By specifying the type as a 'LoadBalancer', Container Engine will
    # create an external HTTP load balancer.
    # The service directs traffic to the deployment by matching the service's selector to the deployment's label
    #
    # For more information about external HTTP load balancing see:
    # https://cloud.google.com/container-engine/docs/load-balancer
    apiVersion: v1
    kind: Service
    metadata:
      name: library-svc
    spec:
      type: LoadBalancer
      ports:
      - port: 80
        targetPort: 8080
      selector:
        app: library

    # [END service]

The Dockerfile:
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/

# Server
EXPOSE 8080
STOPSIGNAL SIGINT
ENTRYPOINT ["python", "manage.py"]
CMD ["runserver", "0.0.0.0:8080"]

library-app container logs
2019-12-07T02:03:58.742639999Z Performing system checks...
 I
2019-12-07T02:03:58.742701271Z
 I
2019-12-07T02:03:58.816567541Z System check identified no issues (0 silenced).
 I
2019-12-07T02:03:59.338790311Z December 07, 2019 - 02:03:59
 I
2019-12-07T02:03:59.338986187Z Django version 2.2.6, using settings 'locallibrary.settings'
 I
2019-12-07T02:03:59.338995688Z Starting development server at http://0.0.0.0:8080/
 I
2019-12-07T02:03:59.338999467Z Quit the server with CONTROL-C.
 I
2019-12-07T02:04:00.814238478Z [07/Dec/2019 02:04:00] "GET / HTTP/1.1" 400 26
 E
  undefined

library container logs:
2019-12-07T02:03:56.568839208Z Performing system checks...
 I
2019-12-07T02:03:56.568912262Z
 I
2019-12-07T02:03:56.624835039Z System check identified no issues (0 silenced).
 I
2019-12-07T02:03:56.669088750Z Exception in thread django-main-thread:
 E
2019-12-07T02:03:56.669204639Z Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection
    self.connect()
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 195, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 126, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection refused
 E
2019-12-07T02:03:56.672779570Z  Is the server running on host "127.0.0.1" and accepting
 E
2019-12-07T02:03:56.672783910Z  TCP/IP connections on port 3306?
 E
2019-12-07T02:03:56.672826889Z
 E
2019-12-07T02:03:56.672903098Z
 E
2019-12-07T02:03:56.672909494Z The above exception was the direct cause of the following exception:
 E
2019-12-07T02:03:56.672913216Z
 E
2019-12-07T02:03:56.672962576Z Traceback (most recent call last):
  File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/local/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
    self.check_migrations()
  File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 453, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/usr/local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 49, in __init__
    self.build_graph()
  File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 212, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations
    if self.has_table():
  File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 56, in has_table
    return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 256, in cursor
    return self._cursor()
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 233, in _cursor
    self.ensure_connection()
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection
    self.connect()
  File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection
    self.connect()
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 195, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 126, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: could not connect to server: Connection refused
 E
2019-12-07T02:03:56.684080787Z  Is the server running on host "127.0.0.1" and accepting
 E
2019-12-07T02:03:56.684085077Z  TCP/IP connections on port 3306?
 E

Cloud SQL proxy container logs:
2019-12-07T02:03:57.648625670Z 2019/12/07 02:03:57 current FDs rlimit set to 1048576, wanted limit is 8500. Nothing to do here.
 E
2019-12-07T02:03:57.660316236Z 2019/12/07 02:03:57 using credential file for authentication; email=library-service@library-259506.iam.gserviceaccount.com
 E
2019-12-07T02:03:58.167649397Z 2019/12/07 02:03:58 Listening on 127.0.0.1:3306 for library-259506:asia-south1:library
 E
2019-12-07T02:03:58.167761109Z 2019/12/07 02:03:58 Ready for new connections
 E
2019-12-07T02:03:58.865747581Z 2019/12/07 02:03:58 New connection for "library-259506:asia-south1:library"
 E
2019-12-07T03:03:29.000559014Z 2019/12/07 03:03:29 ephemeral certificate for instance library-259506:asia-south1:library will expire soon, refreshing now.
 E
2019-12-07T04:02:59.004152307Z 2019/12/07 04:02:59 ephemeral certificate for instance library-259506:asia-south1:library will expire soon, refreshing now.
 E

A: I can't believe it the issue was my library.yaml file was missing this for the cloud proxy. I believe "RunAs" -- Controls which user ID the containers are run with -- this forces it to run as  daemon user and allows us specify RunAsUser which can be overridden by RunAsUser in SecurityContext on a per Container basis.
https://cloud.google.com/solutions/best-practices-for-operating-containers#avoid_running_as_root
 # [START cloudsql_security_context]
    securityContext:
      runAsUser: 2  # non-root user
      allowPrivilegeEscalation: false
  # [END cloudsql_security_context]

From docs https://kubernetes.io/docs/concepts/policy/pod-security-policy/#users-and-groups: "MustRunAsNonRoot - Requires that the pod be submitted with a non-zero runAsUser or have the USER directive defined (using a numeric UID) in the image. Pods which have specified neither runAsNonRoot nor runAsUser settings will be mutated to set runAsNonRoot=true, thus requiring a defined non-zero numeric USER directive in the container. No default provided. Setting allowPrivilegeEscalation=false is strongly recommended with this strategy."


text:
Q: How to automatically draw several plots for several dataframe together in R? I have several dataframes they are the same type only different values, how to generate same type of plots one by one?
I usually do:
A = df1
B = df2
C = df3

plot(A)
plot(B)
plot(C)

Can I do it in a simple way just use A, B, C names?