Programs & Examples On #Stack dump

How do I reset the setInterval timer?

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

function myFn() {console.log('idle');}

var myTimer = setInterval(myFn, 4000);

// Then, later at some future time, 
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

You could also use a little timer object that offers a reset feature:

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new or original interval, stop current interval
    this.reset = function(newT = t) {
        t = newT;
        return this.stop().start();
    }
}

Usage:

var timer = new Timer(function() {
    // your function here
}, 5000);


// switch interval to 10 seconds
timer.reset(10000);

// stop the timer
timer.stop();

// start the timer
timer.start();

Working demo: https://jsfiddle.net/jfriend00/t17vz506/

How does one extract each folder name from a path?

I wrote the following method which works for me.

protected bool isDirectoryFound(string path, string pattern)
    {
        bool success = false;

        DirectoryInfo directories = new DirectoryInfo(@path);
        DirectoryInfo[] folderList = directories.GetDirectories();

        Regex rx = new Regex(pattern);

        foreach (DirectoryInfo di in folderList)
        {
            if (rx.IsMatch(di.Name))
            {
                success = true;
                break;
            }
        }

        return success;
    }

The lines most pertinent to your question being:

DirectoryInfo directories = new DirectoryInfo(@path); DirectoryInfo[] folderList = directories.GetDirectories();

Best way to disable button in Twitter's Bootstrap

The easiest way to do this, is to use the disabled attribute, as you had done in your original question:

<button class="btn btn-disabled" disabled>Content of Button</button>

As of now, Twitter Bootstrap doesn't have a method to disable a button's functionality without using the disabled attribute.

Nonetheless, this would be an excellent feature for them to implement into their javascript library.

How to secure an ASP.NET Web API

in continuation to @ Cuong Le's answer , my approach to prevent replay attack would be

// Encrypt the Unix Time at Client side using the shared private key(or user's password)

// Send it as part of request header to server(WEB API)

// Decrypt the Unix Time at Server(WEB API) using the shared private key(or user's password)

// Check the time difference between the Client's Unix Time and Server's Unix Time, should not be greater than x sec

// if User ID/Hash Password are correct and the decrypted UnixTime is within x sec of server time then it is a valid request

How to install Guest addition in Mac OS as guest and Windows machine as host

Guest additions are not available for Mac OS X. You can get features like clipboard sync and shared folders by using VNC and SMB. Here's my answer on a similar question.

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

How can I install a CPAN module into a local directory?

Other answers already on Stackoverflow:

From perlfaq8:


How do I keep my own module/library directory?

When you build modules, tell Perl where to install the modules.

For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:

perl Makefile.PL INSTALL_BASE=/mydir/perl

You can set this in your CPAN.pm configuration so modules automatically install in your private library directory when you use the CPAN.pm shell:

% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit

For Build.PL-based distributions, use the --install_base option:

perl Build.PL --install_base /mydir/perl

You can configure CPAN.pm to automatically use this option too:

% cpan
cpan> o conf mbuildpl_arg '--install_base /mydir/perl'
cpan> o conf commit

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Can media queries resize based on a div element instead of the screen?

After nearly a decade of work — with proposals, proofs-of-concept, discussions and other contributions by the broader web developer community — the CSS Working Group has finally laid some of the groundwork needed for container queries to be written into a future edition of the CSS Containment spec! For more details on how such a feature might work and be used, check out Miriam Suzanne's extensive explainer.

Hopefully it won't be much longer before we see a robust cross-browser implementation of such a system. It's been a grueling wait, but I'm glad that it's no longer something we simply have to accept as an insurmountable limitation of CSS due to cyclic dependencies or infinite loops or what have you (these are still a potential issue in some aspects of the proposed design, but I have faith that the CSSWG will find a way).


Media queries aren't designed to work based on elements in a page. They are designed to work based on devices or media types (hence why they are called media queries). width, height, and other dimension-based media features all refer to the dimensions of either the viewport or the device's screen in screen-based media. They cannot be used to refer to a certain element on a page.

If you need to apply styles depending on the size of a certain div element on your page, you'll have to use JavaScript to observe changes in the size of that div element instead of media queries.

Alternatively, with more modern layout techniques introduced since the original publication of this answer such as flexbox and standards such as custom properties, you may not need media or element queries after all. Djave provides an example.

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

How do I detect unsigned integer multiply overflow?

#include <stdio.h>
#include <stdlib.h>

#define MAX 100 

int mltovf(int a, int b)
{
    if (a && b) return abs(a) > MAX/abs(b);
    else return 0;
}

main()
{
    int a, b;

    for (a = 0; a <= MAX; a++)
        for (b = 0; b < MAX; b++) {

        if (mltovf(a, b) != (a*b > MAX)) 
            printf("Bad calculation: a: %d b: %d\n", a, b);

    }
}

How to add multiple classes to a ReactJS Component?

It can be done with https://www.npmjs.com/package/clsx :

https://www.npmjs.com/package/clsx

First install it:

npm install --save clsx

Then import it in your component file:

import clsx from  'clsx';

Then use the imported function in your component:

<div className={ clsx(classes.class1, classes.class2)}>

Trigger to fire only if a condition is met in SQL Server

Using LIKE will give you options for defining what the rest of the string should look like, but if the rule is just starts with 'NoHist_' it doesn't really matter.

Checking if a variable is not nil and not zero in ruby

I prefer using a more cleaner approach :

val.to_i.zero?

val.to_i will return a 0 if val is a nil,

after that, all we need to do is check whether the final value is a zero.

Adding values to a C# array

Just a different approach:

int runs = 0; 
bool batting = true; 
string scorecard;

while (batting = runs < 400)
    scorecard += "!" + runs++;

return scorecard.Split("!");

How do I count columns of a table

I think you want to know the total entries count in a table! For that use this code..

SELECT count( * ) as Total_Entries FROM tbl_ifo;

Git push requires username and password

If you have cloned HTTPS instead of SSH and facing issue with username and password prompt on pull, push and fetch. You can solve this problem simply for UBUNTU

Step 1: move to root directory

cd ~/

create a file .git-credentials

Add this content to that file with you usename password and githosting URL

https://user:[email protected]

Then execute the command

git config --global credential.helper store

Now you will be able to pull push and fetch all details from your repo without any hassle.

Finding the average of a list

A statistics module has been added to python 3.4. It has a function to calculate the average called mean. An example with the list you provided would be:

from statistics import mean
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
mean(l)

pandas: best way to select all columns whose names start with X

My solution. It may be slower on performance:

a = pd.concat(df[df[c] == 1] for c in df.columns if c.startswith('foo'))
a.sort_index()


   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      5.0     1.0         0             0        2         NA      NA
1      5.0     2.1         0             1        4          0       0
2      6.0     NaN         0           NaN        1          0       1
5      6.8     6.8         1             0        5          0       0

Updating a JSON object using Javascript

$(document).ready(function(){        
    var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
               {'Id':'2','Username':'Steve','FatherName':'Johnson'},
               {'Id':'3','Username':'Albert','FatherName':'Einstein'}];

    $.each(jsonObj,function(i,v){       
      if (v.Id == 3) {
        v.Username = "Thomas";
        return false;
      }
    });

alert("New Username: " + jsonObj[2].Username);

});

Get index of a key in json

Its too late, but it may be simple and useful

var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };
var keytoFind = "key2";
var index = Object.keys(json).indexOf(keytoFind);
alert(index);

Practical uses for AtomicInteger

If you look at the methods AtomicInteger has, you'll notice that they tend to correspond to common operations on ints. For instance:

static AtomicInteger i;

// Later, in a thread
int current = i.incrementAndGet();

is the thread-safe version of this:

static int i;

// Later, in a thread
int current = ++i;

The methods map like this:
++i is i.incrementAndGet()
i++ is i.getAndIncrement()
--i is i.decrementAndGet()
i-- is i.getAndDecrement()
i = x is i.set(x)
x = i is x = i.get()

There are other convenience methods as well, like compareAndSet or addAndGet

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

hibernate: LazyInitializationException: could not initialize proxy

See my article. I had the same problem - LazyInitializationException - and here's the answer I finally came up with:
http://community.jboss.org/wiki/LazyInitializationExceptionovercome
Setting lazy=false is not the answer - it can load everything all at once, and that's not necessarily good. Example:
1 record table A references:
5 records table B references:
25 records table C references:
125 records table D
...
etc. This is but one example of what can go wrong.
--Tim Sabin

getting the difference between date in days in java

Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }

Fastest way to remove first char in a String

I would just use

string data= "/temp string";
data = data.substring(1)

Output: temp string

That always works for me.

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

Internet Access in Ubuntu on VirtualBox

it could be a problem with your specific network adapter. I have a Dell 15R and there are no working drivers for ubuntu or ubuntu server; I even tried compiling wireless drivers myself, but to no avail.

However, in virtualbox, I was able to get wireless working by using the default configuration. It automatically bridged my internal wireless adapter and hence used my native OS's wireless connection for wireless.

If you are trying to get a separate wireless connection from within ubuntu in virtualbox, then it would take more configuring. If so, let me know, if not, I will not bother typing up instructions to something you are not looking to do, as it is quite complicated in some instances.

p.s. you should be using Windows 7 if you have any technical inclination. Do you live under a rock? No offense intended.

Making an asynchronous task in Flask

You can also try using multiprocessing.Process with daemon=True; the process.start() method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.

I experienced similar problem while working with falcon framework and using daemon process helped.

You'd need to do the following:

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
        target=my_func,
        daemon=True
    )
    heavy_process.start()
    return Response(
        mimetype='application/json',
        status=200
    )

# Define some heavy function
def my_func():
    time.sleep(10)
    print("Process finished")

You should get a response immediately and, after 10s you should see a printed message in the console.

NOTE: Keep in mind that daemonic processes are not allowed to spawn any child processes.

Count elements with jQuery

$('.class').length

This one does not work for me. I'd rather use this:

$('.class').children().length

I don't really know the reason why, but the second one works only for me. Somewhy, either size doesn't work.

WPF User Control Parent

This approach worked for me but it is not as specific as your question:

App.Current.MainWindow

How to render a PDF file in Android

I have made a hybrid approach from some of the answers given to this and other similar posts:

This solution checks if a PDF reader app is installed and does the following: - If a reader is installed, download the PDF file to the device and start a PDF reader app - If no reader is installed, ask the user if he wants to view the PDF file online through Google Drive

NOTE! This solution uses the Android DownloadManager class, which was introduced in API9 (Android 2.3 or Gingerbread). This means that it doesn't work on Android 2.2 or earlier.

I wrote a blog post about it here, but I've provided the full code below for completeness:

public class PDFTools {
    private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
    private static final String PDF_MIME_TYPE = "application/pdf";
    private static final String HTML_MIME_TYPE = "text/html";

    /**
     * If a PDF reader is installed, download the PDF file and open it in a reader. 
     * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.<br />
     * <br />
     * <b>BEWARE:</b> This method
     * @param context
     * @param pdfUrl
     * @return
     */
    public static void showPDFUrl( final Context context, final String pdfUrl ) {
        if ( isPDFSupported( context ) ) {
            downloadAndOpenPDF(context, pdfUrl);
        } else {
            askToOpenPDFThroughGoogleDrive( context, pdfUrl );
        }
    }

