text:
Q: Changing to MYSQL compliant date format using python I currently have a csv file containing a column of dates that is formatted as dd/mm/yyyy but i want to change it to yyyy/mm/dd
I have written the code below:
import csv
csv_in = open('news.csv','rb')

for rows in csv.reader(csv_in):
    value = rows[0]
    day= value[:2]
    year= value[-4:]
    month= value[3:5]
    edited = year +'/'+month+'/'+day
    rows[0] = edited
    writer =csv.writer(open('newsedit.csv', 'wb'))
    writer.writerow(rows)

for some reason the code above will only write one row and stop and i can't seem to figure out why this is happening.

A: It is because you keep initializing a new writer in each iteration. This causes that the output is being replaced over and over again. You should create a writer object only once, then you can use its writerow() method repeatedly.
(Btw. there is a nice datetime module that makes working with dates easy...)

A: Try convert the date by datetime module.
import datetime
datetime.datetime.strptime("25/01/2013", '%d/%m/%Y').strftime('%Y/%m/%d')

The strptime function loads a string to datetime object while strftime converts the datetime to another format as string.


text:
Q: Move semantics in a game of solitaire I'm writing a solitaire backend in C++. Life is easier if I didn't have to wonder whether something is being copied or moved, but what's the point of C++ in that case? I'd just use Python :D.
Anyhoo - I have a Card object which observes the rule of 5 (It has a Constructor, Copy Constructor, Copy Assignment Operator, Move Constructor, Move Assignment Operator). I have separate classes for the various stacks of cards.
So far, I've been using a std::vector<Card> cards to store the cards and every time I need to move a card from one stack to another, I do:
auto last_card = cards.back(); // Get the last element in the collection.
cards.pop_back(); // Remove the last element.
return std::move(last_card); // Move the card and return it.

My question is - Is this the right way to do this? Should I instead have a std::vector<std::unique_ptr> instead so that all I'm ever doing is copying/moving pointers around and not the real objects?
I'm looking for best practices as I'm still new to C++. Any tips/advice will be much appreciated.
Thanks!
EDIT: To clarify, Card object is quite simple really. Just a suit, value and color (inferred by suit). All 3 are enums and there are additional helper functions for flipping the card, checking if it's face up or down etc.

A: This is pretty much fine, except for a couple of details:
return std::move(last_card); // Move the card and return it.

It's a common misconception that you need to, or should, do this. In a return statement, the thing on the right is automatically an xvalue so it is in a moveable condition already. In that sense, std::move is redundant there.
But it's a little worse than that because by writing std::move you're making it harder for the compiler to completely elide even the move — by just writing return last_card you will either get the move you wanted in the first place, or even better a total return-value elision that avoids the whole shebang.
Now, currently you have a copy coming out of cards.back(); the cards.back() expression isn't an rvalue there because it's a reference to something that exists elsewhere, which is basically an lvalue! So you might like to do:
auto last_card = std::move(cards.back());

Also I just want to caution you against the "move the card and return it" observation: remember, std::move doesn't move anything, it just gives you an rvalue expression referring to a thing. If a move occurs, it'll be within the return operation, not before it.
In conclusion, my suggestion:
// Extract the last element in the collection
auto last_card = std::move(cards.back());

// Remove the now-dead last element
cards.pop_back();

// Return the new card (will automatically be moved if elision doesn't occur)
return last_card;

But, this is all kind of moot based on your description of Card, which is very simple and doesn't get any benefit from a move. Frankly you could just copy it around and get the same results. Still, it's nice to be prepared for it to become more complex in the future. Certainly there's nothing here that screams for a unique_ptr.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HttpContext.Current null when making a function Asynchronous in MVC4 I am currently working on MVC4 in VS2010-SP1. I made one of the function in
 the controller class Asynchronous. As part of that I made the controller class
 derived from AsyncController and added the below two methods ( see code section 1 and
 2 below). one method ending with Async(See Code Section 1 ) and another method ending
 with Completed ( See Code Section 2 ). The problem is in the model class I am trying
 to access my webservice with credentials from HttpContext ( See Code below 3 ). The
 context is going null when making an asynchronous call. ie, In the new thread
 httpcontext is not available. How to pass the context from main thread to new threads
 created.
Code Section 1
public void SendPlotDataNewAsync(string fromDate, string toDate, string item)
{

         AsyncManager.OutstandingOperations.Increment();
                    var highChartModel = new HighChartViewModel();
                    Task.Factory.StartNew(() =>
                    {
                          AsyncManager.Parameters["dataPlot"] =
highChartModel.GetGraphPlotPointsNew(fromDate, toDate, item);
                          AsyncManager.OutstandingOperations.Decrement();
                      });

}

Code Section 2
 public JsonResult SendPlotDataNewCompleted(Dictionary<string, List<ChartData>>
 dataPlot)
 {
      return Json(new { Data = dataPlot });
 }

Code Section 3
public List<MeterReportData> GetMeterDataPointReading(MeterReadingRequestDto
meterPlotData)
{

            var client = WcfClient.OpenWebServiceConnection<ReportReadingClient,
IReportReading>(null, (string)HttpContext.Current.Session["WebserviceCredentials"] ??
string.Empty);

                try
                {
                    return
ReadReportMapper.MeterReportReadMap(client.GetMeterDataPointReading(meterPlotData));
                }
                catch (Exception ex)
                {
                    Log.Error("MetaData Exception:{0},{1},{2},{3}",
ex.GetType().ToString(), ex.Message, (ex.InnerException != null) ?
ex.InnerException.Message : String.Empty, " ");
                    throw;
                }
                finally
                {
                    WcfClient.CloseWebServiceConnection<ReportReadingClient,
IReportReading> (client);
                }

                }

A: HttpContext.Current is null because your task is executed on a pool thread without AspNetSynchronizationContext synchronization context.
Use TaskScheduler.FromCurrentSynchronizationContext():
Task.Factory.StartNew(() =>
    {
        AsyncManager.Parameters["dataPlot"] =
            highChartModel.GetGraphPlotPointsNew(fromDate, toDate, item);
        AsyncManager.OutstandingOperations.Decrement();
    },
    CancellationToken.None,
    TaskCreationOptions.None,
    TaskScheduler.FromCurrentSynchronizationContext());


text:
Q: Coerce Logical to Numeric in PowerBI I am creating a new column in PowerBI and would like to return a column with 1s or 0s depending on whether a logical condition is true or false. I would have expected the following to work (as it is similar to type coercion in Excel and other languages)
= 1*([Value] < [Threshold])

However, it returns an error:
Expression.Error: We cannot apply operator * to types Number and Logical.
Details:
    Operator=*
    Left=1
    Right=TRUE

I have got the result I want by returning a logical value and then manually converting the type, however this seems inefficient. How would the above be accomplished with just a formula?

A: If you're adding the column using DAX, then you can use the INT function:
= INT ( [Value] < [Threshold] )

If you're using M (Power Query) then you can use the Number.From function:
= Table.AddColumn(#"Previous Step", "My Column", each Number.From([Value] < [Threshold]), Int64.Type)


text:
Q: Dask support for CSV file with header It seems that dask does not support reading a CSV file that includes a header. When I try to read it I get
 TypeError: 'NoneType' object has no attribute '__getitem__'

I can read the same file with pandas with no problem and with dask without the header, but them dask attributes the first line as the header. Is this a bug?

A: Dask.dataframe supports CSV files with headers:
In [1]: cat foo.csv
name,amount
alice,100
bob,200

In [2]: import dask.dataframe as dd

In [3]: dd.read_csv('foo.csv').compute()
Out[3]:
    name  amount
0  alice     100
1    bob     200

But generally CSV files can be tricky.  If you raise an issue with a sample file that fails we can track down what's going on and resolve the problem.


text:
Q: Run Netcat from a Browser i have a Question. Request you to read the scenario as follows:
Let's say the netcat is already there on a remote machine (Note :It's not listening to any port).i have the only option to make it start listening on some specific port from my Browser only. So can u please tell me how can i make it start listening, because technically, whenever u access that file remotely, the browser ask u to download/save it.
But what i want is that, i want to run it on the target machine so that i can have full access to that remote machine.
So is it possible to run netcat from a browser on the target Machine???
ThanX in Advance

A: It is a security risk, but possible, like this. Make a CGI script and place it wherever your server expects to find them - check in your httpd.conf. Save the following script as test.cgi and make it executable using chmod.
#!/usr/bin/perl

use strict;
use warnings;
use Proc::Daemon;

print "Content-type: text/plain\n\n";
print "Starting nc...\n";
Proc::Daemon::Init;
`/usr/bin/nc -l 2222`;

Now just put the address of the script into your browser's address bar and hit Enter. I have just made it listen on port 2222 and do nothing with the incoming data - but you can do whatever you likw with the data you receive - including piping it to a shell for far greater security risk :-)
Note You may need to install Proc::Daemon into your Perl distro if not already installed.
Note You will need to set the Options ExecCGI and do AddHandler cgi-script .cgi
Note
If you cannot, or do not want to install Proc::Daemon, you can hack it like this:
#!/usr/bin/perl

use strict;
use warnings;

print "Content-type: text/plain\n\n";
print "Starting nc...\n";
my $pid=fork();
die "Unable to fork: $!" if !defined $pid;

if($pid==0){
   # This is the child, run netcat
   open STDIN, "</dev/null";
   open STDOUT,">/dev/null";
   open STDERR,">/dev/null";
   `/usr/bin/nc -l 2222`;
} else {
   print "Child started\n";
}