    /**
     * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
     * @param context
     * @param pdfUrl
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile( tempFile ) );
            return;
        }

        // Show progress dialog while downloading
        final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ( !progress.isShowing() ) {
                    return;
                }
                context.unregisterReceiver( this );

                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                        openPDF( context, Uri.fromFile( tempFile ) );
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue( r );
    }

    /**
     * Show a dialog asking the user if he wants to open the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
        new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl); 
                }
            })
            .show();
    }

    /**
     * Launches a browser to view the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Open a local PDF file with an installed reader
     * @param context
     * @param localUri
     */
    public static final void openPDF(Context context, Uri localUri ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType( localUri, PDF_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Checks if any apps are installed that supports reading of PDF files.
     * @param context
     * @return
     */
    public static boolean isPDFSupported( Context context ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
        i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
        return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
    }

}

Download File Using jQuery

  • Using jQuery function

        var valFileDownloadPath = 'http//:'+'your url';
    
       window.open(valFileDownloadPath , '_blank');
    

including parameters in OPENQUERY

You can execute a string with OPENQUERY once you build it up. If you go this route think about security and take care not to concatenate user-entered text into your SQL!

DECLARE @Sql VARCHAR(8000)
SET @Sql = 'SELECT * FROM Tbl WHERE Field1 < ''someVal'' AND Field2 IN '+ @valueList 
SET @Sql = 'SELECT * FROM OPENQUERY(SVRNAME, ''' + REPLACE(@Sql, '''', '''''') + ''')'
EXEC(@Sql)

Can't resolve module (not found) in React.js

You need to be in project folder, if you are in src or public you have to come out of those folders. Suppose your react-project name is 'hello-react' then cd hello-react

Width equal to content

just use display: table; on your case.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
    System.out.println(g); // Print out the gun
    if (i == 2) { // If you're at the third gun
        ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
        for (Bullet b : bullets) { // Then print every bullet
            System.out.println(b);
        }
    i++; // Don't forget to increment your counter so you know you're at the next gun
}

C#: Converting byte array to string and printing out to console

It's actually:

    Console.WriteLine(Encoding.Default.GetString(value));

or for UTF-8 specifically:

    Console.WriteLine(Encoding.UTF8.GetString(value));

How to add "active" class to Html.ActionLink in ASP.NET MVC

You can try this: In my case i am loading menu from database based on role based access, Write the code on your every view which menu your want to active based on your view.

<script type="text/javascript">
        $(document).ready(function () {         
            $('li.active active-menu').removeClass('active active-menu');
            $('a[href="/MgtCustomer/Index"]').closest('li').addClass('active active-menu');
        });
</script>

Connect with SSH through a proxy

Try -o "ProxyCommand=nc --proxy HOST:PORT %h %p" for command in question. It worked on OEL6 but need to modify as mentioned for OEL7.

What is the purpose of "&&" in a shell command?

Furthermore, you also have || which is the logical or, and also ; which is just a separator which doesn't care what happend to the command before.

$ false || echo "Oops, fail"
Oops, fail

$ true || echo "Will not be printed"
$  

$ true && echo "Things went well"
Things went well

$ false && echo "Will not be printed"
$

$ false ; echo "This will always run"
This will always run

Some details about this can be found here Lists of Commands in the Bash Manual.

How to merge a list of lists with same type of items to a single list of items?

Do you mean this?

var listOfList = new List<List<int>>() {
    new List<int>() { 1, 2 },
    new List<int>() { 3, 4 },
    new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));

foreach (var x in result) Console.WriteLine(x);

Results in: 9 9 9 1 2 3 4 5 6

How to find elements with 'value=x'?

If the value is hardcoded in the source of the page using the value attribute then you can

$('#attached_docs :input[value="123"]').remove();

If you want to target elements that have a value of 123, which was set by the user or programmatically then use EDIT works both ways ..

or

$('#attached_docs :input').filter(function(){return this.value=='123'}).remove();

demo http://jsfiddle.net/gaby/RcwXh/2/

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

BackgroundTint works as color filter.

FEFBDE as tint

37AEE4 as background

Try seeing the difference by comment tint/background and check the output when both are set.

How to add DOM element script to head section?

var script = $('<script type="text/javascript">// function </script>')
document.getElementsByTagName("head")[0].appendChild(script[0])

But in that case script will not be executed and functions will be not accessible in global namespase. To use code in <script> you need do as in you question

$('head').append(script);

Plotting lines connecting points

I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')

Have a long list of x's and y's, and want to connect adjacent pairs?

xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')

Plot of two pairs of points, each connected by a separate line

The entity cannot be constructed in a LINQ to Entities query

If you are using Entity framework, then try removing property from DbContext which uses your complex model as Entity I had same problem when mapping multiple model into a viewmodel named Entity

public DbSet<Entity> Entities { get; set; }

Removing the entry from DbContext fixed my error.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

I found a workaround to download latest version of ChromeDriver via WebDriverManager You could try something like,

WebDriver driver = null ;
boolean oldVersion = true;
String chromeVersion = "";
try {
    try{
        FileReader reader = new FileReader("chromeVersion.txt") ;
        BufferedReader br = new BufferedReader(reader) ;
        
        String line;
        
        while ((line = br.readLine()) != null){
            chromeVersion = line.trim();
        }
        reader.close();
    } catch (IOException e ) {}
    
    WebDriverManager.chromedriver().version(chromeVersion).setup();
    driver = new ChromeDriver() ;
} catch (Exception e) {
    oldVersion = false;
    String err = e.getMessage() ;
    chromeVersion = err.split("version is")[1].split("with binary path")[0].trim();
    try{
        FileWriter writer = new FileWriter("chromeVersion.txt", true) ;
        writer.write(chromeVersion) ;
        writer.close();
    } catch (IOException er ) {}
}

if (!oldVersion){
    WebDriverManager.chromedriver().version(chromeVersion).setup();
    driver = new ChromeDriver() ;
}

driver.get("https://www.google.com") ;

Compiler error: memset was not declared in this scope

Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.

$ man memset

MEMSET(3)                BSD Library Functions Manual                MEMSET(3)

NAME
     memset -- fill a byte string with a byte value

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <string.h>

     void *
     memset(void *b, int c, size_t len);

Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>/<cstdio>/<cstdlib>/etc, rather than C's <string.h>/<stdio.h>/<stdlib.h>/etc.

Reloading a ViewController

If you know your database has been updated and you want to just refresh your ViewController (which was my case). I didn't find another solution but what I did was when my database updated, I called:

[self viewDidLoad];

again, and it worked. Remember if you override other viewWillAppear or loadView then call them too in same order. like.

[self viewDidLoad]; [self viewWillAppear:YES];

I think there should be a more specific solution like refresh button in browser.

How to get the employees with their managers

This is a classic self-join, try the following:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
    emp e, emp m
WHERE e.mgr = m.empno

And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
    emp e, emp m
WHERE e.mgr = m.empno(+)

Or in ANSI SQL syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
    emp e
    LEFT OUTER JOIN emp m
        ON e.mgr = m.empno

ios app maximum memory budget

You should watch session 147 from the WWDC 2010 Session videos. It is "Advanced Performance Optimization on iPhone OS, part 2".
There is a lot of good advice on memory optimizations.

Some of the tips are:

  • Use nested NSAutoReleasePools to make sure your memory usage does not spike.
  • Use CGImageSource when creating thumbnails from large images.
  • Respond to low memory warnings.

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

Selecting/excluding sets of columns in pandas

You just need to convert your set to a list

import pandas as pd
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
my_cols = set(df.columns)
my_cols.remove('B')
my_cols.remove('D')
my_cols = list(my_cols)
df2 = df[my_cols]

How to concatenate multiple column values into a single column in Panda dataframe

If you have even more columns you want to combine, using the Series method str.cat might be handy:

df["combined"] = df["foo"].str.cat(df[["bar", "new"]].astype(str), sep="_")

Basically, you select the first column (if it is not already of type str, you need to append .astype(str)), to which you append the other columns (separated by an optional separator character).

What is the difference between JSF, Servlet and JSP?

JSPs are the View component of MVC (Model View Controller). The Controller takes the incoming request and passes it to the Model, which might be a bean that does some database access. The JSP then formats the output using HTML, CSS and JavaScript, and the output then gets sent back to the requester.

How to download Visual Studio 2017 Community Edition for offline installation?

All I wanted were 1) English only and 2) just enough to build a legacy desktop project written in C. No Azure, no mobile development, no .NET, and no other components that I don't know what to do with.

[Note: Options are in multiple lines for readability, but they should be in 1 line]
vs_community__xxxxxxxxxx.xxxxxxxxxx.exe
    --lang en-US
    --layout ".\Visual Studio Cummunity 2017"
    --add Microsoft.VisualStudio.Workload.NativeDesktop 
    --includeRecommended

I chose "NativeDesktop" from "workload and component ID" site (https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community).

The result was about 1.6GB downloaded files and 5GB when installed. I'm sure I could have removed a few unnecessary components to save space, but the list was rather long, so I stopped there.

"--includeRecommended" was the key ingredient for me, which included Windows SDK along with other essential things for building the legacy project.

What is the purpose of the "final" keyword in C++11 for functions?

Supplement to Mario Knezovic 's answer:

class IA
{
public:
  virtual int getNum() const = 0;
};

class BaseA : public IA
{
public:
 inline virtual int getNum() const final {return ...};
};

class ImplA : public BaseA {...};

IA* pa = ...;
...
ImplA* impla = static_cast<ImplA*>(pa);

//the following line should cause compiler to use the inlined function BaseA::getNum(), 
//instead of dynamic binding (via vtable or something).
//any class/subclass of BaseA will benefit from it

int n = impla->getNum();

The above code shows the theory, but not actually tested on real compilers. Much appreciated if anyone paste a disassembled output.

JavaScript function in href vs. onclick

In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.

In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer cursor) since it is treating the <a> as an anchor, and not a link.

In terms of behavior, when specifying an action by navigation via href, the browser will typically support opening that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.


However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
    $('a#link').click(function(){ /* ... action ... */ })
</script>

How to add header row to a pandas DataFrame

To fix your code you can simply change [Cov] to Cov.values, the first parameter of pd.DataFrame will become a multi-dimensional numpy array:

Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')

But the smartest solution still is use pd.read_excel with header=None and names=columns_list.

How to refer environment variable in POM.xml?

Also, make sure that your environment variable is composed only by UPPER CASE LETTERS.... I don't know why (the documentation doesn't say nothing explicit about it, at least the link provided by @Andrew White), but if the variable is a lower case word (e.g. env.dummy), the variable always came empty or null...

i was struggling with this like an hour, until I decided to try an UPPER CASE VARIABLE, and problem solved.

OK Variables Examples:

  • DUMMY
  • DUMMY_ONE
  • JBOSS_SERVER_PATH

(NOTE: I was using maven v3.0.5)

I Hope that this can help someone....

Subset of rows containing NA (missing) values in a chosen column of a data frame

new_data <- data %>% filter_all(any_vars(is.na(.))) 

This should create a new data frame (new_data) with only the missing values in it.

Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).

How to convert a 3D point into 2D perspective projection?

You can project 3D point in 2D using: Commons Math: The Apache Commons Mathematics Library with just two classes.

Example for Java Swing.

import org.apache.commons.math3.geometry.euclidean.threed.Plane;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;


Plane planeX = new Plane(new Vector3D(1, 0, 0));
Plane planeY = new Plane(new Vector3D(0, 1, 0)); // Must be orthogonal plane of planeX

void drawPoint(Graphics2D g2, Vector3D v) {
    g2.drawLine(0, 0,
            (int) (world.unit * planeX.getOffset(v)),
            (int) (world.unit * planeY.getOffset(v)));
}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    drawPoint(g2, new Vector3D(2, 1, 0));
    drawPoint(g2, new Vector3D(0, 2, 0));
    drawPoint(g2, new Vector3D(0, 0, 2));
    drawPoint(g2, new Vector3D(1, 1, 1));
}

Now you only needs update the planeX and planeY to change the perspective-projection, to get things like this:

enter image description hereenter image description here

How to convert a char to a String?

Use any of the following:

String str = String.valueOf('c');
String str = Character.toString('c');
String str = 'c' + "";

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

I was parsing JSON from a REST API call and got this error. It turns out the API had become "fussier" (eg about order of parameters etc) and so was returning malformed results. Check that you are getting what you expect :)

How to get directory size in PHP

Johnathan Sampson's Linux example didn't work so good for me. Here's an improved version:

function getDirSize($path)
{
    $io = popen('/usr/bin/du -sb '.$path, 'r');
    $size = intval(fgets($io,80));
    pclose($io);
    return $size;
}

How to remove element from array in forEach loop?

I understood that you want to remove from the array using a condition and have another array that has items removed from the array. Is right?

How about this?

_x000D_
_x000D_
var review = ['a', 'b', 'c', 'ab', 'bc'];_x000D_
var filtered = [];_x000D_
for(var i=0; i < review.length;) {_x000D_
  if(review[i].charAt(0) == 'a') {_x000D_
    filtered.push(review.splice(i,1)[0]);_x000D_
  }else{_x000D_
    i++;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);
_x000D_
_x000D_
_x000D_

Hope this help...

By the way, I compared 'for-loop' to 'forEach'.

If remove in case a string contains 'f', a result is different.

_x000D_
_x000D_
var review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
var filtered = [];_x000D_
for(var i=0; i < review.length;) {_x000D_
  if( review[i].includes('f')) {_x000D_
    filtered.push(review.splice(i,1)[0]);_x000D_
  }else {_x000D_
    i++;_x000D_
  }_x000D_
}_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);_x000D_
/**_x000D_
 * review [  "concat",  "copyWithin",  "entries",  "every",  "includes",  "join",  "keys",  "map",  "pop",  "push",  "reduce",  "reduceRight",  "reverse",  "slice",  "some",  "sort",  "splice",  "toLocaleString",  "toSource",  "toString",  "values"] _x000D_
 */_x000D_
_x000D_
console.log("========================================================");_x000D_
review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
filtered = [];_x000D_
_x000D_
review.forEach(function(item,i, object) {_x000D_
  if( item.includes('f')) {_x000D_
    filtered.push(object.splice(i,1)[0]);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log("-----------------------------------------");_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);_x000D_
_x000D_
/**_x000D_
 * review [  "concat",  "copyWithin",  "entries",  "every",  "filter",  "findIndex",  "flatten",  "includes",  "join",  "keys",  "map",  "pop",  "push",  "reduce",  "reduceRight",  "reverse",  "slice",  "some",  "sort",  "splice",  "toLocaleString",  "toSource",  "toString",  "values"]_x000D_
 */
_x000D_
_x000D_
_x000D_

And remove by each iteration, also a result is different.

_x000D_
_x000D_
var review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
var filtered = [];_x000D_
for(var i=0; i < review.length;) {_x000D_
  filtered.push(review.splice(i,1)[0]);_x000D_
}_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);_x000D_
console.log("========================================================");_x000D_
review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];_x000D_
filtered = [];_x000D_
_x000D_
review.forEach(function(item,i, object) {_x000D_
  filtered.push(object.splice(i,1)[0]);_x000D_
});_x000D_
_x000D_
console.log("-----------------------------------------");_x000D_
console.log("review", review);_x000D_
console.log("filtered", filtered);
_x000D_
_x000D_
_x000D_

Google Apps Script to open a URL

You can build a small UI that does the job like this :

function test(){
showURL("http://www.google.com")
}
//
function showURL(href){
  var app = UiApp.createApplication().setHeight(50).setWidth(200);
  app.setTitle("Show URL");
  var link = app.createAnchor('open ', href).setId("link");
  app.add(link);  
  var doc = SpreadsheetApp.getActive();
  doc.show(app);
  }

If you want to 'show' the URL, just change this line like this :

  var link = app.createAnchor(href, href).setId("link");

EDIT : link to a demo spreadsheet in read only because too many people keep writing unwanted things on it (just make a copy to use instead).

EDIT : UiApp was deprecated by Google on 11th Dec 2014, this method could break at any time and needs updating to use HTML service instead!

EDIT : below is an implementation using html service.

function testNew(){
  showAnchor('Stackoverflow','http://stackoverflow.com/questions/tagged/google-apps-script');
}

function showAnchor(name,url) {
  var html = '<html><body><a href="'+url+'" target="blank" onclick="google.script.host.close()">'+name+'</a></body></html>';
  var ui = HtmlService.createHtmlOutput(html)
  SpreadsheetApp.getUi().showModelessDialog(ui,"demo");
}

Disable vertical sync for glxgears

The vblank_mode environment variable does the trick. You should then get several hundreds FPS on modern hardware. And you are now able to compare the results with others.

$>   vblank_mode=0 glxgears

Android: ScrollView force to bottom

One thing to consider is what NOT to set. Make certain your child controls, especially EditText controls, do not have the RequestFocus property set. This may be one of the last interpreted properties on the layout and it will override gravity settings on its parents (the layout or ScrollView).

How to change the current URL in javascript?

This is more robust:

mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');

When the URL has multiple numbers, it will change the last one:

http://mywebsite.com/8815/1.html

It supports numbers with leading zeros:

http://mywebsite.com/0001.html

Example

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

Google Maps API: open url by clicking on marker

If anyone wants to add an URL on a single marker which not require for loops, here is how it goes:

if ($('#googleMap').length) {
    var initialize = function() {
        var mapOptions = {
            zoom: 15,
            scrollwheel: false,
            center: new google.maps.LatLng(45.725788, -73.5120818),
            styles: [{
                stylers: [{
                    saturation: -100
                }]
            }]
        };
        var map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);
        var marker = new google.maps.Marker({
            position: map.getCenter(),
            animation: google.maps.Animation.BOUNCE,
            icon: 'example-marker.png',
            map: map,
            url: 'https://example.com'
        });

        //Add an url to the marker
    google.maps.event.addListener(marker, 'click', function() {
        window.location.href = this.url;
    });
    }
    // Add the map initialize function to the window load function
    google.maps.event.addDomListener(window, "load", initialize);
}

How to delete a localStorage item when the browser window/tab is closed?

I don't think the solution presented here is 100% correct because window.onbeforeunload event is called not only when browser/Tab is closed(WHICH IS REQUIRED), but also on all other several events. (WHICH MIGHT NOT BE REQUIRED)

See this link for more information on list of events that can fire window.onbeforeunload:-

http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

Android scale animation on view

Add this code on values anim

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <scale
        android:duration="@android:integer/config_longAnimTime"
        android:fromXScale="0.2"
        android:fromYScale="0.2"
        android:toXScale="1.0"
        android:toYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"/>
    <alpha
        android:fromAlpha="0.1"
        android:toAlpha="1.0"
        android:duration="@android:integer/config_longAnimTime"
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>
</set>

call on styles.xml

<style name="DialogScale">
    <item name="android:windowEnterAnimation">@anim/scale_in</item>
    <item name="android:windowExitAnimation">@anim/scale_out</item>
</style>

In Java code: set Onclick