text:
Q: Refactoring to inline a class usage? I had a function which became too big, so I refactored variables into fields on a (new) class and parts of the method to methods on the class. My function now looks like this
void doSomething() {
    Resource resource = ....
    new HelperClass(resource)
          .doFirstThing()
          .doSecondThing()
          .closeResource();

Now I wish to do the inverse transformation (because the doSomething function is actually a testcase and I need to produce a nice linear testcase that I can post to Issue Tracker).
How do I do this using automatic refactoring tools in IntelliJ Idea Community?

A: I don't think a direct undo is possible, but check the local history (right click -> Local History -> Show History) to view previous versions of the original class.    These versions will have been created automatically by IntelliJ when various events have occurred, including saving after changes.  You can then selectively restore the state you want


text:
Q: Will read (socket) block until the buffer is full? I wrote a simple C socket program that sends an INIT package to the server to indicate to prepare a text transfer. The server does not sends any data back at that time.
After sending the INIT package the client sends a GET package and waits for chunks of data from the server.
So every time the server receives a GET package it will send a chunk of data to the client.
So far so good. The buffer has a size of 512 bytes, a chunk is 100 Bytes plus a little overhead big.
But my problem is that the client does not receive the second message.
So my guess is that read() will blpck until the buffer is full. Is that right or what might be the reason for that?

A: It depends. For TCP sockets read may return before the buffer is full, and you may need to receive in a loop to get a whole message. For UDP sockets the size you read is typically the size of a single packet (datagram) and then read may block until it has read all the requested data.

A: The answer is no:  read() on a tcp/ip socket will not block until the buffer has the amount of data you requested.   read() will return immediately in all cases if any data is available, even if your socket is blocking and you've requested more data than is available.
Keep in mind that TCP/IP is a byte stream protocol and you must treat it as such.   The interface is under no obligation to transmit your data together in a single packet, as long as it is presented to you in the order you placed it in the socket.

A: The answer is no , read is not blocking call , You can refer below points to guess the error
Several Checkpoints you can find :

*

*Find out what read is returning at the second time .

*memset the buffer every time in while before recv

*use fflush(stdout) if not able to output.

Make sure all three are present . if problem not solved yet .please post source code here


text:
Q: Play Framework - Ajax web service call image request issue I have developed web service using Play framework. I have created POST rest service in Play framework as below.
In routes file:
POST    /imageUpload        controllers.Application.imageUpload()

In Application.java:
public static Result imageUpload() {
    ObjectNode result = Json.newObject();

    MultipartFormData body = request().body().asMultipartFormData();
    FilePart file = body.getFile("file");
    File trainImg = file.getFile();
    File temp = new File("/Play_Framework/temp.jpg");
    trainImg.renameTo(temp);// moved the image to another folder to check the correct image.

    .
    .
    .

    return ok(result);
}

In the service, I have written the code to save the image which is received from the request.
I have called this service from the Ajax as given below.
In my index.html file:
var formData = new FormData();
var blob = new Blob([imageData], { type: "image/jpg"});
formData.append("file", blob, "capturedImage.jpg");

$.ajax({
       url: 'http://localhost:9000/imageUpload',
       data: formData,
       crossDomain: true,
       processData: false,
       contentType: false,
       async: false,
       cache: false,
       dataType: "json",
       type: 'POST',
       success: function(data){
            alert(data);
            var responseStr = JSON.stringify(data);
                alert("Response str -- "+responseStr);
       }
       });

When I upload the file as Multipart form data, I can receive it as multipart data in the server side. But it is stored as "multipartBody7906599875117091855asTemporaryFile".
If I get this file's mimitype - "content/unknown".
When I debug, I got the below multipart form data path "/var/folders/f3/r3rfqfl949z5pf2cprwn95dm0000gn/T/multipartBody7906599875117091855asTemporaryFile".
How do parse this as "jpg" file? Can anyone help me to do this?

A: The following worked for me:
Application.java
public class Application extends Controller {

    public static Result index() {
        return ok(index.render("SO answer 30229421"));
    }

    public static Result imageUpload() {
        ObjectNode result = Json.newObject();

        Http.MultipartFormData body = request().body().asMultipartFormData();
        Http.MultipartFormData.FilePart file = body.getFile("file");
        File trainImg = file.getFile();
        File temp = new File("/tmp/temp.jpg");
        trainImg.renameTo(temp); // moved the image to another folder to check the correct image.

        result.put("path", temp.getAbsolutePath());
        return ok(result);
    }

    public static Result imageDownload(String path) {
        return ok(new File(path));
    }

index.scala.html
@(message: String)

@message

    <input type="file" id="imageData"/>
    <button onclick="send()">Send image</button>

The only difference, is that because you didn't include how you get the imageData value, I used this version (as per this SO answer):
var imageData = $('#imageData')[0].files[0];


text:
Q: That update query doesn't work? Hello boys and girls :)
I have that query:
SELECT * FROM customer
INNER JOIN address ON customer.customer_id = address.customer_id
WHERE address.country_id = 176

So i want to update custome.status to 0
I tried with that query but "0 rows affected":
UPDATE customer
INNER JOIN address ON customer.customer_id = address.customer_id
SET customer.status = 0
WHERE address.country_id = 176

I have about 200 ppl with address.country_id = 176 !
Any ideas, thank u !

A: You can try a different approach with EXISTS instead of JOIN
UPDATE
  customer
SET
  status = 0
WHERE
  EXISTS (
    SELECT *
    FROM address A
    WHERE customer.customer_id = A.customer_id AND country_id = 176
  )

Can't recall, but is it possible, that MySQL won't report change for those records where status is already equals to 0?


text:
Q: При использовании canActivate в маршрутизации не заходит в привязанный Guard, а выдаёт ошибку ERROR Error: "[object Object]" Делаю простенькую авторизацию
app-routing.module.ts
...
const routes: Routes = [
  { path : '', redirectTo: '/login', pathMatch: 'full' },
  { path : 'login', component: AuthorizationComponent },
  { path : 'services', component: ServicesPageComponent, canActivate: [AuthorizationGuard]},
  ...
];
...

authorization.guard.ts
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

export class AuthorizationGuard implements CanActivate{

  constructor(private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

     console.log("localStorage = " +  localStorage.getItem('currentUser'));

      if (localStorage.getItem('currentUser'))
          return true;

      this.router.navigate(['login']);
        return false;
  }
}

При переходе на services в AuthorizationGuard не заходит (пути в импортах прописаны правильно). В консоли ошибка:
ERROR Error: "[object Object]"


text:
Q: How to observe powerline modulated signal? I was assigned to observe the modulated signal of a PLC modem, but I have not really started yet. How do I do this? Should I use an oscilloscope or spectrum analyzer? If so, do I just connect it to the power line where the PLC modem is connected?

A: You didn't give the all-important information about what frequencies you are using for the communication.  You can't know if a filter is right if you don't know what frequencies you want to separate.
However, the main point is to attenuate the power line frequency by a large factor.  Here is one simple passive way to do that:

This is a simplistic filter which is basically 4 high pass filters strung together.  I'm assuming the communication frequency is high compared to the power frequency, like 100 kHz or more.  Each high pass filter stage has a rolloff of 1.6 kHz.  60 Hz is far enough below that so you can make the approximation it will be attenuated by 1.6 kHz / 60 Hz = 27.  These filter stages will interact some to give more overall attenuation, but even ignoring that you get at least the single filter stage attenuation to the power of the number of filter stages, or about 495 k in this case.  That means the 120 V 60 Hz power signal will be down to less than 240 µV out of this filter.  100 kHz, which we're assuming is your lowest frequency of interest, is 63 times the high pass filter rollof frequency, so won't be effected much by this filter.
The signal directly out of this filter is not ready for running into a chip like a opamp or microcontroller A/D yet.  The power line has all kinds of nasty noise on it, with some transients that can be a few 100 V.  This filter will pass such short term spikes, which would blow up a opamp or microcontroller.  There needs to be some sort of clamping function, keeping in mind that those component have to be able to handle 100 V or more for a short time.
The voltage rating of the filter components needs to be carefully considered too.  C1 will take most of the 60 Hz voltage, and certainly needs to be rated for power line operation.  Even after just the first stage, the 60 Hz voltage will be low enough to not be a problem for ordinary resistors.  However, the resistors need to be able to handle the temporary high voltage spikes that won't be attenuated by the filter.  Either get resistors rated for a few 100 Volts, or implement the resistors shown in the schematic by 3 or 4 ordinary equal resistors in series.

A: You're saying little (nothing!) about the protocol. Is this Ethernet Over Powerline? The protocol matters because of the frequencies used.
Powerline communication both has a much higher frequency and much lower level than the 50/60Hz mains power. The higher frequency has its limitations: mains wiring isn't really fit for it, and the signal radiation will cause much attenuation over longer distances.
On the other hand the higher frequency makes it easier to separate the signal from the power. You definitely need insulation, and then transformers are an option. Not ideal, because not only will they scale the signal as much as the mains voltage, a common mains transformer's inductance will attenuate the signal (though the transformer's capacitance may provide better coupling, I'm not sure how this balances).
Instead of a transformer you can also insulate through capacitors. These have to be safety capacitors. Couple one capacitor from the phase and one from the neutral to the inputs of a difference amplifier. The capacitors will block most of the low frequency 50/60Hz power, but since the level of this low frequency is so high (120/230V) you'll need a notch filter to get rid of it.
A spectrum analyzer will not make you much wiser, you'll just see at what frequencies communication occurs. Which you probably know. A scope will allow you to watch the signal in the time domain.

A: OK I got a Hantek 5102P hooked to a 100:1 Cat II high voltage probe on channel one. I got a TP-Link Powerline network running and I hooked the 100:1 probe ground wire first to the single phase 230 volt line's ground wire. Then I located the Neutral wire for the power line circuit and hooked the 100:1 channel 1 probe to this neutral wire.
Then you have to set the channel 1 vertical control to 200 mV millivolts volts/div. Then set the Horizontal sec/div to 20 ms milloseconds.
Now you need to fire up the youtube video and watch the traffic of your signal at around 200 kilohertz but it varies. You will see that when your youtube video sends a lot of audio data that the scope will show an immense amount of waves in bursts of data. This is the essence of the wave modulation. Then if you go into FFT math function of the Hantek 5102P you will see that the Flattop wave analysis chart shows a very wide set of frequencies that are modulated upward during the data bursts. You can hit the F7 button on the Hantek to show both the FFT Spectrum Analysis and the normal scope volt/time waves simultaneously in a split dual screen of two graphs.
Even though the TP-Link sends the data over both the Load and Neutral lines of your home wiring AC lines, an oscilloscope can only pick out a signal from a fairly quiet line so trying to see this hi freq modulation on the Load line of your home powerlines at 110 or 230 Volts is like trying to listen to your heart beat at a AC/DC rock show. Best to go and stick the probes of the scope on the Neutral return lines of the home and wack the horizontal and vertical adjustments to find the signal in the wee 200 Khz ranges.
Bon Hantekin'


text:
Q: Cannot find the Amazon redirected url in the BeautifulSoup (Python). Any idea from where to get the redirect url? I'm trying to get the Amazon advertising data using the Amazon Advertising API.
I have to open a specific link: "https://www.amazon.com/ap/oa?client_id=...&scope=cpc_advertising:campaign_management&response_type=code&redirect_uri=https://.../"
, that redirects me to an url where I can give my Login data.
To get that redirect url, I am using the BeautifulSoup in Python. In the Web Inspector I see that the redirect url is in the response headers under the name "location", yet when called with the BeautifulSoup, the "location" is missing.
from bs4 import BeautifulSoup

headers = {'user-agent': 'Thats the User Agent I get from the Web Inspector'}

p = requests.get(
    'Thats the link from which I wll be further redirected')

login_data = {
    'appAction': 'SIGNIN',
    'email': '...',
    'password': '...'
}

with requests.Session() as s:
    url = p.url
    r = s.get(url, headers=headers)
    soup = BeautifulSoup(r.content, 'html.parser')
    login_data['appActionToken'] = soup.find('input', attrs={'name': 'appActionToken'})['value']
    login_data['openid.return_to'] = soup.find('input', attrs={'name': 'openid.return_to'})['value']
    login_data['prevRID'] = soup.find('input', attrs={'name': 'prevRID'})['value']
    login_data['workflowState'] = soup.find('input', attrs={'name': 'workflowState'})['value']
    r = s.post(url, data = login_data, headers=headers)

    print(r.content)

Any ideas from where we can get the redirect urls ?

A: Youself are the master of your application. You have to know the redirect url for your application and set it in the Login-with-Amazon console.
You can set multiple redirect urls for each application in the console.
Something like:
https://www.yourpage.com/login
http://localhost:8080/login

See also:
https://advertising.amazon.com/API/docs/en-us/setting-up/generate-api-tokens


text:
Q: debugging issues inside applab I am currently creating a quiz creator on appLab for my CS final and I have most of my code working although some of the onEvent lines of my code keep repeating even though I do not have a loop there. I have called the function a few times inside of my program which might be the reason it is malfunctioning. I have tried refactoring the code and splitting up the function into 2 smaller functions one that handles declaring the variables and one that makes the changes to the screen. The main issue is that the code inside the onEvent loop is repeating so I cannot add a counter to count how many questions the user has made correct or incorrect. I am super confused as I have been trying to fix this bug for the past few days. at first, it seems to be working but when you slow down the code before you click on an answer you will see the issue inside the quiz function in the onEvent lines. Thank you so much for helping me out!
here is a link to my project if you want to reference the code (for some reason the formatting of the code does not work in stack overflow)
https://studio.code.org/projects/applab/bzlJBCafMhrd-LAGoqro3nXw8hQ7tJBLxj-N3In9kwo`enter code here`

A:
some of the onEvent lines of my code keep repeating even though I do not have a loop there

The answer can be found in this Code.org forum thread. The key statement is:

*

*When you call onEvent() it creates a new event handler sitting in the background responding to events. Once you've created an event handler, there's no way to get rid of it. When you restart the game the old event handlers are still hanging out in the background and new event handlers are created...
In your case, restart the game means just going to the next quiz screen, calling the function quiz(), wherein you call onEvent(). In the second run of quiz() a second event handler is created, hence the callback function is called twice, in the third quiz round thrice, and so on. So, to avoid this, don't call onEvent() repeatedly for the same UI element event.


text:
Q: Open a URL in a Firefox instance running on another computer? I have Firefox running, and from the command line I can open a new tab by just typing:
firefox http://stackoverflow.com

What I'm trying to accomplish is similar, but remotely. I have Firefox running on machine B. From machine A I want to be able to run (after setting whatever ssh tunneling or similar is needed) something like:
firefox http://stackoverflow.com

However the tab should open not on machine A, but rather on machine B. I don't want X11 forwarding, I just want to be able to instruct Firefox on a remote machine to open a given URL.
Any ideas?

A: On the machine where Firefox will run and display (machine A), you need to:

*

*Specify which X server to connect to, e.g. set DISPLAY=:0.0 .

*Authenticate somehow to the X server. An easy way is to read the value of $XAUTHORITY in the X session and use the same one.

For example, in a terminal in the X session do:
$ echo $XAUTHORITY
/var/run/gdm/auth-for-ambro-j3bu8Q/database

Then from the SSH terminal, do, as the same user as the X session (otherwise use su):
DISPLAY=:0.0 XAUTHORITY=/var/run/gdm/auth-for-ambro-j3bu8Q/database firefox http://stackoverflow.com

You can have the value of $XAUTHORITY automatically written somewhere when you login. For example, create the following script ~/write-xauth (don't forget to chmod +x):
#!/bin/bash
touch "$HOME"/.saved-xauthority
chmod u=rw,g=,o= "$HOME"/.saved-xauthority
echo "$XAUTHORITY" > "$HOME"/.saved-xauthority

Then create an autostart file that will run the above script, ~/.config/autostart/save-xauthority.desktop :
[Desktop Entry]
Type=Application
Name=Save XAUTHORITY to .saved-xauthority
Exec=/home/<type_user>/write-xauth
Terminal=false
X-KDE-StartupNotify=false
StartupNotify=false

Once you have a shell on machine B (the machine on which firefox will not display), you just have to SSH to machine A (where firefox will run and will display) and run the firefox command I posted. It is possible to automate this into a script on machine B. You'll have use keys (rather than password) for SSH authentication to machine A. For example, see https://wiki.archlinux.org/index.php/SSH_Keys . This will allow you to ssh non-interactively without entering a password. Now you can run commands on machine A from machine B by typing:
ssh machineA command argument ...

In your case, you'd probably want to make a script on machineA for opening the Firefox window:
ssh machineA ./open_local_firefox http://whatever

And this script would look something like:
#!/bin/bash
export DISPLAY=:0.0
export XAUTHORITY=$(cat "$HOME"/.saved-xauthority)
firefox "$1" &>/dev/null 2>&1 &

It's worth noting that this setup will allow machine B to run anything on machine A as the user you're SSHing as. It's possible to limit this, but it's not easy. If you want to do this with SSH, sshd's ForceCommand option would probably help.
There are other ways of doing this of course, but it all boils down to running the 'firefox' command on machine A with the right environment vars (as shown above) as the right user. For example, you can set up an HTTP server and a script on machine A, such that a certain POST request will open that Firefox window. This is probably easier to secure than the SSH approach.

A: Your question is not very clear. If you mean, that you are sitting in front of your local machine L and want to run firefox on a running X session on remote machine R, you can do the following:
From your machine L login to the remote machine R with ssh:
ssh wife@remotemachine

Search for the running X displays on the remote machine (displays correspond to a socket in /tmp/.X11-unix):
ls -l /tmp/.X11-unix/

The following was the result in my case:
srwxrwxrwx. 1 erik         erik         0 13. Jun 14:44 X0
srwxrwxrwx. 1 concubine    concubine    0 13. Jun 11:40 X1
srwxr-xr-x. 1 gdm          gdm          0 13. Jun 11:13 X1024
srwxrwxrwx. 1 gdm          gdm          0 13. Jun 16:17 X2
srwxrwxrwx. 1 wife         wife         0 13. Jun 16:25 X3

I want to show my wife something on her display, therefore I do:
export DISPLAY=:3

This corresponds to the socket X3.
After that I just run:
firefox 'http://superuser.com/a/1088747/180675'

to show her this interesting answer.


text:
Q: In mysql, find all instances of a named column that are not foreign keys This one has had me trumped for a while!
I want to run a query to retrieve all instances of a column (from information_schema, I guess) that ARE or ARE NOT foreign keys.
Now, let me back off a little and explain my real need. I have a rather large database dealing with company information. Now, I want to be able to delete (or update) a customer record, and have all related foreign keys affected by CASCADE. Now, if the foreign key constraints are not duly set everywhere, then a few records might be orphaned.
So, I want to first query to get a bird's eye view of my column. Now let's assume that all instances of this column have the same name "mycol".
I've taken note of the table REFERENTIAL_CONSTRAINTS, but got intimidated ;). One immediate constraint (pardon the pun) I've seen is: the field CONSTRAINT_NAME is populated with names like customer_ibfk_1, since the naming of FK constraints on this project was left for mysql to handle as default. This table has no field for "REFERENCED_COLUMN", and so I'm stumped.
Any help please!

A: Here's what I eventually came up with. Of course, I'm open to input/refinements from the DBA grandfathers around here! But for now, this approach is giving me the info I need.
USE INFORMATION_SCHEMA;

Get all tables that have at least one foreign key referencing a column in "mytable"
SELECT TABLE_NAME, COUNT(*) AS reference_count
FROM REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = 'mydb'
    AND REFERENCED_TABLE_NAME = 'mytable' GROUP BY TABLE_NAME;

Get all tables that have at least one foreign key on a column named "mycolumn"
SELECT TABLE_NAME
FROM KEY_COLUMN_USAGE
WHERE CONSTRAINT_SCHEMA = 'mydb'
    AND COLUMN_NAME = 'mycolumn'
    AND REFERENCED_TABLE_SCHEMA IS NOT NULL;

Get all tables that have ANY COLUMN named "mycolumn". The subquery in the WHERE clause AND (SELECT Table_Type FROM TABLES WHERE table_schema = 'mydb' AND TABLE_NAME = COLUMNS.TABLE_NAME) is necessary, otherwise it would return also any VIEW having a column named "mycolumn"
SELECT TABLE_NAME
FROM COLUMNS
WHERE
    TABLE_SCHEMA = 'mydb'
    AND COLUMN_NAME = 'mycolumn'
    AND (SELECT Table_Type
        FROM TABLES WHERE table_schema = 'mydb'
        AND TABLE_NAME = COLUMNS.TABLE_NAME) = 'BASE TABLE';

Now, using the 2 previous queries, we can obtain any tables having a column named "mycolumn" but in which "mycolumn" is NOT A FOREIGN KEY. Note that this filtering will not respect a PRIMARY KEY, and will also return any table where "mycolumn" is a PRIMARY KEY.
SELECT TABLE_NAME
FROM COLUMNS
WHERE TABLE_SCHEMA = 'mydb'
    AND COLUMN_NAME = 'mycolumn'
    AND (SELECT Table_Type
        FROM TABLES
        WHERE table_schema = 'mydb'
            AND TABLE_NAME = COLUMNS.TABLE_NAME) = 'BASE TABLE'
    AND TABLE_NAME NOT IN
        (SELECT TABLE_NAME
        FROM KEY_COLUMN_USAGE
        WHERE CONSTRAINT_SCHEMA = 'mydb'
            AND COLUMN_NAME = 'mycolumn'
            AND REFERENCED_TABLE_SCHEMA IS NOT NULL
        );

A: Foreign key can be multicolumn, so having single value like "REFERENCED_COLUMN" is not possible. Instead the table seems to refer to index covering the referenced column(s), you could try to check these.
But there seems to be better possibility with information_schema.KEY_COLUMN_USAGE, which lists directly table/column name and for it referenced table/column name. I tried to test and show it in this fiddle http://sqlfiddle.com/#!9/3d96f/2
If you do query of all instances of your column name, you can then left-join it to this by table and column to see, if FK exists or if you get null.


text:
Q: RegisterScript firing order I would like to know if any of you knows when exactly the scripts injected using ScriptManager's RegisterScript function fired inside a webpage

A: Here is what I found in the msdn:

The script block added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised. The script blocks are not guaranteed to be output in the order they are registered. If the order of the script blocks is important, use a StringBuilder object to gather the scripts together in a single string, and then register them all in a single client script block.

Hope this helps.


text:
Q: How to use wordpress text editor in php page I read this article: Use Wordpress Text Editor in non-wp page and found out no solution. Currently i want to embedded a wp text editor to a php page. I tried tinymce but the text editor does not look like the wp text editor (totally different especially missing text and visual tab). Is there anyway to use exactly wp text editor in php page?
my code:
<?php
    $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
    require_once( $parse_uri[0] . 'wp-load.php' );
    $my_text_setting = array("media_buttons"=>false, "textarea_rows"=>get_option('default_post_edit_rows', 5));
    wp_editor("","my_text_editor",$my_text_setting);

?>

A: The wordpress editor is designed to work in wordpress enviroment and there is not much point in trying to somehow make it work "outside" of wordpress. You might hack it but any wordpress upgrade might break it.
You need to use your php in the wordpress context by making a page template for your theme out of the your php.


text:
Q: Unable to redirect to a VF Page This is my lex controller
({
    handleClick : function(component, event, helper) {

        var recId = component.get('v.recordId');
        var retURL = component.get('v.pdf');
        retURL = window.open("apex/Letter?recordId="+recordID);

    }
})

Lex component
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId">
   <lightning:button label="PDF" onclick ="{!c.handleClick}"/>
   <aura:attribute name="recordId" type="String"/>
</aura:component>

when I have clicked on PDF button on my record page I got a message URL doesn't exist.
Someone in my org has deleted my controller, I have written the same code previously which used to work, now it's not working

A: Three things.
First, don't specify recordId when you use force:hasRecordId. If you don't define it exactly correct, you can end up causing bugs.
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId">
   <lightning:button label="PDF" onclick ="{!c.handleClick}"/>
</aura:component>

Second, always specify a leading forward slash in the URL or you'll end up creating a "relative URL"; you'll end up with the wrong URL.
Third, make sure you type the correct variable name, and remember it is case sensitive.
({
    handleClick : function(component, event, helper) {
        var recId = component.get('v.recordId');
        window.open("/apex/Letter?recordId="+recId);
    }
})


text:
Q: Ping error return always equals 0 Having trouble getting this code to work. I can run the script (with changes) in vbscript and it runs fine. But I cant get this version to return a ping error return value other than 0. Any help is appreciated.
This is scanning a list of remote machines with checkboxes and returning the checked values. I want to run the ping to verify the remote machine are there before continuing. But with a error return of 0 for all queries its useless.
function statuschk3(){
var checkedValue = null;
var inputElements = document.getElementsByName("comp");
for(var i=0; inputElements[i]; ++i){
  if(inputElements[i].checked)
  {checkedValue = inputElements[i].value;
var WshShell = new ActiveXObject("WScript.Shell");
var status = WshShell.run ("ping -n 1 -a"  + checkedValue + ",0 ,true");
    if(status == 0)
    {   var fso = new ActiveXObject("Scripting.FileSystemObject");
        var s = fso.OpenTextFile("C:/script/testfile1.txt", 8, true);
        s.WriteLine(checkedValue + " is turned off or off the domain");
        s.Close();
    }
    else`

A: Here's a function I use to test connectivity. I use a vbscript version of this, but I rewrote it in javascript.
function Reachable(strComputer)
{
    var wmiQuery = "Select * From Win32_PingStatus Where Address = '" + strComputer + "'";
    var objWMIService = GetObject("winmgmts://./root/cimv2");
    var colItems = objWMIService.ExecQuery(wmiQuery);
    var enumItems = new Enumerator(colItems)
    for (; !enumItems.atEnd(); enumItems.moveNext())
    {
        var objStatus = enumItems.item();
        if ((objStatus.StatusCode == null) || (objStatus.Statuscode != 0))
        {
            return false //if computer is unreachable, return false
        }
        else
        {
            return true //'if computer is reachable, return true
        }
    }
}

Usage:
vbscript:
If Reachable(strComputer) Then MsgBox "Online" Else MsgBox "Offline"
javascript:
if (Reachable(strComputer)) { alert("Online") } else { alert("Offline") }
edit:
If you'd like to adjust the timeout of this, you can add the following to this line:
var wmiQuery = "Select * From Win32_PingStatus Where Address = '" + strComputer + "' and Timeout=500";

Where 500 is 500 milliseconds.
Here's more on the Win32_PingStatus class, where it says the default Timeout is 1000 milliseconds.
another edit to address your original question:
It looks like you have some syntax issues with your original code:
var status = WshShell.run ("ping -n 1 -a"  + checkedValue + ",0 ,true");

needs to be
var status = WshShell.run ("ping -n 1 -a "  + checkedValue, 0,true);

Notice the location of the space after a and the quotation marks after checkedValue
Also, the logic is backwards. if(status==0) then the device is ONLINE.

A: For what it's worth, if langstrom's WMI solution works, I think I prefer it over my own.  My purpose in answering is to help you figure out what went wrong with your script.
Firstly, ping.exe can receive error responses from the gateway saying "no route to host" or similar.  But having received responses (erroneous or not), the exit status is 0.  It's better to check the output of the command for valid responses to determine success / fail.
But the more immediate problem is that shellObj.run() is forking the ping process asynchronously.  It's non-blocking.
Using shellObj.exec() solves both problems.  Here's an example using console JScript:
// returns 0 for success, non-zero for fail
function ping(host) {

    var osh = WSH.CreateObject('Wscript.Shell'),
        proc = osh.exec('ping -n 1 ' + host);

    while (!proc.Status) WSH.Sleep(25);
    return !/\btime\b/i.test(proc.StdOut.ReadAll());
}

Unfortunately, since browser / HTA JScript doesn't understand WSH or Sleep, you have to get creative with setInterval to block until the ping executable is finished.  (This is why langstrom's WMI solution would be preferable to spawning an executable.  Trying to hack a non-blocking command into something that blocks is cumbersome and awkward with HTA JScript.)
// alerts true on success, false on fail
function ping(host) {

    var osh = new ActiveXObject('Wscript.Shell'),
        proc = osh.exec('ping -n 1 ' + host),
        waitForExit = setInterval(function() {
            if (proc.Status) {
                clearInterval(waitForExit);
                alert(/\btime\b/i.test(proc.StdOut.ReadAll()));
            }
        }, 25);
}

ping('localhost');


text:
Q: HTML - xml data islands I am designing a web app and I intent to embed data on an xml island so that I can dynamically render it on an HTML table on the client-side based on options the users will select.
I have the broad concepts, but I need pointers on how to use DOM in navigating my xml. And how to update my xml island possibly for posting back to the server?
Please any links to online resources or a quick advice will be very appreciated.
NB: I understand most of the dynamic HTML concepts and server and client side stuff, so don't shy being very technical in your response:)

A: In W3C HTML there are no XML data islands (unless you're referring to external XML file linked via frames loaded using Javascript), but you can re-use HTML elements and insert metadata in class, title (if you care about HTML4 validity), data-* (HTML5) or your custom attributes.
For DOM navigation you've got DOM Core, like element.childNodes, .nextSibling, .getAttribute(), etc.
DOM can be verbose and tedious to use (e.g. when looking for elements in DOM you have to be careful to skip text nodes), so there are JS libraries like jQuery and Prototype built on top of it that offer more convenient API.
If you intend to a lot of DOM transformations, then Javascript API for XPath and XSLT processor will be handy.

A: What you describe can be done with XML.
However, I think it would be much easier if you used JSON instead of XML. That way, you can directly work with a Javascript object, which is friendlier than navigating XML DOM. Then you can send the serialized JSON form to the server using the JSON library

A: Ajax Patterns has some good examples for using data islands: http://ajaxpatterns.org/wiki/index.php?title=XML_Data_Island


text:
Q: Dynamic realloc inside a function - C I seem to have a problem with reallocating memory of arrays inside a function. Whenever the code gets to realloc, it is shut down due to Segmentation fault.
I call malloc in main:
char* coded_message = (char*) malloc(BASE_LENGTH * sizeof(char));
read_input(&coded_message, &original_message, &char_counter);

Than pass it to a function, which is reading input an if needed be reallocates the memory. So I the function goes like this:
int read_input(char** coded_message){
    ...
    *coded_message = (char*) realloc(*coded_message, (counter + REALLOC_LENGTH) * sizeof(char));
    ...
}

A: C uses pass-by value. The function arguments are passed by value to the called function, thus any chnages made to the argument will not reflect back to the caller.
In this case, from the function read_input(), the assignment (return value of realloc()) to the original_message will not reflect back to the caller, main().
In other words, you can change the content pointed to by read_input, can be changed, but the read_input itself cannot be changed. If you want to change the pointer itself, you need to pass a pointer to the pointer.


text:
Q: Unable to cout char I can't understand the problem here so i hope some can help out
I have program start out like this int main():
    Board br;
    GetNames();
    br.PresentPlayer();

    system("PAUSE");
    return 0;

GetNames() looks like this:
char p[100];
char p2[100];
Board br;
cout << "Please Enter Player 1's Name:";
cin >> _player_name_1;
cout << "Please Enter " << _player_name_1 << "'s Symbol(Make sure its 1 characters long):";
cin >> p;
cout << "Please Enter Player 2's Name:";
cin >> _player_name_2;
cout << "Please Enter " << _player_name_2 << "'s Symbol(Make sure its 1 characters long):";
cin >> p2;
br.SetSymbols(p[0], p2[0]);

Board::SetSymbols(char p,char p2) looks like this:
void Board::SetSymbols(char p1,char p2)
{
_player_char_1 = p1;
_player_char_2 = p2;
_current_player = _player_char_1;
cout << _current_player << endl;
}

Variables are in Board.h:
char _player_char_1;
char _player_char_2;
char _current_player;

And lastly PresentPlayer():
void Board::PresentPlayer()
{
cout << _current_player << endl;

}

So when SetSymbols is executed it prints out _player_char_1 correctly
however when PresentPlayer is executed It prints out those symbols that you would do this alt+numlock numbers
why is this happening??

A: char _player_char_1;
char _player_char_2;
char _current_player;

should be
char *_player_char_1;
char *_player_char_2;
char *_current_player;

Or, since you're using C++, stop using char* (you're not allocating memory for them, or checking bounds), use std::string instead.
void Board::SetSymbols(char p1,char p2)

needs to be
void Board::SetSymbols(char *p1,char *p2)

or even better
void Board::SetSymbols(std::string &p1, std::string &p2)


text:
Q: Center align text within specific area (rectangle) with Imagemagick I need to center align text within a rectangle. It is a composition so we have a background, logo and text.
Here is the code:
$file = 'filename_'.rand(5,15).'.gif';

exec("convert 'images/highres/bg/deer_and_snow_blue.gif' -coalesce -interline-spacing 2 -font fonts/FredokaOneRegular.ttf -fill black -pointsize 16 -annotate +220+520 \"This is some sample text here \" null: \( 'images/uploads/cganewlogored.jpeg' -resize 165.34736842105264x84 -coalesce \) -geometry +666.652631579+501 -layers Composite " . $file);

echo '<img src="'.$file.'" />';

I have an example here of a text aligned version which is fine (image 2). But, i need it to move to the green area (image 2)
Image 1:

Image 2:


text:
Q: Event management platform database design I am trying to create a project for event management website platform (ex: EventBrite, TicketMaster, etc) with laravel 5, where people can create event on my platform, and people also can sell and buy event tickets through my platform. And now i am confused about how to create the database design. Can someone help me to design the basic relational database design structure?
For now, i only thought of the user table, organizer table, event table, event category table. But i dont have any idea when it comes to the booking table, ticket table, and etc.
Thanks very much for the help. :)

A: You can have a look to this project. Attendize is a free, open-source & self-hosted ticket selling and event management platform built with Laravel

*

*https://www.attendize.com

*https://github.com/Attendize/Attendize


text:
Q: Como cadastrar novo em autocomplete Não sei se é o lugar certo para se perguntar, mas sempre vejo o seguinte componente em alguns sistemas:

Gostaria de saber, que plugin é esse?
Se for apenas o jquery ui autocomplete, como é feito aquele button para adicionar?

A: Não sei também que plugin é esse (se colocares o link na pergunta podemos ser mais específicos) mas isso é bem simples de fazer. Basta ter uma div escondida que fica visivel no foco da primeira. Até dá para fazer só com CSS e selectores sibling.
Com algum trabalho no CSS pode dar-se o aspeto que se quiser.
Exemplo:

div{
    opacity: 0;
    transition: opacity 1s;

}

#meuInput:focus ~ div{
    opacity: 1
}
<input type="text" id="meuInput" />

<button>Adicione mais um!</button>

Pode ser também o caso de esse botão estar dentro da primeira (e única no exemplo) option de um select...


text:
Q: How to run linux application in background which uses shell? I have an application/binary from a C program which by defaults uses the shell to take inputs from the user. So, when I start the application in background using & it stops automatically, because of the implementation on which I have no access. When I run this code
iStatus = system("./flute-static -send -a232.0.0.1/6666 a.txt &");

It gives output [1] 21970, the pid.
Then if I press another enter, it gives output
[1]+  Stopped                 ./flute-static -send -a232.0.0.1/6666 a.txt

And obviously it fails to send the data. How can I solve the problem. Please help me. Thanks in advance.

A: You can try nohup
iStatus = system("nohup ./flute-static -send -a232.0.0.1/6666 a.txt &");

Nohup means: do not terminate this process even when the stty is cut off.
Or You can use screen
https://www.mattcutts.com/blog/a-quick-tutorial-on-screen/

A: Read Advanced Linux Programming and about the fork system call; you surely want to use fork(2), execve(2), waitpid(2) with some other syscalls(2) and/or perhaps daemon(3) and/or popen(3). Perhaps using strace(1) on the flute-static program might help you understand more of it.
BTW, you might use some FLUTE library (compile MAD-ALCLIB from its source code!), or simply use an HTTP & FTP client library like libcurl
Whatever you do, if a backgrounded process is reading stdin, it is stopped (see signal(7), tty(4) etc...)! Read also the tty demystified


text:
Q: Istio Gateway Fail To Connect Via HTTPS Deployments in a GKE cluster with Istio is working correctly via HTTP. But when i tried to secure it with cert-manager with following resources, HTTPS request fails state like so on curl
`Immediate connect fail for 64:ff9b::2247:fd8a: Network is unreachable
* connect to 34.71.253.138 port 443 failed: Connection refused`.

What should i do to make it work with HTTPS as well.
ClusterIssuer with following configuration
apiVersion: cert-manager.io/v1alpha2
kind: ClusterIssuer
metadata:
  name: letsencrypt-staging
  namespace: istio-system
spec:
  acme:
    # The ACME server URL
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    # Email address used for ACME registration
    email: iprocureservers@iprocu.re
    # Name of a secret used to store the ACME account private key
    privateKeySecretRef:
      name: letsencrypt-staging
    solvers:
    # ACME DNS-01 provider configurations
    - dns01:
        # Google Cloud DNS
        clouddns:
          # Secret from the google service account key
          serviceAccountSecretRef:
            name: cert-manager-credentials
            key: gcp-dns-admin.json
          # The project in which to update the DNS zone
          project: iprocure-server

Certificate configuration like so, which made a certifiate in a Ready:True state
apiVersion: cert-manager.io/v1alpha3
kind: Certificate
metadata:
  name: letsencrypt-staging
  namespace: istio-system
spec:
  secretName: letsencrypt-staging
  commonName: "*.iprocure.tk"
  dnsNames:
  - '*.iprocure.tk'
  issuerRef:
    name: letsencrypt-staging
    kind: ClusterIssuer

And lastly a Gateway
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: iprocure-gateway
  namespace: default
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "*"
    tls:
      httpsRedirect: false
  - port:
      number: 443
      name: https
      protocol: HTTPS
    hosts:
    - "*"
    tls:
      mode: SIMPLE
      credentialName: letsencrypt-staging

If i do, kubectl describe certificate -n istio-system
    Name:         letsencrypt-staging
    Namespace:    istio-system
    Labels:       <none>
    Annotations:  <none>
    API Version:  cert-manager.io/v1
    Kind:         Certificate
    Metadata:
    Creation Timestamp:  2020-10-13T13:32:37Z
    Generation:          1
    Resource Version:    28030994
    Self Link:           /apis/cert-manager.io/v1/namespaces/istio-system/certificates/letsencrypt-staging
    UID:                 ad838d28-5349-4aaa-a618-cc3bfc316e6e
    Spec:
    Common Name:  *.iprocure.tk
    Dns Names:
        *.iprocure.tk
    Issuer Ref:
        Kind:       ClusterIssuer
        Name:       letsencrypt-staging-clusterissuer
    Secret Name:  letsencrypt-staging-cert-secret
    Status:
    Conditions:
        Last Transition Time:  2020-10-13T13:35:05Z
        Message:               Certificate is up to date and has not expired
        Reason:                Ready
        Status:                True
        Type:                  Ready
    Not After:               2021-01-11T12:35:05Z
    Not Before:              2020-10-13T12:35:05Z
    Renewal Time:            2020-12-12T12:35:05Z
    Revision:                1
    Events:                    <none>

Running kubectl get certificates -o wide -n istio-system, yields
NAME                  READY   SECRET                            ISSUER                              STATUS                                          AGE
letsencrypt-staging   True    letsencrypt-staging-cert-secret   letsencrypt-staging-clusterissuer   Certificate is up to date and has not expired   17h

A: Issue
I assume that https wasn't working because of the requirements which have to be enabled if you want to use cert-menager with istio in older versions.
Solution
As @Yunus Einsteinium mentioned in comments

Thank you for guiding me in the right direction. Using the OSS Istio, not the GKE one, is the way to go! I managed to make HTTPS work!

So the solution here was to use OOS istio installed with istioctl instead of the older istio gke addon.


text:
Q: How to shorten a string Let's say I have following files: 1.html, 2.html and 3.html and I want to rename them to 1.html-bak, 2.html-bak and 3.html-bak. To do this I run following command:
find . -name '*.html' -print0 | xargs -0 -I {} mv {} {}-bak

Everything is OK, files are renamed as expected.
The question is how to rename them back to *.html instead of *.html-bak?
How to remove last 4 chars from string?

A: You can use ${file%-*} to get the desired file name back. The following code loops through all files whose name end with html-bak and performs the renaming by removing everything after the last dash:
for file in *html-bak
do
   echo "mv $file ${file%-*}" # <-- using "echo" for safety. Remove once checked
done

${var%-*} strips the shortest match of * from back of $var. That is, removes until the first dash - is found starting from the right:
$ file="1.h-tml-bak"
$ echo ${file%-*}
1.h-tml

You of course could also use the length, to get everything but the last 4 characters:
$ echo ${file:0:-4}
1.h-tml

A: If you have GNU Parallel you can run:
find . -name '*.html-bak' -print0 | parallel -0 mv {} {.}.html

This works even if the filenames contain ', " and space.
All new computers have multiple cores, but most programs are serial in nature and will therefore not use the multiple cores. However, many tasks are extremely parallelizeable:

*

*Run the same program on many files

*Run the same program for every line in a file

*Run the same program for every block in a file

GNU Parallel is a general parallelizer and makes is easy to run jobs in parallel on the same machine or on multiple machines you have ssh access to.
If you have 32 different jobs you want to run on 4 CPUs, a straight forward way to parallelize is to run 8 jobs on each CPU:

GNU Parallel instead spawns a new process when one finishes - keeping the CPUs active and thus saving time:

Installation
A personal installation does not require root access. It can be done in 10 seconds by doing this:
(wget -O - pi.dk/3 || curl pi.dk/3/ || fetch -o - http://pi.dk/3) | bash

For other installation options see http://git.savannah.gnu.org/cgit/parallel.git/tree/README
Learn more
See more examples: http://www.gnu.org/software/parallel/man.html
Watch the intro videos: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1
Walk through the tutorial: http://www.gnu.org/software/parallel/parallel_tutorial.html
Sign up for the email list to get support: https://lists.gnu.org/mailman/listinfo/parallel


text:
Q: Elementary question about topology and metric spaces Let $(X, \rho ) $ be a metric space. Denote
$$ \mathscr{B} = \{ B(\epsilon,x) : x \in X, \epsilon>0 \} $$
Let $B_1,B_2 \in \mathscr{B}$ . Let $x \in X$ be arbitrary with $ x \in B_1 \cap B_2 $. I want to find $B_3 \in \mathscr{B}$ such that $x \in B_3 \subset B_1 \cap B_2 $
Attempt:
Fix $b_1,b_2 \in X$ and we say they are the centers of $B_1,B_2$, respectively. Then we have  $B_1 = \{ z \in X : \rho(z, b_1 ) < \epsilon_1 \} $ and $B_2 = \{ z \in X : \rho(z, b_2 ) < \epsilon_2 \} $. Let $x \in X$ be arbitrary with $x \in B_1 \cap B_2 $. After doing some drawings, I think the correct choice for $\epsilon $ would be
$$ \epsilon = \frac{ \min\{ \epsilon_1 - \rho(x,b_1), \epsilon_2 - \rho(x,b_2 )\}}{2} $$
Now, put $B_3 = \{ y : \rho(x,y) < \epsilon \} $. We must check $B_3 \subset B_1 \cap B_2 $. To do this, let $y \in B_3 $. Next,
$$ \rho(y,b_1) \leq \rho(y,x) + \rho(x, b_1) < \epsilon + \rho(x,b_1) \leq \frac{ \epsilon_1 - \rho(b_1,x)}{2} + \rho(b_1,x) =  \frac{ \epsilon_1}{2} + \frac{ \rho(b_1,x)}{2} < \epsilon_1/2 + \epsilon_1/2 = \epsilon_1 $$
Therefore, $y \in B_1$. Similarly, we obtain that $y \in B_2$. In particular, $y \in B_1 \cap B_2$. This implies $B_3 \subset B_1 \cap B_2$.
I would like to know if this a correct approach. Maybe is too long or maybe it has flaws, I don't know. Any feedback would be greatly appreciated

A: $x\in B_{i}=B\left(\epsilon_{i},x_{i}\right)=\left\{ z\in X\mid\rho\left(x_{i},z\right)<\epsilon_{i}\right\} $
for $i=1,2$.
Let's choose for a $B_3$ that is centered at $x$, i.e.
$B_{3}=B\left(\epsilon,x\right)$ for some
$\epsilon>0$.
To achieve $B_3\subset B_1\cap B_2$ it must be so that $\rho\left(x,z\right)<\epsilon$
implies $\rho\left(x_{i},z\right)<\epsilon_{i}$ for $i=1,2$.
$\rho\left(x_{i},x\right)<\epsilon_{i}$ for $i=1,2$ makes it
possible to find some $\epsilon>0$ with $\epsilon<\epsilon_{i}-\rho\left(x_{i},x\right)$
for $i=1,2$.
Then $\rho\left(x_{i},z\right)\leq\rho\left(x_{i},x\right)+\rho\left(x,z\right)<\rho\left(x_{i},x\right)+\left(\epsilon_{i}-\rho\left(x_{i},x\right)\right)=\epsilon_{i}$
for $i=1,2$.

A: You did everything right.
By the way, it is enough to define
$$ \epsilon:=\min\{ \epsilon_1 - \rho(x,b_1), \epsilon_2 - \rho(x,b_2)\}$$

This fact will be trivial when you study general topological spaces. In that case you could just say
$$B_1, B_2\in \tau \ \Rightarrow \  B_1\cap B_2 \in \tau\ \Rightarrow \forall x\in B_1\cap B_2\ \ \exists\, \epsilon>0 \text{ such that } x\in B(x,\epsilon)\subset B_1\cap B_2$$

A: I think your idea is basically right, but it would be better to label $b_1$ and $b_2$ the centres of the balls rather than calling them the "radiuses" which is just confusing. I think your proof would go easier that way. Also consider that a ball is just an open set, so any element within a ball $B$ must have another, smaller, ball around it which is completely contained in $B$. Then just take the smaller of the two radiuses of the balls. That is a much quicker route to the result.


text:
Q: Are dimen values cached? Is there any performance gain over doing the following:
final int pixels = getResources.getDimensionPixelSize(R.dimen.pixels);
for (CustomView view: views) {
    view.setPixelValue(pixels);
}

vs.
for (CustomView view: views) {
    view.setPixelValue(getResources.getDimensionPixelSize(R.dimen.pixels));
}

Or are dimens values cached / the bytecode optimised / some other optimisation that makes this redundant?

A: Looking at Resources.getDimentionPixelSize() and deeper till AssetManager.loadResourceValue() which is native it's impossible to say. However, from Resources.getDimentionPixelSize() source it's possible to say the following:
public int getDimensionPixelSize(int id) throws NotFoundException {
    synchronized (mAccessLock) {
        TypedValue value = mTmpValue;
        if (value == null) {
            mTmpValue = value = new TypedValue();
        }
        getValue(id, value, true);
        if (value.type == TypedValue.TYPE_DIMENSION) {
            return TypedValue.complexToDimensionPixelSize(
                    value.data, mMetrics);
        }
        throw new NotFoundException(
                "Resource ID #0x" + Integer.toHexString(id) + " type #0x"
                + Integer.toHexString(value.type) + " is not valid");
    }
}

*

*It will lock resources by synchronized (mAccessLock)  (read, if some other thread of you will try to access resources same moment - on of them will wait);

*It will call some float math inside TypedValue.complexToDimensionPixelSize();

*It will probably create TypedValue object;

*It will do at least 5 method calls;

So, maybe it's cached somewhere in native, but even so, call will be definitely not free for you.
Here's some measurements I've done for this question (with only single thread accessing resources):
    int pixels = 0;
    Resources res = getResources();
    long ms = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        pixels = res.getDimensionPixelSize(R.dimen.my_dimen);
    }

    Log.e(TAG, "Time " + (System.currentTimeMillis() - ms));

On S6 with Android Lollipop it gives about 816 ms, or 8160 nano-sec / call.
Finally, in your case (I believe you have maximum 10-20 iterations) it really doesn't matter in terms of performance. In more iterations and / or some concurrency in access to resources in might be significant.
Personally I would suggest to do it outside for better style and small but still speed improvement.


text:
Q: ng-click doesn't work inside an  tag I'm working with jstree, and foreach node I want to add a set of action buttons as following :

    <md-button class="md-icon-button" aria-label="Nouveau" ng-click="createNode($event)">
        <md-icon class="material-icons">add_circle</md-icon>
    </md-button>
    <md-button class="md-icon-button" aria-label="Modifier" ng-click="renameNode($event)">
        <md-icon class="material-icons">edit</md-icon>
    </md-button>
    <md-button class="md-icon-button" aria-label="Supprimer" ng-click="removeNode($event)">
        <md-icon class="material-icons">delete_circle</md-icon>
    </md-button>

So what I did is in the directive I created, which wraps jstree, I iterate over nodes and concat these action buttons with the node's text :
value.map(function(node){
    node.text = node.text + addActionButtons();
    return node;
});

addActionButtons() will simply return the action buttons string in above.
So in this case jstree will add the action buttons inside an a tag, as following :

   Label 1

      <md-button class="md-icon-button" aria-label="Nouveau" ng-click="createNode($event)">
         <md-icon class="material-icons">add_circle</md-icon>
      </md-button>
      <md-button class="md-icon-button" aria-label="Modifier" ng-click="renameNode($event)">
         <md-icon class="material-icons">edit</md-icon>
      </md-button>
      <md-button class="md-icon-button" aria-label="Supprimer" ng-click="removeNode($event)">
         <md-icon class="material-icons">delete_circle</md-icon>
      </md-button>

The problem I'm facing here is that when I click on some action button it doesn't trigger the ng-click.
How can I solve this ?
Update:
When I tried to use onclick="alert('test')" it worked, so the problem is only with the ng-click, I think I have to do something like this :
node.text = node.text + $compile(addActionButtons())(scope);

But this adds a string [Object object] in front of my nodes, and not the action buttons.

A: Try to change href="#" to href="javascript:void(0)"

A: I believe the issue you are suffering from is since AddActionButtons is generating a string dynamically, Angular does not recognize the directives as existing.
You will probably need to use the $compile service:
https://docs.angularjs.org/api/ng/service/$compile
Also, consult this answer:
Compiling dynamic HTML strings from database


text:
Q: Git help - proper directory I need some enlightenment here .
$which git
/usr/bin/git
-- so the problem is it is not on the right directory ..
how do I change its path or make it to the right one
/usr/local/bin/git
---- can somebody help me with this


text:
Q: "An exclamation" or "An ejaculation" ? Are these words synonymous? Exclamations and ejaculations are usually expressions of surprise or anxiety, something said quickly and suddenly.  Grammatically they are always interjections and may seem to be the same kind of utterance.   Are they ?

A: A wikipedia search kind of clears the air on the difference. Ejaculate is clearly a word which is used today in an entirely unrelated context- albeit similar (who really expects ejaculations!)
 Both ejaculate and exclaim indicate surprise, but vary in the degree of expression. For instance, an "ooh" or an "aah" is an ejaculation.
Exclamations on the other hand are of two kinds- clausal containing a subject+verb, eg. the very colloquial "God damn it!" and phrasal- consisting of phrases.

A: They are synonyms and  though ejaculation is defined as "a sudden discharging of a fluid from a duct", the connotation is ejection from the urethra.  Unlike Brazil, Americans tend to use a dysphemism with sexual connotations.


text:
Q: routed network, subnetwork clients has broken tcp connection I manage a linux server which works also as a router, and route between following networks:

*

*PPPoE (to connect to ISP) (default gw)

*wired network

*2x VPN networks (PPTP and openVPN)

*wireless AP (DHCP)

All host is reachable from the linux server,the WAN, Wifi, VPN and LAN clients.
But somtimes from the LAN and AP, i can't access some webpages, here is a example:
Now the 8tracks.com is unreacheable (23.23.196.130).
first i try to reach from the AP (same result if i try from LAN)
connection established request sent but no answer come.
closed the connection after 7 secounds.
then i connected from the server, and page loaded successfully.
the other weird: if i try to connect through VPN, connection will be successfull.
i have same routing setting for all networks, firewall rules are unified for all interface.
I have no idea why works connection otherwise with other interface with same configuration.

A: You have probably a legion of masquaraded/NAT-ted connections, too. Linux handles them in a static hash table, which can overflow. After that, you will get exactly this mystic problem.
A command
cat /proc/sys/net/netfilter/nf_conntrack_max

says you, what is the upper limit of this hash map. Multiple this with 13 and set it with the command
echo #muchbiggernumber# >/proc/sys/net/netfilter/nf_conntrack_max

If it was the cause of your problem, you can make this change permanent editing /etc/sysctl.conf intuitively.


text:
Q: Objective-C best method for decrypting NSStrings from .txt file I've have a .txt file containing an NSString (encrypted using a private key) that my application uses (decrypted using a public key). Everything works beautifully for one string, however, if I have another NSString that I want to use I have to create another separate .txt file with that encrypted NSString. I know there has to be a way to put all the NSStrings in one file and somehow parse it, although I'm not sure how to achieve this. Could it be done using a .plist file that contains all the encrypted strings?
This is an example of the code I use to decrypt my .txt file with one NSString:
NSString *filePath = @"/path/to/file.txt";

    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        crypto = [[MyCrypto alloc] initWithPublicKey:publicKeyData privateKey:privateKeyData];

        NSError *err;

        theString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&err];

        if (!theString) {
            NSLog(@"error: %@", err);
        }

[crypto setClearTextWithString:theString];
decryptedTextData = [crypto decrypt];
NSLog(@"Decrypted: %@", theString);

...

If someone can shed some light on the subject with an example I would truly appreciate it.

A: Make a for loop and put your decription code inside, furthermore modify the line
 theString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&err];

to the following (assuming i is the loop variable):
 theString = [array objectAtIndex:i];

Where you created array in the initialization part of your code, using:
NSArray *array = [NSArray arrayWithContentsOfFile:@"file.txt"];

The specified file also has to be a valid PLIST, an array being its root element. Example:
<plist>
<array>
    <string>alshnj369537nwlzba</string>
    <string>9ö876534tzhwjukmhnlfb</string>
    <!-- et cetera... -->
</array>
<plist>

Hope this helps.


text:
Q: MvvmCross: cannot display data in iOS table cell I'm trying to bind a list of objects to a very simple table cell in iOS using Xamarin and MvvmCross and I can't get anything to display.
If I use MvxStandardTableViewSource I can see the items in the list no problem so the issue would not appear to be with the data.
I followed the instructions shown in N+1 6.5 and nothing appeared in my list. I deleted the table cell, followed the instructions again and this time only put one label in the cell and used the default cell height. Still nothing.
Here is my view code:
var tableView = new UITableView(new RectangleF(0, 50, 320, 500), UITableViewStyle.Plain);
Add(tableView);
var source = new MvxSimpleTableViewSource(tableView, JobListCell.Key, JobListCell.Key);
tableView.Source = source;

var set = this.CreateBindingSet<JobListView, JobListViewModel>();
set.Bind(source).To(vm => vm.Jobs);
set.Apply();

tableView.ReloadData();

Here is the JobListCell code:
public partial class JobListCell : MvxTableViewCell
{
    public static readonly UINib Nib = UINib.FromName ("JobListCell", NSBundle.MainBundle);
    public static readonly NSString Key = new NSString ("JobListCell");

    public JobListCell (IntPtr handle) : base (handle)
    {
        this.DelayBind(() => {
            var set = this.CreateBindingSet<JobListCell, JobListItem>();
            set.Bind(JobDescriptionLabel).To(item => item.JobDescription);
            set.Apply();
        });
    }

    public static JobListCell Create ()
    {
        return (JobListCell)Nib.Instantiate (null, null) [0];
    }
}

Here is the cell designer code so you can see the outlet generated:
[Register ("JobListCell")]
partial class JobListCell
{
    [Outlet]
    MonoTouch.UIKit.UILabel JobDescriptionLabel { get; set; }

    void ReleaseDesignerOutlets ()
    {
        if (JobDescriptionLabel != null) {
            JobDescriptionLabel.Dispose ();
            JobDescriptionLabel = null;
        }
    }
}

Here is the class I'm binding to:
public class JobListItem
{
    public int JobId { get; set; }

    public string JobDescription { get; set; }

    public string JobAddress { get; set; }

    public string JobPriority { get; set; }

    public override string ToString()
    {
        return JobDescription;
    }

}

Any ideas?

A: This appears to have been caused by a mismatch between the Xamarin version and the XCode version.
When I upgraded Xamarin to the latest version (Xamarin.iOS 7.2) then deleted and re-created the cell files, all started working as expected.


text:
Q: Error Trying to reinstall Visual Studio 2019 There is 1 other post similar to this one, but its answer is kind of unclear and doesn't apply to my situation.
So, this is a bit of a long story, but it will help you understand my situation better.
First off, I am working with unity. I used Visual Studio in the past before so I didn't have the unity mod, because I did not think I would be using much unity. But now I am, I skimmed through this one youtube video and I thought I had to reinstall Visual Studio. So I made the mistake of deleting a bunch of Visual Studio files from my C: drive and deleting my recycling bin. How stupid of me. I could have just went to the Visual Studio mods website and downloaded it from there. I'm sorry for my stupidity. Anyways, when I tried reinstalling, it brought up this error:
Before we get started
Installation folder: 'C:Program Files(x86)\Microsoft Visual Studio\2019\Community' could not be found.

I tried reinstalling Visual Studio, but it just said the same thing.
Anyone have anything to help?

A: Try creating that folder and moving vs 2019 content into there


text:
Q: How can you prevent a click from firing at the end of a long press? I ask because of this situation:
I put down my finger on a list item. After 500ms, a Hammer press event is triggered, and the page shows an action sheet. After 1s, I raise my finger, and a click event fires (a regular click, not one emitted by Hammer). My finger at that point is over the action sheet backdrop, which has a click handler that closes itself.
I realize using the Hammer tap event to close the action sheet would work, because it has a 250ms maximum duration, but the action sheet library uses a click event. Is there a way to tell the browser to not fire clicks if the duration is eg 250ms? Or to alternatively tell the browser to not emit the next click that happens?

A: Have you implemented the solution below based on the hammer.js page discussion on disabling ghost clicks?
https://developers.google.com/mobile/articles/fast_buttons#ghost
hammer.js

A: I just had the same issue in Ionic: ActionSheet was disappearing after touch end.
I came up with the following workaround: ignore click event on the element right after pressup event in HammerJS by using pointer-events: none. This solution exploits the fact that click event is fired on the element immediately after pressup event, so we are able to prevent it somehow by handling pressup.
In global styles I added the following helper class:
.prevent-pointer-events {
  pointer-events: none;
}

Then, on the same element where I handle the press event I added a new pressup event handler which does the following:
  element.classList.add('prevent-pointer-events');

  setTimeout(() => {
    element.classList.remove('prevent-pointer-events');
  }, 50); // after 50ms we are sure the "click" event was fired and ignored,
          // so we can revert the class name back

Note that this solution is local, just for one element, although it can be extended to handle global pressup event on the document body.


text:
Q: C++17 Template argument deduction failed I wanted to simulate timer which would call a function (callback) periodically for that i wrote following snippet (naive though) wherein,
Argument deduction is failing at line Timer/<int, int, float>/.. in main function. I am compiling this code with c++17 std. How I can fix this? or those arguments necessary?
Any help in this regard is appreciated.
#include <functional>
#include <chrono>

using namespace std::chrono_literals;

template<typename ...Args>
class Timer
{
public:
  Timer(std::function<void(Args...)> func, Args&&... args, std::chrono::milliseconds step)
    : m_callback{ func },
      m_args{ std::forward<Args>(args)... },
      m_time{ step },
      m_stop{ false },
  { }

private:
  std::function<void(Args...)> m_callback;
  std::thread m_executer;
  std::tuple<Args...> m_args;
  std::chrono::milliseconds m_time;
  bool m_stop;
};

int main()
{
  // Create a timer
  auto timer = Timer/*<int, int, float>*/([](int a, int b, float c) { }, 15, 17, 12.0f, 500ms);

  return 0;
}

A: I stripped out everything that wasn't germane to your question (you should do that to make it easier to get help), and here's what I got to work.  First, I moved the milliseconds before the variadic arguments.  It can confuse the compiler where parameter packs end, so you usually want ... to be the last thing in an argument list.
Second, CTAD (Class template arg deduction) is not working for you due to the need to convert your lambda to a std::function before it can match.
If main() passes an actual std::function into your constructor as it expects, then it works:
auto timer = Timer(
    std::function<void(int, int, float)>([](int a, int b, float c) { }),
    500ms, 15, 17, 12.0f);

But that is arguably worse looking than what you originally tried.
The better fix, which is a bit obscure, is to help CTAD figure out what you're doing with a c++17 deduction guide.  This is a pattern match saying,  "if they try to create this class using this syntax, it really means it's this type."
Here's a guide I found to work for you:
template <typename T, typename... Args>
Timer(T&&, std::chrono::milliseconds, Args...) -> Timer<Args...>;

What this guide does is says: they can pass anything T&& as the first parameter and it's just ignored, and thats followed by chrono milliseconds, then some more types in the Args pack.  Given that, the acutal type of Timer (right of the arrow) is just the Timer<Args...> whatever they are.  It then proceeds, and your function just needs to be convertible to the std::function.
Now it matches your use with the lambda, instantiates Timer with the given Args, and from that knows it can convert your lambda to the std::function.
Here's a working example, minus all the stuff that was unrelated:
#include <functional>
#include <chrono>

using namespace std::chrono_literals;

template<typename ...Args>
struct Timer {
  Timer(std::function<void(Args...)> func,  std::chrono::milliseconds step, Args&&... args )
  { }
};

template <typename T, typename... Args>
Timer(T&&, std::chrono::milliseconds, Args...) -> Timer<Args...>;

int main() {
    auto timer = Timer([](int a, int b, float c) { }, 500ms, 15, 17, 12.0f);
}

Compiler Explorer: https://godbolt.org/z/Wa3oK3

A: There are 2 issues with template argument deduction here. The std::function parameter can't be deduced from the lambda argument, and deduction only works for parameter packs when they are trailing.
To fix this, you can change the order of the arguments to the constructor, like this:
Timer(std::function<void(Args...)> func, std::chrono::milliseconds step, Args&&... args)
 // ...                                                              //  ^^^^^^^^^ trailing

and add a deduction guide
template<typename Func, typename ...Args>
Timer(Func, std::chrono::milliseconds, Args&&...) -> Timer<Args...>;

Here's a demo.
Note the warning, your member initializer list is not in the same order as the member declarations.


text:
Q: 301 redirect coz of change in URL structure I have a website which is currently build on Wordpress. It is a News website and hence there are closely around 3000 posts.
Our SEO team is suggesting to change the URL structure from
Post name to Custom Structure.
news.com/financial-budget-2018/ change to news.com/politics/financial-budget-2018/
Need to know if:-

*

*If will have to define 301 redirect rule for each of the 3000 posts in the .htaccess file.

*Whether this should be handled in PHP, where I can do a check of the url segments and accordingly search in the database for the matching new url and then redirect them.

Or any other better way of handling this


text:
Q: mysql: Restore backup that was created with "--tab" option in mysqldump mysqldump has the "--tab" option to split up the dump separate files for each table. mysql creates a .sql file (with schema) and a .txt file (with data) for each table.
The .sql files work fine, but how do I import the data from the .txt files?

A: Official documentation doesn't covert the case of importing these *.txt and foreign key constrains. There is still open long-lived bug#19996 to implement foreign key ignore in mysqlimport. So it has to be done manually.
#!/bin/bash -e

DIR=/path/to/csv/backup
DATABASE=database
USER=user
PASSWORD=password

for filename in $DIR/*.txt
do
tablename=`basename $filename .txt`
mysql --user=$USER --password=$PASSWORD $DATABASE <<EOF
  SET FOREIGN_KEY_CHECKS=0;
  LOAD DATA INFILE '$filename' INTO TABLE \`$tablename\`;
EOF
done

Also I would like to note that there's no much sense in storing these per-table *.sql files produced by mysqldump --tab, because there's also a foreign key issue on fields. As a schema is always known I suggest just to delete them after backup is completed.


text:
Q: Removing horizontal lines from the header and footer of the title page I intend to set two blank pages before my thesis title page. However, the workaround I use does good job for the first page, but introduces horizontal lines
in the title page (there were "text text..." is). The following is my code:
\documentclass[a4paper,12pt]{book}
\usepackage{amsmath, amsthm, amssymb}
\usepackage{url}
\usepackage[algoruled,vlined]{algorithm2e}
\usepackage{graphicx,subfigure}

% for nice tables
\usepackage{booktabs}
% end for nice tables

% for using color names
\usepackage[usenames,dvipsnames]{color}
% end for using color names

% for nicer figure captions
\usepackage[font=small,format=plain,labelfont=bf,up,textfont=it,up]{caption}
% end for nicer figure captions

% fancy headers and footers
\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0.1pt} % for upper line
\renewcommand{\footrulewidth}{0.1pt} % for lower line
\fancyhead[LE,RO]{\itshape \nouppercase \rightmark}
\fancyhead[LO,RE]{\itshape \nouppercase \leftmark}
\fancyfoot[C]{\thepage}
% end fancy headers and footers

% for shaded table cells
\usepackage{colortbl}

% for multirow option in the tables
\usepackage{multirow}

\usepackage[semicolon]{natbib}

\usepackage{fancybox}

\usepackage{xcolor}
\usepackage{framed}

\newcommand{\HRule}{\rule{\linewidth}{0.5mm}}

\newenvironment{myfancybox}{%
  \def\FrameCommand{\fboxsep=\FrameSep \fcolorbox{black}}%
  \color{black}\MakeFramed {\FrameRestore}}%
{\endMakeFramed}

% for theorems, lemmas...
\theoremstyle{plain}            % use "default" font

\newtheorem{thm}{Theorem}[chapter]
\newtheorem{lemma}[thm]{Lemma}
\newtheorem{prop}[thm]{Proposition}
\newtheorem{cor}[thm]{Corollary}
\newtheorem*{thma}{Theorem}

%\theoremstyle{definition}      % use "definition-style" font for the rest

%\bibliographystyle{plain} %Choose a bibliograhpic style

\usepackage{sectsty}
\allsectionsfont{\itshape}

% for height of the heading
\setlength{\headheight}{15pt}

\parskip1ex
\begin{document}
 \begin{titlepage}
\fancyhf{}
\newpage
\mbox{}
\newpage
\mbox{}
\newpage
 {\large text text text text
          text text text text text text text text
         text text text text text text text text
          text text text text text text text text}
\end{titlepage}

\end{document}

Is it possible to get two initial pages blank, and the title page without the horizontal lines? Note that the horizontal lines are necessary for the rest of the document, but should be absent from the title page.

A: You can use \pagestyle{empty} instead of \fancyhf{} to get empty foot and head lines without lines.


text:
Q: How to import sqlite3 in pycharm? How can I use sqlite3 in pycharm?
I found out that sqlite3 is basically included in standard library. However, when I try to import it, the module is not found.
import sqlite3 << this returns a import error.
Is sqlite3 module name different in pycharm?

A: Putting answer for anyone who lands on this page searching for a solution for Windows OS:
For me the issue was with DLL file of sqlite3.
Solution:

*

*I took DLL file from sqlite site. This might vary based on your
version of python installation.

*I pasted it in the DLL directory of
the env. for me it was "C:\Anaconda\Lib", but check for yours.


text:
Q: Can't figure out what's wrong with my proof I have to decide if it possible to find a set $A\subset \mathbb{R}$ such that:
$A$ is not connected nor compact but it is complete.
At first, I thought it wasn't possible, and made the following "proof":
Proof: Given that $A$ is not connected, it is possible to find $B$, $C$ subsets of $\mathbb{R}$, disjoint and open such that $A=B\cup C$. Using the "representation theorem for open sets on the real line" (math analysis, Apostol), $B$ and $C$ are both a countable union of disjoint open intervals, so $A=\bigcup_{k=1}^{\infty}(a_k,b_k)$ where one $a_j$ and $b_j$ can be $-\infty$ and $+\infty$, respectively.
So if we take one interval with a finite endpoint, say, $(a_2,b_2)$ ($a_2$ finite), we can construct a sequence converging to $a_2$, so that sequence is cauchy, but doesn't converge to a point belonging to $A$. $\blacksquare$
But a classmate could find an example: $\mathbb{Z}$. Another one: $\bigcup_{k=0}^{\infty}[2k,2k+1]$.
So, what's wrong with my proof? Any help is highly appreciated. Thanks and regards.

A: If $A$ is not connected you can find $B,C\subset A$ which are open in $\boldsymbol A$ such that $B\cap C=\emptyset$.  $B$ and $C$ do not have to be open in $\Bbb R$.

A: You need to be careful when you write $A$ as a disjoint union of sets.  We have that $A = B\cup C$ where $B$ and $C$ are open in $A$, but they don't have to be open in $\mathbb{R}$.  Consider $A = [0,1) \cup [2,3]$.
As a hint to finding a disconnected, noncompact, complete set, I would consider an interval of the form $(-\infty, a]$ for some $a \in \mathbb{R}$.  There is a way to construct a set with the desired properties from an interval of this form.


text:
Q: PHP: exchange all keys with their associated values in an array and preserving even if value has several indentical occurrences In PHP we do have function array_flip for exchanging all keys with their associated values in an array, however I am looking for a the solution as follows with the help of php functions
INPUT
array(
    "a" => 1,
    "b" => 1,
    "c" => 2
);

OUTPUT
array(
        1 => array("a", "b"),
        2 => "c"
);

A: I don't think there is a php function for it, so you'll have to write your own. If you really want a mixture of nested arrays and values the way to go would be:
function my_array_flip($arr)
{
    $new_arr = array();
    foreach ($arr as $k => $v)
    {
        if (array_key_exists($v, $new_arr))
        {
            if (is_array($new_arr[$v]))
            {
                $new_arr[] = $k;
            }
            else
            {
                $new_arr[$v] = array($new_arr[$v]);
                $new_arr[$v][] = $k;
            }
        }
        else
        {
            $new_arr[$v] = $k;
        }
    }

    return $new_arr;
}

For your array this will return:
Array
(
    [1] => Array
        (
            [0] => a
            [1] => b
        )

    [2] => c
)

A: $source = array(
    "a" => 1,
    "b" => 1,
    "c" => 2
);

foreach ($source as $key => $value)
{
    $result[$value][] = $key;
}

A: Don't think exists a function for that but you can achieve it with some code:
$input = [
    "a" => 1,
    "b" => 1,
    "c" => 2,
];

$grouped = [];
foreach ($input as $key => $group) {
    $grouped[$group][] = $key;
}

Result:
var_dump($grouped);

array(2) {
  [1] =>
  array(2) {
    [0] =>
    string(1) "a"
    [1] =>
    string(1) "b"
  }
  [2] =>
  array(1) {
    [0] =>
    string(1) "c"
  }
}

Sets always array as values because I guess this will simplify things when you'll use the result in your code.


text:
Q: Axon FW 4.6 comes with Dead Letter Queue support, but is it possible to still have rollback support in case of exception? we're looking into using the new feature of Axon, dead letter queue(DLQ).
In our previous application (axon 4.5x) we have a lot of eventhandlers updating projections. Our default is to rethrow exceptions when they occur, which will trigger a rollback for the database updates. Perhaps not the best practice to rely on this behaviour (because it can not rollback everything, eg sending an email from event can not be reverted of course)
This behaviour seems to get lost when introducing DLQ in our applications, which has big impact on our current application flow (projections are updated when they previously weren't). This makes upgrading not that easy.
Is it possible to still get the old behaviour(transaction rolled back in case of exceptions) together with DLQ processing?
What we tried was building a test application to test the new DLQ features. While playing around all looks fine in case of exceptions (they were moved to dlq) but the projections still got updated (not rolled back as before)
We throw an exception after the .save() of the projection simulating a database failure to see if events involved (we have multiple eventhandlers for an event updating projections) got rolled back.

A: You need to choose here, @davince. Storing a dead-letter in the dead-letter queue similarly requires a database transaction.
To ensure the token still progresses and the dead letter is entered, the framework uses the existing transaction.
Furthermore, in practical terms event handling was successful.
Hence, a rollback for some of the parts wouldn't be feasible.
The best way to deal with this, as is mentioned in the Reference Guide, is to make your event handlers idempotent:

Before configuring a SequencedDeadLetterQueue it is vital to validate whether your event handling functions are idempotent.
As a processing group consists of several Event Handling Components
(as explained in the intro of this chapter), some handlers may succeed
in event handling while others will not. As a configured dead-letter
queue does not stall event handling, a failure in one Event Handling
Component does not cause a rollback for other event handlers.
Furthermore, as the dead-letter support is on the processing group
level, dead-letter processing will invoke all event handlers for that
event within the processing group.
Thus, if your event handlers are not idempotent, processing letters may result in undesired side effects.
Hence, we strongly recommend making your event handlers idempotent when using the dead-letter queue.
The principle of exactly-once delivery is no longer guaranteed; at-least-once delivery is the reality to cope with.

I understand this requires some rework on your end, @davince. Although the feature is powerful, it comes with a certain level of responsibility before you use it.
I hope the above clarifies this for you.
Added, I'd like to point out that the version upgrade in itself does not require you to use the dead-letter queue. Hence, this change shouldn't impose any strains for updating to the latest release.
Update 1
Sometimes you need to think about an issue a bit longer.. I was just wondering the following things about your setup. Perhaps I can help out on that front:

*

*What storage mechanism do you use to store projections in?

*Where are you storing your tokens?

*Where are you planning to store your dead-letters?

*How are you invoking the storage layer from your event handlers?

Update 2
Thanks for sharing that you're using PostgreSQL for your projections, tokens, and dead letters. And that you're using JPA entities for storage.
It gives more certainty about your setup, as it may impact how your system would react in case of a rollback.
However, as it's rather vanilla/regular, the shared comment from the Reference Guide still applies.
This, sadly enough, means some work on your end, @davince. I hope the road forward to start using the SequencedDeadLetterQueue from Axon Framework is clear.
By the way, if you ever have recommendations on how the framework or the documentation may be improved, be sure to file issues in GitHub here and here, respectively.