public void onClick(View v) {
            fab_onclick(R.style.DialogScale, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
          //  Dialogs.fab_onclick(R.style.DialogScale, "Scale");

        }

setup on method:

alertDialog.getWindow().getAttributes().windowAnimations = type;

Download a file by jQuery.Ajax

Here is what I did, pure javascript and html. Did not test it but this should work in all browsers.

Javascript Function

var iframe = document.createElement('iframe');
iframe.id = "IFRAMEID";
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src = 'SERVERURL'+'?' + $.param($scope.filtro);
iframe.addEventListener("load", function () {
     console.log("FILE LOAD DONE.. Download should start now");
});

Using just components that is supported in all browsers no additional libraries.

enter image description here enter image description here

Here is my server side JAVA Spring controller code.

@RequestMapping(value = "/rootto/my/xlsx", method = RequestMethod.GET)
public void downloadExcelFile(@RequestParam(value = "param1", required = false) String param1,
    HttpServletRequest request, HttpServletResponse response)
            throws ParseException {

    Workbook wb = service.getWorkbook(param1);
    if (wb != null) {
        try {
            String fileName = "myfile_" + sdf.format(new Date());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + ".xlsx\"");
            wb.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }

How to remove specific elements in a numpy array

To delete by value :

modified_array = np.delete(original_array, np.where(original_array == value_to_delete))

Accessing constructor of an anonymous class

It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.

Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.

How to enable Google Play App Signing

While Migrating Android application package file (APK) to Android App Bundle (AAB), publishing app into Play Store i faced this issue and got resolved like this below...

When building .aab file you get prompted for the location to store key export path as below:

enter image description here
enter image description here In second image you find Encrypted key export path Location where our .pepk will store in the specific folder while generating .aab file.

Once you log in to the Google Play Console with play store credential: select your project from left side choose App Signing option Release Management>>App Signing enter image description here

you will find the Google App Signing Certification window ACCEPT it.

After that you will find three radio button select **

Upload a key exported from Android Studio radio button

**, it will expand you APP SIGNING PRIVATE KEY button as below

enter image description here

click on the button and choose the .pepk file (We Stored while generating .aab file as above)

Read the all other option and submit.

Once Successfully you can go back to app release and browse the .aab file and complete RollOut...

@Ambilpura

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

If you need a recursive search, you have a variety of options. You should consider ack.

Failing that, if you have GNU find and xargs:

find . -name '*.cc' -print0 -o -name '*.h' -print0 | xargs -0 grep hello /dev/null

The use of /dev/null ensures you get file names printed; the -print0 and -0 deals with file names containing spaces (newlines, etc).

If you don't have obstreperous names (with spaces etc), you can use:

find . -name '*.*[ch]' -print | xargs grep hello /dev/null

This might pick up a few names you didn't intend, because the pattern match is fuzzier (but simpler), but otherwise works. And it works with non-GNU versions of find and xargs.

CSS3 Transition not working

If you have a <script> tag anywhere on your page (even in the HTML, even if it is an empty tag with a src), then a transition must be activated by some event (it won't fire automatically when the page loads).

toBe(true) vs toBeTruthy() vs toBeTrue()

In javascript there are trues and truthys. When something is true it is obviously true or false. When something is truthy it may or may not be a boolean, but the "cast" value of is a boolean.

Examples.

true == true; // (true) true
1 == true; // (true) truthy
"hello" == true;  // (true) truthy
[1, 2, 3] == true; // (true) truthy
[] == false; // (true) truthy
false == false; // (true) true
0 == false; // (true) truthy
"" == false; // (true) truthy
undefined == false; // (true) truthy
null == false; // (true) truthy

This can make things simpler if you want to check if a string is set or an array has any values.

var users = [];

if(users) {
  // this array is populated. do something with the array
}

var name = "";

if(!name) {
  // you forgot to enter your name!
}

And as stated. expect(something).toBe(true) and expect(something).toBeTrue() is the same. But expect(something).toBeTruthy() is not the same as either of those.

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

Why can't I have abstract static methods in C#?

This question is 12 years old but it still needs to be given a better answer. As few noted in the comments and contrarily to what all answers pretend it would certainly make sense to have static abstract methods in C#. As philosopher Daniel Dennett put it, a failure of imagination is not an insight into necessity. There is a common mistake in not realizing that C# is not only an OOP language. A pure OOP perspective on a given concept leads to a restricted and in the current case misguided examination. Polymorphism is not only about subtying polymorphism: it also includes parametric polymorphism (aka generic programming) and C# has been supporting this for a long time now. Within this additional paradigm, abstract classes (and most types) are not only used to type instances. They can also be used as bounds for generic parameters; something that has been understood by users of certain languages (like for example Haskell, but also more recently Scala, Rust or Swift) for years.

In this context you may want to do something like this:

void Catch<TAnimal>() where TAnimal : Animal
{
    string scientificName = TAnimal.ScientificName; // abstract static property
    Console.WriteLine($"Let's catch some {scientificName}");
    …
}

And here the capacity to express static members that can be specialized by subclasses totally makes sense!

Unfortunately C# does not allow abstract static members but I'd like to propose a pattern that can emulate them reasonably well. This pattern is not perfect (it imposes some restrictions on inheritance) but as far as I can tell it is typesafe.

The main idea is to associate an abstract companion class (here SpeciesFor<TAnimal>) to the one that should contain abstract members (here Animal):

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal
{
    public static SpeciesFor<TAnimal> Instance { get { … } }

    // abstract "static" members

    public abstract string ScientificName { get; }
    
    …
}

public abstract class Animal { … }

Now we would like to make this work:

void Catch<TAnimal>() where TAnimal : Animal
{
    string scientificName = SpeciesFor<TAnimal>.Instance.ScientificName;
    Console.WriteLine($"Let's catch some {scientificName}");
    …
}

Of course we have two problems to solve:

  1. How do we allow and force an implementer of a subclass of Animal to associate a specific instance of SpeciesFor<TAnimal> to this subclass?
  2. How does the property SpeciesFor<TAnimal>.Instance retrieve this information?

Here is how we can solve 1:

public abstract class Animal<TSelf> where TSelf : Animal<TSelf>
{
    private Animal(…) {}
    
    public abstract class OfSpecies<TSpecies> : Animal<TSelf>
        where TSpecies : SpeciesFor<TSelf>, new()
    {
        protected OfSpecies(…) : base(…) { }
    }
    
    …
}

By making the constructor of Animal<TSelf> private we make sure that all its subclasses are also subclasses of inner class Animal<TSelf>.OfSpecies<TSpecies>. So these subclasses must specify a TSpecies type that has a new() bound.

For 2 we can provide the following implementation:

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal<TAnimal>
{
    private static SpeciesFor<TAnimal> _instance;

    public static SpeciesFor<TAnimal> Instance => _instance ??= MakeInstance();

    private static SpeciesFor<TAnimal> MakeInstance()
    {
        Type t = typeof(TAnimal);
        while (true)
        {
            if (t.IsConstructedGenericType
                    && t.GetGenericTypeDefinition() == typeof(Animal<>.OfSpecies<>))
                return (SpeciesFor<TAnimal>)Activator.CreateInstance(t.GenericTypeArguments[1]);
            t = t.BaseType;
            if (t == null)
                throw new InvalidProgramException();
        }
    }

    // abstract "static" members

    public abstract string ScientificName { get; }
    
    …
}

How can we be sure that the reflection code inside MakeInstance() never throws? As we've already said, almost all classes within the hierarchy of Animal<TSelf> are also subclasses of Animal<TSelf>.OfSpecies<TSpecies>. So we know that for these classes a specific TSpecies must be provided. This type is also necessarily constructible thanks to constraint : new(). But this still leaves abstract types like Animal<Something> that have no associated species. Now we can convince ourself that the curiously recurring template pattern where TAnimal : Animal<TAnimal> makes it impossible to write SpeciesFor<Animal<Something>>.Instance as type Animal<Something> is never a subtype of Animal<Animal<Something>>.

Et voilà:

public class CatSpecies : SpeciesFor<Cat>
{
    // overriden "static" members

    public override string ScientificName => "Felis catus";
    public override Cat CreateInVivoFromDnaTrappedInAmber() { … }
    public override Cat Clone(Cat a) { … }
    public override Cat Breed(Cat a1, Cat a2) { … }
}

public class Cat : Animal<Cat>.OfSpecies<CatSpecies>
{
    // overriden members

    public override string CuteName { get { … } }
}

public class DogSpecies : SpeciesFor<Dog>
{
    // overriden "static" members

    public override string ScientificName => "Canis lupus familiaris";
    public override Dog CreateInVivoFromDnaTrappedInAmber() { … }
    public override Dog Clone(Dog a) { … }
    public override Dog Breed(Dog a1, Dog a2) { … }
}

public class Dog : Animal<Dog>.OfSpecies<DogSpecies>
{
    // overriden members

    public override string CuteName { get { … } }
}

public class Program
{
    public static void Main()
    {
        ConductCrazyScientificExperimentsWith<Cat>();
        ConductCrazyScientificExperimentsWith<Dog>();
        ConductCrazyScientificExperimentsWith<Tyranosaurus>();
        ConductCrazyScientificExperimentsWith<Wyvern>();
    }
    
    public static void ConductCrazyScientificExperimentsWith<TAnimal>()
        where TAnimal : Animal<TAnimal>
    {
        // Look Ma! No animal instance polymorphism!
        
        TAnimal a2039 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a2988 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a0400 = SpeciesFor<TAnimal>.Instance.Clone(a2988);
        TAnimal a9477 = SpeciesFor<TAnimal>.Instance.Breed(a0400, a2039);
        TAnimal a9404 = SpeciesFor<TAnimal>.Instance.Breed(a2988, a9477);
        
        Console.WriteLine(
            "The confederation of mad scientists is happy to announce the birth " +
            $"of {a9404.CuteName}, our new {SpeciesFor<TAnimal>.Instance.ScientificName}.");
    }
}

A limitation of this pattern is that it is not possible (as far as I can tell) to extend the class hierarchy in a satifying manner. For example we cannot introduce an intermediary Mammal class associated to a MammalClass companion. Another is that it does not work for static members in interfaces which would be more flexible than abstract classes.

how to convert a string to date in mysql?

STR_TO_DATE('12/31/2011', '%m/%d/%Y')

Resolving a Git conflict with binary files

I use Git Workflow for Excel - https://www.xltrail.com/blog/git-workflow-for-excel application to resolve most of my binary files related merge issues. This open-source app helps me to resolve issues productively without spending too much time and lets me cherry pick the right version of the file without any confusion.

Python: How to increase/reduce the fontsize of x and y tick labels?

You can set the fontsize directly in the call to set_xticklabels and set_yticklabels (as noted in previous answers). This will only affect one Axes at a time.

ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

You can also set the ticklabel font size globally (i.e. for all figures/subplots in a script) using rcParams:

import matplotlib.pyplot as plt

plt.rc('xtick',labelsize=8)
plt.rc('ytick',labelsize=8)

Or, equivalently:

plt.rcParams['xtick.labelsize']=8
plt.rcParams['ytick.labelsize']=8

Finally, if this is a setting that you would like to be set for all your matplotlib plots, you could also set these two rcParams in your matplotlibrc file:

xtick.labelsize      : 8 # fontsize of the x tick labels
ytick.labelsize      : 8 # fontsize of the y tick labels

Difference between an API and SDK

Suppose company C offers product P and P involves software in some way. Then C can offer a library/set of libraries to software developers that drive P's software systems.

That library/libraries are an SDK. It is part of the systems of P. It is a kit for software developers to use in order to modify, configure, fix, improve, etc the software piece of P.

If C wants to offer P's functionality to other companies/systems, it does so with an API.

This is an interface to P. A way for external systems to interact with P.

If you think in terms of implementation, they will seem quite similar. Especially now that the internet has become like one large distributed operating system.

In purpose, though, they are actually quite distinct.

You build something with an SDK and you use or consume something with an API.

Windows ignores JAVA_HOME: how to set JDK as default?

I had the same issue. I have a bunch of Java versions installed and for some reason Java 1.7 was being used instead of Java 1.6, even though I specified in the path to use 1.6 (C:\jdk1.6.0_45_32\bin).

I had to move the path of the JDK I wanted to use (1.6) to be the first entry in the PATH environment variable to make sure Windows uses 1.6 instead of 1.7.

So, for example, the PATH environment variable before was:

C:\Program Files (x86);...<other entries>;C:\dev\ant181\bin;C:\jdk1.6.0_45_32\bin

and after I moved the jdk to be first, it worked:

C:\jdk1.6.0_45_32\bin;C:\Program Files (x86);...<other entries>;C:\dev\ant181\bin

I guess the Windows installer of Java 1.7 installed it to some other directory already in the PATH, thus getting used first instead of the specified custom PATH entry C:\jdk1.6.0_45_32\bin;

source command not found in sh shell

$ls -l `which sh`
/bin/sh -> dash

$sudo dpkg-reconfigure dash #Select "no" when you're asked
[...]

$ls -l `which sh`
/bin/sh -> bash

Then it will be OK

How do I force git to use LF instead of CR+LF under windows?

Context

If you

  1. want to force all users to have LF line endings for text files and
  2. you cannot ensure that all users change their git config,

you can do that starting with git 2.10. 2.10 or later is required, because 2.10 fixed the behavior of text=auto together with eol=lf. Source.

Solution

Put a .gitattributes file in the root of your git repository having following contents:

* text=auto eol=lf

Commit it.

Optional tweaks

You can also add an .editorconfig in the root of your repository to ensure that modern tooling creates new files with the desired line endings.

# EditorConfig is awesome: http://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

How to reshape data from long to wide format

The new (in 2014) tidyr package also does this simply, with gather()/spread() being the terms for melt/cast.

Edit: Now, in 2019, tidyr v 1.0 has launched and set spread and gather on a deprecation path, preferring instead pivot_wider and pivot_longer, which you can find described in this answer. Read on if you want a brief glimpse into the brief life of spread/gather.

library(tidyr)
spread(dat1, key = numbers, value = value)

From github,

tidyr is a reframing of reshape2 designed to accompany the tidy data framework, and to work hand-in-hand with magrittr and dplyr to build a solid pipeline for data analysis.

Just as reshape2 did less than reshape, tidyr does less than reshape2. It's designed specifically for tidying data, not the general reshaping that reshape2 does, or the general aggregation that reshape did. In particular, built-in methods only work for data frames, and tidyr provides no margins or aggregation.

Create a custom callback in JavaScript

When calling the callback function, we could use it like below:

consumingFunction(callbackFunctionName)

Example:

// Callback function only know the action,
// but don't know what's the data.
function callbackFunction(unknown) {
  console.log(unknown);
}

// This is a consuming function.
function getInfo(thenCallback) {
  // When we define the function we only know the data but not
  // the action. The action will be deferred until excecuting.
  var info = 'I know now';
  if (typeof thenCallback === 'function') {
    thenCallback(info);    
  }
}

// Start.
getInfo(callbackFunction); // I know now

This is the Codepend with full example.

PHP form - on submit stay on same page

The best way to stay on the same page is to post to the same page:

<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">

Python Binomial Coefficient

A bit shortened multiplicative variant given by PM 2Ring and alisianoi. Works with python 3 and doesn't require any packages.

def comb(n, k):
  # Remove the next two lines if out-of-range check is not needed
  if k < 0 or k > n:
    return None
  x = 1
  for i in range(min(k, n - k)):
    x = x*(n - i)//(i + 1)
  return x

Or

from functools import reduce
def comb(n, k):
  return (None if k < 0 or k > n else
    reduce(lambda x, i: x*(n - i)//(i + 1), range(min(k, n - k)), 1))

The division is done right after multiplication not to accumulate high numbers.

jQuery get values of checked checkboxes into array

DEMO: http://jsfiddle.net/PBhHK/

$(document).ready(function(){

    var searchIDs = $('input:checked').map(function(){

      return $(this).val();

    });
    console.log(searchIDs.get());

});

Just call get() and you'll have your array as it is written in the specs: http://api.jquery.com/map/

$(':checkbox').map(function() {
      return this.id;
    }).get().join();

How to change font-color for disabled input?

You could use the following style with opacity

input[disabled="disabled"], select[disabled="disabled"], textarea[disabled="disabled"] {
    opacity: 0.85 !important;
}

or a specific CSS class

.ui-state-disabled{
    opacity: 0.85 !important;
}

How to export data from Excel spreadsheet to Sql Server 2008 table

In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:

On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.

After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.

How to split one text file into multiple *.txt files?

On my Linux system (Red Hat Enterprise 6.9), the split command does not have the command-line options for either -n or --additional-suffix.

Instead, I've used this:

split -d -l NUM_LINES really_big_file.txt split_files.txt.

where -d is to add a numeric suffix to the end of the split_files.txt. and -l specifies the number of lines per file.

For example, suppose I have a really big file like this:

$ ls -laF
total 1391952
drwxr-xr-x 2 user.name group         40 Sep 14 15:43 ./
drwxr-xr-x 3 user.name group       4096 Sep 14 15:39 ../
-rw-r--r-- 1 user.name group 1425352817 Sep 14 14:01 really_big_file.txt

This file has 100,000 lines, and I want to split it into files with at most 30,000 lines. This command will run the split and append an integer at the end of the output file pattern split_files.txt..

$ split -d -l 30000 really_big_file.txt split_files.txt.

The resulting files are split correctly with at most 30,000 lines per file.

$ ls -laF
total 2783904
drwxr-xr-x 2 user.name group        156 Sep 14 15:43 ./
drwxr-xr-x 3 user.name group       4096 Sep 14 15:39 ../
-rw-r--r-- 1 user.name group 1425352817 Sep 14 14:01 really_big_file.txt
-rw-r--r-- 1 user.name group  428604626 Sep 14 15:43 split_files.txt.00
-rw-r--r-- 1 user.name group  427152423 Sep 14 15:43 split_files.txt.01
-rw-r--r-- 1 user.name group  427141443 Sep 14 15:43 split_files.txt.02
-rw-r--r-- 1 user.name group  142454325 Sep 14 15:43 split_files.txt.03


$ wc -l *.txt*
    100000 really_big_file.txt
     30000 split_files.txt.00
     30000 split_files.txt.01
     30000 split_files.txt.02
     10000 split_files.txt.03
    200000 total

Android notification is not showing

You were missing the small icon. I did the same mistake and the above step resolved it.

As per the official documentation: A Notification object must contain the following:

  1. A small icon, set by setSmallIcon()

  2. A title, set by setContentTitle()

  3. Detail text, set by setContentText()

  4. On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.

See http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Automatic prune with Git fetch or pull

If you want to always prune when you fetch, I can suggest to use Aliases.

Just type git config -e to open your editor and change the configuration for a specific project and add a section like

[alias]
pfetch = fetch --prune   

the when you fetch with git pfetch the prune will be done automatically.

How to install latest version of Node using Brew

Try to use "n" the Node extremely simple package manager.

> npm install -g n

Once you have "n" installed. You can pull the latest node by doing the following:

> n latest

I've used it successfully on Ubuntu 16.0x and MacOS 10.12 (Sierra)

Reference: https://github.com/tj/n

How to get the range of occupied cells in excel sheet

See the Range.SpecialCells method. For example, to get cells with constant values or formulas use:

_xlWorksheet.UsedRange.SpecialCells(
        Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeConstants |
        Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeFormulas)

Android Studio with Google Play Services

  1. Go to File -> Project Structure
  2. Select 'Project Settings'
  3. Select 'Dependencies' Tab
  4. Click '+' and select '1.Library Dependencies'
  5. Search for : com.google.android.gms:play-services
  6. Select the latest version and click 'OK'

Voila! No need to fight with Gradle :)

Why is there no xrange function in Python3?

comp:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2

>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.656799077987671

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.579368829727173

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

21.54827117919922

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

22.014557123184204

With timeit number=1 param:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.2245171070098877

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=1)

0.10750913619995117

comp:~$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.113872020003328

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.07014398300089

With timeit number=1,2,3,4 param works quick and in linear way:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.09329321900440846

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=2)

0.18501482300052885

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=3)

0.2703447980020428

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=4)

0.36209142999723554

So it seems if we measure 1 running loop cycle like timeit.timeit("[x for x in range(1000000) if x%4]",number=1) (as we actually use in real code) python3 works quick enough, but in repeated loops python 2 xrange() wins in speed against range() from python 3.

How to pass a callback as a parameter into another function

Also, could be simple as:

if( typeof foo == "function" )
    foo();

Best practice multi language website

Database work:

Create Language Table ‘languages’:

Fields:

language_id(primary and auto increamented)

language_name

created_at

created_by

updated_at

updated_by

Create a table in database ‘content’:

Fields:

content_id(primary and auto incremented)

main_content

header_content

footer_content

leftsidebar_content

rightsidebar_content

language_id(foreign key: referenced to languages table)

created_at

created_by

updated_at

updated_by

Front End Work:

When user selects any language from dropdown or any area then save selected language id in session like,

$_SESSION['language']=1;

Now fetch data from database table ‘content’ based on language id stored in session.

Detail may found here http://skillrow.com/multilingual-website-in-php-2/

how to install gcc on windows 7 machine?

Download mingw-get and simply issue:

mingw-get install gcc.

See the Getting Started page.

How to generate List<String> from SQL query?

I think this is what you're looking for.

List<String> columnData = new List<String>();

using(SqlConnection connection = new SqlConnection("conn_string"))
{
    connection.Open();
    string query = "SELECT Column1 FROM Table1";
    using(SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(reader.GetString(0));
            }         
        }
    }
}

Not tested, but this should work fine.

Styling an anchor tag to look like a submit button

Why not just use a button and call the url with JavaScript?

<input type="button" value="Cancel" onclick="location.href='url.html';return false;" />

How to print React component on click of a button?

You'll have to style your printout with @media print {} in the CSS but the simple code is:

export default class Component extends Component {

    print(){
        window.print();
    }


  render() {

  ...
  <span className="print"
              onClick={this.print}>
    PRINT
    </span>

  } 
}

Hope that's helpful!

What is the best way to update the entity in JPA

Using executeUpdate() on the Query API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.

Consider the following example :

 Employee employee= (Employee)entityManager.find(Employee.class , 1);
 entityManager
     .createQuery("update Employee set name = \'xxxx\' where id=1")
     .executeUpdate();

After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee) to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.

Normally , executeUpdate() is used in the bulk update process as it is faster due to bypassing the persistent context

The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.

   Employee employee= (Employee)entityManager.find(Employee.class ,1);
   employee.setName("Updated Name");

Why Java Calendar set(int year, int month, int date) not returning correct date?

1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:

c1.set(2000, Calendar.JANUARY, 30);

What is the difference between git clone and checkout?

One thing to notice is the lack of any "Copyout" within git. That's because you already have a full copy in your local repo - your local repo being a clone of your chosen upstream repo. So you have effectively a personal checkout of everything, without putting some 'lock' on those files in the reference repo.

Git provides the SHA1 hash values as the mechanism for verifying that the copy you have of a file / directory tree / commit / repo is exactly the same as that used by whoever is able to declare things as "Master" within the hierarchy of trust. This avoids all those 'locks' that cause most SCM systems to choke (with the usual problems of private copies, big merges, and no real control or management of source code ;-) !

What should my Objective-C singleton look like?

Another option is to use the +(void)initialize method. From the documentation:

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

So you could do something akin to this:

static MySingleton *sharedSingleton;

+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        sharedSingleton = [[MySingleton alloc] init];
    }
}

builder for HashMap

I had a similar requirement a while back. Its nothing to do with Guava but you can do something like this to be able to cleanly construct a Map using a fluent builder.

Create a base class that extends Map.

public class FluentHashMap<K, V> extends LinkedHashMap<K, V> {
    private static final long serialVersionUID = 4857340227048063855L;

    public FluentHashMap() {}

    public FluentHashMap<K, V> delete(Object key) {
        this.remove(key);
        return this;
    }
}

Then create the fluent builder with methods that suit your needs:

public class ValueMap extends FluentHashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public ValueMap() {}

    public ValueMap withValue(String key, String val) {
        super.put(key, val);
        return this;
    }

... Add withXYZ to suit...

}

You can then implement it like this:

ValueMap map = new ValueMap()
      .withValue("key 1", "value 1")
      .withValue("key 2", "value 2")
      .withValue("key 3", "value 3")

Push local Git repo to new remote including all branches and tags

This is the most concise way I have found, provided the destination is empty. Switch to an empty folder and then:

# Note the period for cwd >>>>>>>>>>>>>>>>>>>>>>>> v
git clone --bare https://your-source-repo/repo.git .
git push --mirror https://your-destination-repo/repo.git

Substitute https://... for file:///your/repo etc. as appropriate.

How do I get the height and width of the Android Navigation Bar programmatically?

Simple One-line Solution

As suggested in many of above answers, for example

Simply getting navigation bar height may not be enough. We need to consider whether 1. navigation bar exists, 2. is it on the bottom, or right or left, 3. is app open in multi-window mode.

Fortunately you can easily bypass all the long coding by simply setting android:fitsSystemWindows="true" in your root layout. Android system will automatically take care of adding necessary padding to the root layout to make sure that the child views don't get into the navigation bar or statusbar regions.

There is a simple one line solution

android:fitsSystemWindows="true"

or programatically

findViewById(R.id.your_root_view).setFitsSystemWindows(true);

you may also get root view by

findViewById(android.R.id.content).getRootView();
or
getWindow().getDecorView().findViewById(android.R.id.content)

For more details on getting root-view refer - https://stackoverflow.com/a/4488149/9640177

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

First allow NULL on the parent table and set the default values to NULL. Next create the foreign key relationship. Afterwards, you can update the values to match accordingly

Create a branch in Git from another branch

If you want create a new branch from any of the existing branches in Git, just follow the options.

First change/checkout into the branch from where you want to create a new branch. For example, if you have the following branches like:

  • master
  • dev
  • branch1

So if you want to create a new branch called "subbranch_of_b1" under the branch named "branch1" follow the steps:

  1. Checkout or change into "branch1"

    git checkout branch1
    
  2. Now create your new branch called "subbranch_of_b1" under the "branch1" using the following command.

    git checkout -b subbranch_of_b1 branch1
    

    The above will create a new branch called subbranch_of_b1 under the branch branch1 (note that branch1 in the above command isn't mandatory since the HEAD is currently pointing to it, you can precise it if you are on a different branch though).

  3. Now after working with the subbranch_of_b1 you can commit and push or merge it locally or remotely.

A sample Graphical Illustration Of Creating Branches Under another Branch

push the subbranch_of_b1 to remote

 git push origin subbranch_of_b1 

Check if a key is down?

I scanned the above answers and the proposed keydown/keyup approach works only under special circumstances. If the user alt-tabs away, or uses a key gesture to open a new browser window or tab, then a keydown will be registered, which is fine, because at that point it's impossible to tell if the key is something the web app is monitoring, or is a standard browser or OS shortcut. Coming back to the browser page, it'll still think the key is held, though it was released in the meantime. Or some key is simply kept held, while the user is switching to another tab or application with the mouse, then released outside our page.

Modifier keys (Shift etc.) can be monitored via mousemove etc. assuming that there is at least one mouse interaction expected when tabbing back, which is frequently the case.

For most all other keys (except modifiers, Tab, Delete, but including Space, Enter), monitoring keypress would work for most applications - a key held down will continue to fire. There's some latency in resetting the key though, due to the periodicity of keypress firing. Basically, if keypress doesn't keep firing, then it's possible to rule out most of the keys. This, combined with the modifiers is pretty airtight, though I haven't explored what to do with Tab and Backspace.

I'm sure there's some library out there that abstracts over this DOM weakness, or maybe some DOM standard change took care of it, since it's a rather old question.

Split string into individual words Java

Yet another method, using StringTokenizer :

String s = "I want to walk my dog";
StringTokenizer tokenizer = new StringTokenizer(s);

while(tokenizer.hasMoreTokens()) {
    System.out.println(tokenizer.nextToken());
}

Can't drop table: A foreign key constraint fails

Use show create table tbl_name to view the foreign keys

You can use this syntax to drop a foreign key:

ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol

There's also more information here (see Frank Vanderhallen post): http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;

ArrayList<String> recordings = new ArrayList<String>();

this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.

Running AMP (apache mysql php) on Android

Check out androPHP I use it for testing on android ANdroPHP.

echo that outputs to stderr

No, that's the standard way to do it. It shouldn't cause errors.

Is there a short contains function for lists?

You can use this syntax:

if myItem in list:
    # do something

Also, inverse operator:

if myItem not in list:
    # do something

It's work fine for lists, tuples, sets and dicts (check keys).

Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts.

How can I find the number of days between two Date objects in Ruby?

This worked for me:

(endDate - beginDate).to_i

Python - Join with newline

You need to print to get that output.
You should do

>>> x = "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
>>> x                   # this is the value, returned by the join() function
'I\nwould\nexpect\nmultiple\nlines'
>>> print x    # this prints your string (the type of output you want)
I
would
expect
multiple
lines

How do I loop through or enumerate a JavaScript object?

You can just iterate over it like:

for (var key in p) {
  alert(p[key]);
}

Note that key will not take on the value of the property, it's just an index value.

How to remove unused imports from Eclipse

I know this is a very old thread. I found this way very helpful for me:

  1. Go to Window ? Preferences ? Java ? Editor ? Save Actions.
  2. Check the option "Perform the selected actions on save".
  3. Check the option "Organize imports".

Now every time you save your classes, eclipse will take care of removing the unused imports.

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

tar: file changed as we read it

To enhance Fabian's one-liner; let us say that we want to ignore only exit status 1 but to preserve the exit status if it is anything else:

tar -czf sample.tar.gz dir1 dir2 || ( export ret=$?; [[ $ret -eq 1 ]] || exit "$ret" )

This does everything sandeep's script does, on one line.

Select row on click react-table

if u want to have multiple selection on select row..

import React from 'react';
import ReactTable from 'react-table';
import 'react-table/react-table.css';
import { ReactTableDefaults } from 'react-table';
import matchSorter from 'match-sorter';


class ThreatReportTable extends React.Component{

constructor(props){
  super(props);

  this.state = {
    selected: [],
    row: []
  }
}
render(){

  const columns = this.props.label;

  const data = this.props.data;

  Object.assign(ReactTableDefaults, {
    defaultPageSize: 10,
    pageText: false,
    previousText: '<',
    nextText: '>',
    showPageJump: false,
    showPagination: true,
    defaultSortMethod: (a, b, desc) => {
    return b - a;
  },


  })

    return(
    <ReactTable className='threatReportTable'
        data= {data}
        columns={columns}
        getTrProps={(state, rowInfo, column) => {


        return {
          onClick: (e) => {


            var a = this.state.selected.indexOf(rowInfo.index);


            if (a == -1) {
              // this.setState({selected: array.concat(this.state.selected, [rowInfo.index])});
              this.setState({selected: [...this.state.selected, rowInfo.index]});
              // Pass props to the React component

            }

            var array = this.state.selected;

            if(a != -1){
              array.splice(a, 1);
              this.setState({selected: array});


            }
          },
          // #393740 - Lighter, selected row
          // #302f36 - Darker, not selected row
          style: {background: this.state.selected.indexOf(rowInfo.index) != -1 ? '#393740': '#302f36'},


        }


        }}
        noDataText = "No available threats"
        />

    )
}
}


  export default ThreatReportTable;

How do I change the formatting of numbers on an axis with ggplot?

I also found another way of doing this that gives proper 'x10(superscript)5' notation on the axes. I'm posting it here in the hope it might be useful to some. I got the code from here so I claim no credit for it, that rightly goes to Brian Diggs.

fancy_scientific <- function(l) {
     # turn in to character string in scientific notation
     l <- format(l, scientific = TRUE)
     # quote the part before the exponent to keep all the digits
     l <- gsub("^(.*)e", "'\\1'e", l)
     # turn the 'e+' into plotmath format
     l <- gsub("e", "%*%10^", l)
     # return this as an expression
     parse(text=l)
}

Which you can then use as

ggplot(data=df, aes(x=x, y=y)) +
   geom_point() +
   scale_y_continuous(labels=fancy_scientific) 

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

I found this answer to the question:

http://padcom13.blogspot.co.uk/2011/10/creating-standalone-applications-with.html

Not only do you get the dependent lib files in a lib folder, you also get a bin director with both a unix and a dos executable.

The executable ultimately calls java with a -cp argument that lists all of your dependent libs too.

The whole lot sits in an appasembly folder inside the target folder. Epic.

============= Yes I know this is an old thread, but it's still coming high on search results so I thought it might help someone like me.

Android Drawing Separator/Divider Line in Layout?

You can use this in LinearLayout :

android:divider="?android:dividerHorizontal"
android:showDividers="middle"

For Example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="?android:dividerHorizontal"
    android:showDividers="middle"
    android:orientation="vertical" >            

        <TextView 
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:text="abcd gttff hthjj ssrt guj"/>

        <TextView 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="abcd"/>
        <TextView 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="abcd gttff hthjj ssrt guj"/>

        <TextView 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="abcd"/>

</LinearLayout>

jQuery on window resize

Here's an example using jQuery, javascript and css to handle resize events.
(css if your best bet if you're just stylizing things on resize (media queries))
http://jsfiddle.net/CoryDanielson/LAF4G/

css

.footer 
{
    /* default styles applied first */
}

@media screen and (min-height: 820px) /* height >= 820 px */
{
    .footer {
        position: absolute;
        bottom: 3px;
        left: 0px;
        /* more styles */
    }
}

javascript

window.onresize = function() {
    if (window.innerHeight >= 820) { /* ... */ }
    if (window.innerWidth <= 1280) {  /* ... */ }
}

jQuery

$(window).on('resize', function(){
    var win = $(this); //this = window
    if (win.height() >= 820) { /* ... */ }
    if (win.width() >= 1280) { /* ... */ }
});

How do I stop my resize code from executing so often!?

This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.

To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lowdash libraries.

  • debounce will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.
  • throttle will only execute your resize code every X number of milliseconds. It "throttles" how often the code is called. This isn't used as often with resize events, but it's worth being aware of.

If you don't have underscore or lowdash, you can implement a similar solution yourself: JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Installing specific laravel version with composer create-project

Installing specific laravel version with composer create-project

composer global require laravel/installer

Then, if you want install specific version then just edit version values "6." , "5.8."

composer create-project --prefer-dist laravel/laravel Projectname "6.*"

Run Local Development Server

php artisan serve

sudo: docker-compose: command not found

If you have tried installing via the official docker-compose page, where you need to download the binary using curl:

curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

Then do not forget to add executable flag to the binary:

chmod +x /usr/local/bin/docker-compose

If docker-compose is installed using python-pip

sudo apt-get -y install python-pip
sudo pip install docker-compose

try using pip show --files docker-compose to see where it is installed.

If docker-compose is installed in user path, then try:

sudo "PATH=$PATH" docker-compose

As I see from your updated post, docker-compose is installed in user path /home/user/.local/bin and if this path is not in your local path $PATH, then try:

sudo "PATH=$PATH:/home/user/.local/bin" docker-compose

curl POST format for CURLOPT_POSTFIELDS

EDIT: From php5 upwards, usage of http_build_query is recommended:

string http_build_query ( mixed $query_data [, string $numeric_prefix [, 
                          string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

Simple example from the manual:

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "\n";

/* output:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
*/

?>

before php5:

From the manual:

CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.

So something like this should work perfectly (with parameters passed in a associative array):

function preparePostFields($array) {
  $params = array();

  foreach ($array as $key => $value) {
    $params[] = $key . '=' . urlencode($value);
  }

  return implode('&', $params);
}

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

How to set 777 permission on a particular folder?

Easiest way to set permissions to 777 is to connect to Your server through FTP Application like FileZilla, right click on folder, module_installation, and click Change Permissions - then write 777 or check all permissions.

batch file to copy files to another location?

Batch file to copy folder is easy.

xcopy /Y C:\Source\*.* C:\NewFolder

Save the above as a batch file, and get Windows to run it on start up.

To do the same thing when folder is updated is trickier, you'll need a program that monitors the folder every x time and check for changes. You can write the program in VB/Java/whatever then schedule it to run every 30mins.

Why use getters and setters/accessors?

One other use (in languages that support properties) is that setters and getters can imply that an operation is non-trivial. Typically, you want to avoid doing anything that's computationally expensive in a property.

Extract part of a regex match

The currently top-voted answer by Krzysztof Krason fails with <title>a</title><title>b</title>. Also, it ignores title tags crossing line boundaries, e.g., for line-length reasons. Finally, it fails with <title >a</title> (which is valid HTML: White space inside XML/HTML tags).

I therefore propose the following improvement:

import re

def search_title(html):
    m = re.search(r"<title\s*>(.*?)</title\s*>", html, re.IGNORECASE | re.DOTALL)
    return m.group(1) if m else None

Test cases:

print(search_title("<title   >with spaces in tags</title >"))
print(search_title("<title\n>with newline in tags</title\n>"))
print(search_title("<title>first of two titles</title><title>second title</title>"))
print(search_title("<title>with newline\n in title</title\n>"))

Output:

with spaces in tags
with newline in tags
first of two titles
with newline
  in title

Ultimately, I go along with others recommending an HTML parser - not only, but also to handle non-standard use of HTML tags.

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

I solved this by creating all under user variables (including the PATH variable). This is because the system variables do not "translate" the user variables. So if you only want to use maven in your account, you need to add another PATH variable as a user variable, not system variable.

How to add meta tag in JavaScript

Like this ?

<script>
var meta = document.createElement('meta');
meta.setAttribute('http-equiv', 'X-UA-Compatible');
meta.setAttribute('content', 'IE=Edge');
document.getElementsByTagName('head')[0].appendChild(meta);
</script>

Select specific row from mysql table

SQL tables are not ordered by default, and asking for the n-th row from a non ordered set of rows has no meaning as it could potentially return a different row each time unless you specify an ORDER BY:

select * from customer order by id where row_number() = 3

(sometimes MySQL tables are shown with an internal order but you cannot rely on this behaviour). Then you can use LIMIT offset, row_count, with a 0-based offset so row number 3 becomes offset 2:

select * from customer order by id
limit 2, 1

or you can use LIMIT row_count OFFSET offset:

select * from customer order by id
limit 1 offset 2

Archive the artifacts in Jenkins

Also, does Jenkins delete the artifacts after each build ? (not the archived artifacts, I know I can tell it to delete those)

No, Hudson/Jenkins does not, by itself, clear the workspace after a build. You might have actions in your build process that erase, overwrite, or move build artifacts from where you left them. There is an option in the job configuration, in Advanced Project Options (which must be expanded), called "Clean workspace before build" that will wipe the workspace at the beginning of a new build.

Rules for C++ string literals escape character

I left something like this as a comment, but I feel it probably needs more visibility as none of the answers mention this method:

The method I now prefer for initializing a std::string with non-printing characters in general (and embedded null characters in particular) is to use the C++11 feature of initializer lists.

std::string const str({'\0', '6', '\a', 'H', '\t'});

I am not required to perform error-prone manual counting of the number of characters that I am using, so that if later on I want to insert a '\013' in the middle somewhere, I can and all of my code will still work. It also completely sidesteps any issues of using the wrong escape sequence by accident.

The only downside is all of those extra ' and , characters.

Getting the index of a particular item in array

FindIndex Extension

static class ArrayExtensions
{
    public static int FindIndex<T>(this T[] array, Predicate<T> match)
    {
        return Array.FindIndex(array, match);
    }
}

Usage

int[] array = { 9,8,7,6,5 };

var index = array.FindIndex(i => i == 7);

Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.


Bonus: IndexOf Extension

I wrote this first not reading the question properly...

static class ArrayExtensions
{
    public static int IndexOf<T>(this T[] array, T value)
    {
        return Array.IndexOf(array, value);
    }   
}

Usage

int[] array = { 9,8,7,6,5 };

var index = array.IndexOf(7);

Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

LTrim function and RTrim function :

  • The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable.
  • It uses the Trim function to remove both types of spaces.

                  select LTRIM(RTRIM(' SQL Server '))
    

    output:

                             SQL Server
    

How to import keras from tf.keras in Tensorflow?

this worked for me in tensorflow==1.4.0

from tensorflow.python import keras

Java Replacing multiple different substring in a string at once (or in the most efficient way)

StringBuilder will perform replace more efficiently, since its character array buffer can be specified to a required length.StringBuilder is designed for more than appending!

Of course the real question is whether this is an optimisation too far ? The JVM is very good at handling creation of multiple objects and the subsequent garbage collection, and like all optimisation questions, my first question is whether you've measured this and determined that it's a problem.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

You should define the __unicode__ method on your model, and the template will call it automatically when you reference the instance.

Is there a simple way to remove multiple spaces in a string?

foo is your string:

" ".join(foo.split())

Be warned though this removes "all whitespace characters (space, tab, newline, return, formfeed)" (thanks to hhsaffar, see comments). I.e., "this is \t a test\n" will effectively end up as "this is a test".

React js change child component's state from parent component

Above answer is partially correct for me, but In my scenario, I want to set the value to a state, because I have used the value to show/toggle a modal. So I have used like below. Hope it will help someone.

class Child extends React.Component {
  state = {
    visible:false
  };

  handleCancel = (e) => {
      e.preventDefault();
      this.setState({ visible: false });
  };

  componentDidMount() {
    this.props.onRef(this)
  }

  componentWillUnmount() {
    this.props.onRef(undefined)
  }

  method() {
    this.setState({ visible: true });
  }

  render() {
    return (<Modal title="My title?" visible={this.state.visible} onCancel={this.handleCancel}>
      {"Content"}
    </Modal>)
  }
}

class Parent extends React.Component {
  onClick = () => {
    this.child.method() // do stuff
  }
  render() {
    return (
      <div>
        <Child onRef={ref => (this.child = ref)} />
        <button onClick={this.onClick}>Child.method()</button>
      </div>
    );
  }
}

Reference - https://github.com/kriasoft/react-starter-kit/issues/909#issuecomment-252969542

How can I set NODE_ENV=production on Windows?

In PowerShell:

$env:NODE_ENV="production"

How to combine two or more querysets in a Django view?

Requirements: Django==2.0.2, django-querysetsequence==0.8

In case you want to combine querysets and still come out with a QuerySet, you might want to check out django-queryset-sequence.

But one note about it. It only takes two querysets as it's argument. But with python reduce you can always apply it to multiple querysets.

from functools import reduce
from queryset_sequence import QuerySetSequence

combined_queryset = reduce(QuerySetSequence, list_of_queryset)

And that's it. Below is a situation I ran into and how I employed list comprehension, reduce and django-queryset-sequence

from functools import reduce
from django.shortcuts import render    
from queryset_sequence import QuerySetSequence

class People(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mentor = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, related_name='my_mentees')

class Book(models.Model):
    name = models.CharField(max_length=20)
    owner = models.ForeignKey(Student, on_delete=models.CASCADE)

# as a mentor, I want to see all the books owned by all my mentees in one view.
def mentee_books(request):
    template = "my_mentee_books.html"
    mentor = People.objects.get(user=request.user)
    my_mentees = mentor.my_mentees.all() # returns QuerySet of all my mentees
    mentee_books = reduce(QuerySetSequence, [each.book_set.all() for each in my_mentees])

    return render(request, template, {'mentee_books' : mentee_books})

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I have a theory on this bug, which happened to me a few times as well.

What I think happens: if you are logged into iTunesConnect, then the web page will query the database for available builds. This querying could possibly interfere with the creation of new builds.

What I did was: Log off from iTunesConnect on all your web browsers. Increase the build nr in Xcode, make an Archive, and upload it.

Then: resist the temptations to log into iTunesConnect to check on the status. Wait at least an hr before logging on.

When I did finally log on to iTunesConnect, I found my binaries sitting there, and waiting for me.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

As suggested by djjeck in comment in this answer I missed to put public modifier for my class.

It should be

public class MyActivity extends AppCompatActivity {

It may help some like me.

Linear regression with matplotlib / numpy

import numpy as np
import matplotlib.pyplot as plt 
from scipy import stats

x = np.array([1.5,2,2.5,3,3.5,4,4.5,5,5.5,6])
y = np.array([10.35,12.3,13,14.0,16,17,18.2,20,20.7,22.5])
gradient, intercept, r_value, p_value, std_err = stats.linregress(x,y)
mn=np.min(x)
mx=np.max(x)
x1=np.linspace(mn,mx,500)
y1=gradient*x1+intercept
plt.plot(x,y,'ob')
plt.plot(x1,y1,'-r')
plt.show()

USe this ..

Git log to get commits only for a specific branch

You could try something like this:

#!/bin/bash

all_but()
{
    target="$(git rev-parse $1)"
    echo "$target --not"
    git for-each-ref --shell --format="ref=%(refname)" refs/heads | \
    while read entry
    do
        eval "$entry"

        test "$ref" != "$target" && echo "$ref"
    done
}

git log $(all_but $1)

Or, borrowing from the recipe in the Git User's Manual:

#!/bin/bash
git log $1 --not $( git show-ref --heads | cut -d' ' -f2 | grep -v "^$1" )

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I have the same problem and i think the firewall is blocking the git protocol. So in the end I have to resort to using https:// to fetch and push. However this will always prompt the user to enter the password...

here is the example what working for me (just to share with those cant use git:// protocol :)

git fetch https://[user-name]@github.com/[user-name]/[project].git

if the above works, you can remove the origin and replace with

git remote rm origin  
git remote add origin https://[user-name]@github.com/[user-name]/[project].git

Ignore self-signed ssl cert using Jersey Client

Just adding the same code with the imports. Also contains the unimplemented code that is needed for compilation. I initially had trouble finding out what was imported for this code. Also adding the right package for the X509Certificate. Got this working with trial and error:

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import javax.ws.rs.core.MultivaluedMap;

 TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

     public java.security.cert.X509Certificate[] getAcceptedIssuers() {
         java.security.cert.X509Certificate[] chck = null;
         ;
         return chck;
     }

     public void checkServerTrusted(X509Certificate[] arg0, String arg1)
             throws CertificateException {
         // TODO Auto-generated method stub

     }

     public void checkClientTrusted(X509Certificate[] arg0, String arg1)
             throws CertificateException {

     }

     public void checkClientTrusted(
             java.security.cert.X509Certificate[] arg0, String arg1)
                     throws java.security.cert.CertificateException {
         // TODO Auto-generated method stub

     }

     public void checkServerTrusted(
             java.security.cert.X509Certificate[] arg0, String arg1)
                     throws java.security.cert.CertificateException {
         // TODO Auto-generated method stub

     }
 } };

 // Install the all-trusting trust manager
 try {
     SSLContext sc = SSLContext.getInstance("TLS");
     sc.init(null, trustAllCerts, new SecureRandom());
     HttpsURLConnection
     .setDefaultSSLSocketFactory(sc.getSocketFactory());
 } catch (Exception e) {
     ;
 }

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

Make child div stretch across width of page

Since position: absolute; and viewport width were no options in my special case, there is another quick solution to solve the problem. The only condition is, that overflow in x-direction is not necessary for your website.

You can define negative margins for your element:

#help_panel {
    margin-left: -9999px;
    margin-right: -9999px;
}

But since we get overflow doing this, we have to avoid overflow in x-direction globally e.g. for body:

body {
    overflow-x: hidden;
}

You can set padding to choose the size of your content.

Note that this solution does not bring 100% width for content, but it is helpful in cases where you need e.g. a background color which has full width with a content still depending on container.

How do I make case-insensitive queries on Mongodb?

I just solved this problem a few hours ago.

var thename = 'Andrew'
db.collection.find({ $text: { $search: thename } });
  • Case sensitivity and diacritic sensitivity are set to false by default when doing queries this way.

You can even expand upon this by selecting on the fields you need from Andrew's user object by doing it this way:

db.collection.find({ $text: { $search: thename } }).select('age height weight');

Reference: https://docs.mongodb.org/manual/reference/operator/query/text/#text

Change event on select with knockout binding, how can I know if it is a real change?

Actually you want to find whether the event is triggered by user or program , and its obvious that event will trigger while initialization.

The knockout approach of adding subscription won't help in all cases, why because in most of the model will be implemented like this

  1. init the model with undefined data , just structure (actual KO initilization)
  2. update the model with initial data (logical init like load JSON , get data etc)
  3. User interaction and updates

The actual step that we want to capture is changes in 3, but in second step subscription will get call , So a better way is to add to event change like

 <select data-bind="value: level, event:{ change: $parent.permissionChanged}">

and detected the event in permissionChanged function

this.permissionChanged = function (obj, event) {

  if (event.originalEvent) { //user changed

  } else { // program changed

  }

}

Command to escape a string in bash

It may not be quite what you want, since it's not a standard command on anyone's systems, but since my program should work fine on POSIX systems (if compiled), I'll mention it anyway. If you have the ability to compile or add programs on the machine in question, it should work.

I've used it without issue for about a year now, but it could be that it won't handle some edge cases. Most specifically, I have no idea what it would do with newlines in strings; a case for \\n might need to be added. This list of characters is not authoritative, but I believe it covers everything else.

I wrote this specifically as a 'helper' program so I could make a wrapper for things like scp commands.

It can likely be implemented as a shell function as well

I therefore present escapify.c. I use it like so:

scp user@host:"$(escapify "/this/path/needs to be escaped/file.c")" destination_file.c

PLEASE NOTE: I made this program for my own personal use. It also will (probably wrongly) assume that if it is given more than one argument that it should just print an unescaped space and continue on. This means that it can be used to pass multiple escaped arguments correctly, but could be seen as unwanted behavior by some.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
  char c='\0';
  int i=0;
  int j=1;
  /* do not care if no args passed; escaped nothing is still nothing. */
  if(argc < 2)
  {
    return 0;
  }
  while(j<argc)
  {
    while(i<strlen(argv[j]))
    {
      c=argv[j][i];
      /* this switch has no breaks on purpose. */
      switch(c)
      {
      case ';':
      case '\'':
      case ' ':
      case '!':
      case '"':
      case '#':
      case '$':
      case '&':
      case '(':
      case ')':
      case '|':
      case '*':
      case ',':
      case '<':
      case '>':
      case '[':
      case ']':
      case '\\':
      case '^':
      case '`':
      case '{':
      case '}':
        putchar('\\');
      default:
        putchar(c);
      }
      i++;
    }
    j++;
    if(j<argc) {
      putchar(' ');
    }
    i=0;
  }
  /* newline at end */
  putchar ('\n');
  return 0;
}

Remove carriage return in Unix

If you're using an OS (like OS X) that doesn't have the dos2unix command but does have a Python interpreter (version 2.5+), this command is equivalent to the dos2unix command:

python -c "import sys; import fileinput; sys.stdout.writelines(line.replace('\r', '\n') for line in fileinput.input(mode='rU'))"

This handles both named files on the command line as well as pipes and redirects, just like dos2unix. If you add this line to your ~/.bashrc file (or equivalent profile file for other shells):

alias dos2unix="python -c \"import sys; import fileinput; sys.stdout.writelines(line.replace('\r', '\n') for line in fileinput.input(mode='rU'))\""

... the next time you log in (or run source ~/.bashrc in the current session) you will be able to use the dos2unix name on the command line in the same manner as in the other examples.

How to use a variable from a cursor in the select statement of another cursor in pl/sql

Use alter session set current_schema = <username>, in your case as an execute immediate.

See Oracle's documentation for further information.

In your case, that would probably boil down to (untested)

DECLARE

   CURSOR client_cur IS
     SELECT  distinct username 
       from all_users 
      where length(username) = 3;

   -- client cursor 
   CURSOR emails_cur IS
   SELECT id, name 
     FROM org;

BEGIN

   FOR client IN client_cur LOOP

   -- ****
      execute immediate 
     'alter session set current_schema = ' || client.username;
   -- ****

      FOR email_rec in client_cur LOOP

         dbms_output.put_line(
             'Org id is ' || email_rec.id || 
             ' org nam '  || email_rec.name);

      END LOOP;

  END LOOP;
END;
/

What are the differences between "git commit" and "git push"?

Since git is a distributed version control system, the difference is that commit will commit changes to your local repository, whereas push will push changes up to a remote repo.

Merging cells in Excel using Apache POI

You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);

example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4)); will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).

for detail refer BusyDeveloper's Guide

HTML not loading CSS file

guys the best thing to try is to refreash the whole website by pressing ctrl + F5 on mac it is CMD + R

How to remove margin space around body or clear default css styles

try to ad the following in your CSS:

body, html{
    padding:0;
    margin:0;
}

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

How to dynamically change a web page's title?

You can use JavaScript. Some bots, including Google, will execute the JavaScript for the benefit of SEO (showing the correct title in the SERP).

document.title = "Google will run this JS and show the title in the search results!";

However, this is more complex since you are showing and hiding tabs without refreshing the page or changing the URL. Maybe adding an anchor will help as stated by others. I may need to retract my answer.

Articles showing positive results: http://www.aukseo.co.uk/use-javascript-to-generate-seo-friendly-title-tags-1275/ http://www.ifinity.com.au/2012/10/04/Changing_a_Page_Title_with_Javascript_to_update_a_Google_SERP_Entry

Don't always assume a bot won't execute JavaScript. http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157 Google and other search engines know that the best results to index are the results that the actual end user will see in their browser, including JavaScript.

PHP removing a character in a string

$str = preg_replace('/\?\//', '?', $str);

Edit: See CMS' answer. It's late, I should know better.

Create a directly-executable cross-platform GUI app using Python

!!! KIVY !!!

I was amazed seeing that no one mentioned Kivy!!!

I have once done a project using Tkinter, although they do advocate that it has improved a lot, it still gives me a feel of windows 98, so I switched to Kivy.

I have been following a tutorial series if it helps...

Just to give an idea of how kivy looks, see this (The project I am working on):

The Project that I am working on

And I have been working on it for barely a week now ! The benefits for Kivy you ask? Check this

The reason why I chose this is, its look and that it can be used in mobile as well.

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

this is the easiest way: Make list
Select list
right click: Define Name (e.g. ItemStatus)
select a cell where the list should appear (copy paste can be done later, so not location critical)
Data > Data Validation
Allow: Select List
Source: =ItemStatus (don't forget the = sign)
click Ok
dropdown appears in the cell you selected
Home > Conditional Formatting
Manage Rules
New Rule
etc.

Eclipse CDT: no rule to make target all

In C/C++ Build -> Builder Settings, select Internal builder (instead of External builder).

It works for me.

How to change fonts in matplotlib (python)?

The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):

import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

print(fpath) will show you where you should put the .ttf.

You can see the output here: https://matplotlib.org/gallery/api/font_file.html

How do I create a local database inside of Microsoft SQL Server 2014?

Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link

Youtube video about entire process.
Writeup with pictures about installing SQL Server

How to select a local server:

When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:

1) Make sure you have Server Type: Database

2) Make sure you have Authentication: Windows Authentication (no username & password)

3) For the server name field look to the right and select the drop down arrow, click 'browse for more'

4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14

How do I create a local database inside of Microsoft SQL Server 2014?

1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)

2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.

  <configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <requestLimits>
               <headerLimits>
                  <add header="Content-type" sizeLimit="100" />
               </headerLimits>
            </requestLimits>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>

Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

How to select a value in dropdown javascript?

Using some ES6:

Get the options first, filter the value based on the option and set the selected attribute to true.

_x000D_
_x000D_
window.onload = () => {_x000D_
_x000D_
  Array.from(document.querySelector(`#Mobility`).options)_x000D_
    .filter(x => x.value === "12")[0]_x000D_
    .setAttribute('selected', true);_x000D_
_x000D_
};
_x000D_
<select style="width: 280px" id="Mobility" name="Mobility">_x000D_
  <option selected disabled>Please Select</option>_x000D_
  <option>K</option>_x000D_
  <option>1</option>_x000D_
  <option>2</option>_x000D_
  <option>3</option>_x000D_
  <option>4</option>_x000D_
  <option>5</option>_x000D_
  <option>6</option>_x000D_
  <option>7</option>_x000D_
  <option>8</option>_x000D_
  <option>9</option>_x000D_
  <option>10</option>_x000D_
  <option>11</option>_x000D_
  <option>12</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to post data to specific URL using WebClient in C#

//Making a POST request using WebClient.
Function()
{    
  WebClient wc = new WebClient();

  var URI = new Uri("http://your_uri_goes_here");

  //If any encoding is needed.
  wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
  //Or any other encoding type.

  //If any key needed

  wc.Headers["KEY"] = "Your_Key_Goes_Here";

  wc.UploadStringCompleted += 
      new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

  wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");    
}

void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)    
{  
  try            
  {          
     MessageBox.Show(e.Result); 
     //e.result fetches you the response against your POST request.         
  }
  catch(Exception exc)         
  {             
     MessageBox.Show(exc.ToString());            
  }
}

How to set time delay in javascript

If you need refresh, this is another posibility:

setTimeout(function () { 
    $("#jsSegurosProductos").jsGrid("refresh"); 
}, 1000);

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

For each conflicted file you get, you can specify

git checkout --ours -- <paths>
# or
git checkout --theirs -- <paths>

From the git checkout docs

git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>...

--ours
--theirs
When checking out paths from the index, check out stage #2 (ours) or #3 (theirs) for unmerged paths.

The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using -f will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using --ours or --theirs. With -m, changes made to the working tree file can be discarded to re-create the original conflicted merge result.

Contain form within a bootstrap popover?

like this Working demo http://jsfiddle.net/7e2XU/21/show/# * Update: http://jsfiddle.net/kz5kjmbt/

 <div class="container">
    <div class="row" style="padding-top: 240px;"> <a href="#" class="btn btn-large btn-primary" rel="popover" data-content='
<form id="mainForm" name="mainForm" method="post" action="">
    <p>
        <label>Name :</label>
        <input type="text" id="txtName" name="txtName" />
    </p>
    <p>
        <label>Address 1 :</label>
        <input type="text" id="txtAddress" name="txtAddress" />
    </p>
    <p>
        <label>City :</label>
        <input type="text" id="txtCity" name="txtCity" />
    </p>
    <p>
        <input type="submit" name="Submit" value="Submit" />
    </p>
</form>
 data-placement="top" data-original-title="Fill in form">Open form</a>

    </div>
</div>

JavaScript code:

    $('a[rel=popover]').popover({
      html: 'true',
      placement: 'right'
    })

ScreenShot

working updated fiddle screenshot

Sending POST parameters with Postman doesn't work, but sending GET parameters does

Check your content-type in the header. I was having issue with this sending raw JSON and my content-type as application/json in the POSTMAN header.

my php was seeing jack all in the request post. It wasn't until i change the content-type to application/x-www-form-urlencoded with the JSON in the RAW textarea and its type as JSON, did my PHP app start to see the post data. not what i expected when deal with raw json but its now working for what i need.

postman POST request

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Changing navigation title programmatically

In Swift 4:

Swift 4

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Your title"
}

I hope it helps, regards!

How to change port number for apache in WAMP

In addition of the modification of the file C:\wamp64\bin\apache\apache2.4.27\conf\httpd.conf.
To get the url shortcuts working, edit the file C:\wamp64\wampmanager.conf and change the port:

[apache]
apachePortUsed = "8080"

Then exit and relaunch wamp.

calling server side event from html button control

On your aspx page define the HTML Button element with the usual suspects: runat, class, title, etc.

If this element is part of a data bound control (i.e.: grid view, etc.) you may want to use CommandName and possibly CommandArgument as attributes. Add your button's content and closing tag.

<button id="cmdAction" 
    runat="server" onserverclick="cmdAction_Click()" 
    class="Button Styles" 
    title="Does something on the server" 
    <!-- for databound controls -->
    CommandName="cmdname"> 
    CommandArgument="args..."
    >
    <!-- content -->
    <span class="ui-icon ..."></span>
    <span class="push">Click Me</span>
</button>

On the code behind page the element would call the handler that would be defined as the element's ID_Click event function.

protected void cmdAction_Click(object sender, EventArgs e)
{
: do something.
}

There are other solutions as in using custom controls, etc. Also note that I am using this live on projects in VS2K8.

Hoping this helps. Enjoy!

Correct file permissions for WordPress

Commands:

chown www-data:www-data -R *
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;

Where ftp-user is what user you are using to upload the files

chown -R ftp-user:www-data wp-content
chmod -R 775 wp-content

Auto increment in phpmyadmin

You cannot set a maximum value (other than choosing a datatype which cannot hold large numbers, but there are none that have the limit you're asking for). You can check that with LAST_INSERT_ID() after inserting to get the id of the newly created member, and if it is too big handle it in your application code (e.g., delete and reject the member).

Why do you want an upper limit?