Programs & Examples On #Rijndaelmanaged

.NET Framework (1.1 and later) managed version of the Rijndael (AES) algorithm.

Using AES encryption in C#

http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt

using System.Security.Cryptography;
using System.IO;

 

public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
    byte[] encryptedBytes = null;
    byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    using (MemoryStream ms = new MemoryStream())
    {
        using (RijndaelManaged AES = new RijndaelManaged())
        {
            AES.KeySize = 256;
            AES.BlockSize = 128;
            var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);
            AES.Mode = CipherMode.CBC;
            using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                cs.Close();
            }
            encryptedBytes = ms.ToArray();
        }
    }
    return encryptedBytes;
}

public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
    byte[] decryptedBytes = null;
    byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    using (MemoryStream ms = new MemoryStream())
    {
        using (RijndaelManaged AES = new RijndaelManaged())
        {
            AES.KeySize = 256;
            AES.BlockSize = 128;
            var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);
            AES.Mode = CipherMode.CBC;
            using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                cs.Close();
            }
            decryptedBytes = ms.ToArray();
        }
    }
    return decryptedBytes;
}

How can I remove all my changes in my SVN working directory?

You can use the following command to revert all local changes:

svn st -q | awk '{print $2;}' | xargs svn revert

How to import multiple .csv files at once?

Something like the following should result in each data frame as a separate element in a single list:

temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)

This assumes that you have those CSVs in a single directory--your current working directory--and that all of them have the lower-case extension .csv.

If you then want to combine those data frames into a single data frame, see the solutions in other answers using things like do.call(rbind,...), dplyr::bind_rows() or data.table::rbindlist().

If you really want each data frame in a separate object, even though that's often inadvisable, you could do the following with assign:

temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))

Or, without assign, and to demonstrate (1) how the file name can be cleaned up and (2) show how to use list2env, you can try the following:

temp = list.files(pattern="*.csv")
list2env(
  lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))), 
         read.csv), envir = .GlobalEnv)

But again, it's often better to leave them in a single list.

Convert all strings in a list to int

Here is a simple solution with explanation for your query.

 a=['1','2','3','4','5'] #The integer represented as a string in this list
 b=[] #Fresh list
 for i in a: #Declaring variable (i) as an item in the list (a).
     b.append(int(i)) #Look below for explanation
 print(b)

Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

Output console:

[1, 2, 3, 4, 5]

So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

jQuery: read text file from file system

specify the full path of the file url

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

Your problem might be here:

OR
                        (
                            SELECT m.ResourceNo FROM JobMember m
                            JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
                            WHERE t.TaskManagerNo = @UserResourceNo
                            OR
                            t.AlternateTaskManagerNo = @UserResourceNo
                        )

try changing to

OR r.ResourceNo IN
                        (
                            SELECT m.ResourceNo FROM JobMember m
                            JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
                            WHERE t.TaskManagerNo = @UserResourceNo
                            OR
                            t.AlternateTaskManagerNo = @UserResourceNo
                        )

“Unable to find manifest signing certificate in the certificate store” - even when add new key

Try this: Right click on your project -> Go to properties -> Click signing which is left side of the screen -> Uncheck the Sign the click once manifests -> Save & Build

Difference between no-cache and must-revalidate

I think there is a difference between max-age=0, must-revalidate and no-cache:

In the must-revalidate case the client is allowed to send a If-Modified-Since request and serve the response from cache if 304 Not Modified is returned.

In the no-cache case, the client must not cache the response, so should not use If-Modified-Since.

How to set up a Web API controller for multipart/form-data

Here's another answer for the ASP.Net Core solution to this problem...

On the Angular side, I took this code example...

https://stackblitz.com/edit/angular-drag-n-drop-directive

... and modified it to call an HTTP Post endpoint:

  prepareFilesList(files: Array<any>) {

    const formData = new FormData();
    for (var i = 0; i < files.length; i++) { 
      formData.append("file[]", files[i]);
    }

    let URL = "https://localhost:44353/api/Users";
    this.http.post(URL, formData).subscribe(
      data => { console.log(data); },
      error => { console.log(error); }
    );

With this in place, here's the code I needed in the ASP.Net Core WebAPI controller:

[HttpPost]
public ActionResult Post()
{
  try
  {
    var files = Request.Form.Files;

    foreach (IFormFile file in files)
    {
        if (file.Length == 0)
            continue;
        
        string tempFilename = Path.Combine(Path.GetTempPath(), file.FileName);
        System.Diagnostics.Trace.WriteLine($"Saved file to: {tempFilename}");

        using (var fileStream = new FileStream(tempFilename, FileMode.Create))
        {
            file.CopyTo(fileStream);
        }
    }
    return new OkObjectResult("Yes");
  }
  catch (Exception ex)
  {
    return new BadRequestObjectResult(ex.Message);
  }
}

Shockingly simple, but I had to piece together examples from several (almost-correct) sources to get this to work properly.

SQL query, store result of SELECT in local variable

I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.

declare @myVal int; set @myVal = isnull((select a from table1), 0);

Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.

Why is it common to put CSRF prevention tokens in cookies?

Besides the session cookie (which is kind of standard), I don't want to use extra cookies.

I found a solution which works for me when building a Single Page Web Application (SPA), with many AJAX requests. Note: I am using server side Java and client side JQuery, but no magic things so I think this principle can be implemented in all popular programming languages.

My solution without extra cookies is simple:

Client Side

Store the CSRF token which is returned by the server after a succesful login in a global variable (if you want to use web storage instead of a global thats fine of course). Instruct JQuery to supply a X-CSRF-TOKEN header in each AJAX call.

The main "index" page contains this JavaScript snippet:

// Intialize global variable CSRF_TOKEN to empty sting. 
// This variable is set after a succesful login
window.CSRF_TOKEN = '';

// the supplied callback to .ajaxSend() is called before an Ajax request is sent
$( document ).ajaxSend( function( event, jqXHR ) {
    jqXHR.setRequestHeader('X-CSRF-TOKEN', window.CSRF_TOKEN);
}); 

Server Side

On successul login, create a random (and long enough) CSRF token, store this in the server side session and return it to the client. Filter certain (sensitive) incoming requests by comparing the X-CSRF-TOKEN header value to the value stored in the session: these should match.

Sensitive AJAX calls (POST form-data and GET JSON-data), and the server side filter catching them, are under a /dataservice/* path. Login requests must not hit the filter, so these are on another path. Requests for HTML, CSS, JS and image resources are also not on the /dataservice/* path, thus not filtered. These contain nothing secret and can do no harm, so this is fine.

@WebFilter(urlPatterns = {"/dataservice/*"})
...
String sessionCSRFToken = req.getSession().getAttribute("CSRFToken") != null ? (String) req.getSession().getAttribute("CSRFToken") : null;
if (sessionCSRFToken == null || req.getHeader("X-CSRF-TOKEN") == null || !req.getHeader("X-CSRF-TOKEN").equals(sessionCSRFToken)) {
    resp.sendError(401);
} else
    chain.doFilter(request, response);
}   

How to parse a CSV file using PHP

Just discovered a handy way to get an index while parsing. My mind was blown.

$handle = fopen("test.csv", "r");
for ($i = 0; $row = fgetcsv($handle ); ++$i) {
    // Do something will $row array
}
fclose($handle);

Source: link

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

The below are the typical situation where we shall get ERR_FILE_NOT_FOUND even file avail in respective folder.

Code:
@font-face {
    font-family: Eau_Sans_Bold;
    src: url("/fonts/eau_sans_bold.otf") format("opentype");
}
Error:
 GET file:///C:/fonts/eau_sans_bold.otf net::ERR_FILE_NOT_FOUND

Answer or Solution.:
@font-face {
    font-family: Eau_Sans_Book;
    src: url("../fonts/eau_sans_book.otf") format("opentype");  
}

Basically browser not able to pick if we metion just /font/. We should to mention ../fonts/ This will work. So, we wont get ERR_FILE_NOT_FOUND.

Count the number of items in my array list

The only thing I would add to Mark Peters solution is that you don't need to iterate over the ArrayList - you should be able to use the addAll(Collection) method on the Set. You only need to iterate over the entire list to do the summations.

How to run console application from Windows Service?

I use this class:

class ProcessWrapper : Process, IDisposable
{
    public enum PipeType { StdOut, StdErr }

    public class Output
    {
        public string Message { get; set; }
        public PipeType Pipe { get; set; }
        public override string ToString()
        {
            return $"{Pipe}: {Message}";
        }
    }

    private readonly string _command;
    private readonly string _args;
    private readonly bool _showWindow;
    private bool _isDisposed;

    private readonly Queue<Output> _outputQueue = new Queue<Output>();

    private readonly ManualResetEvent[] _waitHandles = new ManualResetEvent[2];
    private readonly ManualResetEvent _outputSteamWaitHandle = new ManualResetEvent(false);

    public ProcessWrapper(string startCommand, string args, bool showWindow = false)
    {
        _command = startCommand;
        _args = args;
        _showWindow = showWindow;
    }

    public IEnumerable<string> GetMessages()
    {
        while (!_isDisposed)
        {
            _outputSteamWaitHandle.WaitOne();
            if (_outputQueue.Any())
                yield return _outputQueue.Dequeue().ToString();
        }
    }

    public void SendCommand(string command)
    {
        StandardInput.Write(command);
        StandardInput.Flush();
    }

    public new int Start()
    {
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = _command,
            Arguments = _args,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            RedirectStandardInput = true,
            CreateNoWindow = !_showWindow
        };
        StartInfo = startInfo;

        OutputDataReceived += delegate (object sender, DataReceivedEventArgs args)
        {
            if (args.Data == null)
            {
                _waitHandles[0].Set();
            }
            else if (args.Data.Length > 0)
            {
                _outputQueue.Enqueue(new Output { Message = args.Data, Pipe = PipeType.StdOut });
                _outputSteamWaitHandle.Set();
            }
        };

        ErrorDataReceived += delegate (object sender, DataReceivedEventArgs args)
        {
            if (args.Data == null)
            {
                _waitHandles[1].Set();
            }
            else if (args.Data.Length > 0)
            {
                _outputSteamWaitHandle.Set();
                _outputQueue.Enqueue(new Output { Message = args.Data, Pipe = PipeType.StdErr });
            }
        };

        base.Start();

        _waitHandles[0] = new ManualResetEvent(false);
        BeginErrorReadLine();
        _waitHandles[1] = new ManualResetEvent(false);
        BeginOutputReadLine();

        return Id;
    }

    public new void Dispose()
    {
        StandardInput.Flush();
        StandardInput.Close();
        if (!WaitForExit(1000))
        {
            Kill();
        }
        if (WaitForExit(1000))
        {
            WaitHandle.WaitAll(_waitHandles);
        }
        base.Dispose();
        _isDisposed = true;
    }
}

z-index not working with position absolute

Old question but this answer might help someone.

If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden, otherwise anything outside of it will be cut off.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

I would do something like the following:

INSERT INTO cache VALUES (key, generation)
ON DUPLICATE KEY UPDATE (key = key, generation = generation + 1);

Setting the generation value to 0 in code or in the sql but the using the ON DUP... to increment the value. I think that's the syntax anyway.

log4j configuration via JVM argument(s)?

Relative Path is also ok:

java -Dlog4j.configuration=file:".\log4j.properties" -jar com.your-1.0-SNAPSHOT.jar

or

java -Dlog4j.configuration=file:".\log4j.xml" -jar com.your-1.0-SNAPSHOT.jar

Regex to validate password strength

All of above regex unfortunately didn't worked for me. A strong password's basic rules are

  • Should contain at least a capital letter
  • Should contain at least a small letter
  • Should contain at least a number
  • Should contain at least a special character
  • And minimum length

So, Best Regex would be

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*]).{8,}$

The above regex have minimum length of 8. You can change it from {8,} to {any_number,}

Modification in rules?

let' say you want minimum x characters small letters, y characters capital letters, z characters numbers, Total minimum length w. Then try below regex

^(?=.*[a-z]{x,})(?=.*[A-Z]{y,})(?=.*[0-9]{z,})(?=.*[!@#\$%\^&\*]).{w,}$

Note: Change x, y, z, w in regex

Edit: Updated regex answer

Edit2: Added modification

Check to see if cURL is installed locally?

cURL is disabled for most hosting control panels for security reasons, but it's required for a lot of php applications. It's not unusual for a client to request it. Since the risk of enabling cURL is minimal, you are probably better off enabling it than losing a customer. It's simply a utility that helps php scripts fetch things using standard Internet URLs.

To enable cURL, you will remove curl_exec from the "disabled list" in the control panel php advanced settings. You will also find a disabled list in the various php.ini files; look in /etc/php.ini and other paths that might exist for your control panel. You will need to restart Apache to make the change take effect.

service httpd restart

To confirm whether cURL is enabled or disabled, create a file somewhere in your system and paste the following contents.

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

Save the file as testcurl.php and then run it as a php script.

php testcurl.php

If cURL is disabled you will see this error.

Fatal error: Call to undefined function curl_version() in testcurl.php on line 2

If cURL is enabled you will see a long list of attributes, like this.

array(9) {
["version_number"]=>
int(461570)
["age"]=>
int(1)
["features"]=>
int(540)
["ssl_version_number"]=>
int(9465919)
["version"]=>
string(6) "7.11.2"
["host"]=>
string(13) "i386-pc-win32"
["ssl_version"]=>
string(15) " OpenSSL/0.9.7c"
["libz_version"]=>
string(5) "1.1.4"
["protocols"]=>
array(9) {
[0]=>
string(3) "ftp"
[1]=>
string(6) "gopher"
[2]=>
string(6) "telnet"
[3]=>
string(4) "dict"
[4]=>
string(4) "ldap"
[5]=>
string(4) "http"
[6]=>
string(4) "file"
[7]=>
string(5) "https"
[8]=>
string(4) "ftps"
}
}

How to get the CUDA version?

Found mine after:

whereis cuda

at

cuda: /usr/lib/cuda /usr/include/cuda.h

with

nvcc --version

CUDA Version 9.1.85

Loop through files in a folder using VBA?

Try this one. (LINK)

Private Sub CommandButton3_Click()

Dim FileExtStr As String
Dim FileFormatNum As Long
Dim xWs As Worksheet
Dim xWb As Workbook
Dim FolderName As String
Application.ScreenUpdating = False
Set xWb = Application.ThisWorkbook
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = xWb.Path & "\" & xWb.Name & " " & DateString
MkDir FolderName
For Each xWs In xWb.Worksheets
    xWs.Copy
    If Val(Application.Version) < 12 Then
        FileExtStr = ".xls": FileFormatNum = -4143
    Else
        Select Case xWb.FileFormat
            Case 51:
                FileExtStr = ".xlsx": FileFormatNum = 51
            Case 52:
                If Application.ActiveWorkbook.HasVBProject Then
                    FileExtStr = ".xlsm": FileFormatNum = 52
                Else
                    FileExtStr = ".xlsx": FileFormatNum = 51
                End If
            Case 56:
                FileExtStr = ".xls": FileFormatNum = 56
            Case Else:
                FileExtStr = ".xlsb": FileFormatNum = 50
        End Select
    End If
    xFile = FolderName & "\" & Application.ActiveWorkbook.Sheets(1).Name & FileExtStr
    Application.ActiveWorkbook.SaveAs xFile, FileFormat:=FileFormatNum
    Application.ActiveWorkbook.Close False
Next
MsgBox "You can find the files in " & FolderName
Application.ScreenUpdating = True

End Sub

How to call same method for a list of objects?

It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.

I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:

map(do_something, a_list_of_objects)

This replaces a bunch of code that looks like this:

 do_something(a)
 do_something(b)
 do_something(c)
 ...

But can also be achieved with a pedestrian "for" loop:

  for obj in a_list_of_objects:
       do_something(obj)

The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.

You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):

  [ do_something(x) for x in a_list_of_objects ]

For methods, I suppose either of these would work (with the same reservations):

map(lambda x: x.method_call(), a_list_of_objects)

or

[ x.method_call() for x in a_list_of_objects ]

So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.

How to make a hyperlink in telegram without using bots?

First make link with @bold bot . Then Copy text and paste it to remove "via @bold"

Get current controller in view

I do it like this, but perhaps it's only ASP.NET MVC 4

@ViewContext.RouteData.Values["controller"]

How to change the style of the title attribute inside an anchor tag?

Native tooltip cannot be styled.

That being said, you can use some library that would show styles floating layers when element is being hovered (instead of the native tooltips, and suppress them) requiring little or no code modifications...

Convert nested Python dict to object?

>>> def dict2obj(d):
        if isinstance(d, list):
            d = [dict2obj(x) for x in d]
        if not isinstance(d, dict):
            return d
        class C(object):
            pass
        o = C()
        for k in d:
            o.__dict__[k] = dict2obj(d[k])
        return o


>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
'bar'

Repeat rows of a data.frame

df <- data.frame(a = 1:2, b = letters[1:2]) 
df[rep(seq_len(nrow(df)), each = 2), ]

Inserting line breaks into PDF

Another option is to use TCPDF::Ln(). It adds a line to the PDF with the option to set the height.

If the newlines are within your content already then MultiCell() is probably the way to go, as others have mentioned, but I find I like using:

$pdf->Cell(0, 0, 'Line 1', 0, 0, 'C');
$pdf->Ln();
$pdf->Cell(0, 0, 'Line 2', 0, 0, 'C');

It confuses me that Cell() and MultiCell() take in different arguments so I tend to stick to using Cell() only. Also it reads like a newline character for the PDF the same as \n reads like a newline character in text or <br> in HTML.

Get the last item in an array

You can add a last() function to the Array prototype.

Array.prototype.last = function () {
    return this[this.length - 1];
};

How can I convert ticks to a date format?

    private void button1_Click(object sender, EventArgs e)
    {
        long myTicks = 633896886277130000;
        DateTime dtime = new DateTime(myTicks);
        MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
    }

Gives

September 27, 2009

Is that what you need?

I don't see how that format is necessarily easy to work with in SQL queries, though.

Email Address Validation in Android on EditText

I did this way:

Add this method to check whether email address is valid or not:

private boolean isValidEmailId(String email){

    return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
              + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
              + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
              + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
              + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
              + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
     }

Now check with String of EditText:

if(isValidEmailId(edtEmailId.getText().toString().trim())){
  Toast.makeText(getApplicationContext(), "Valid Email Address.", Toast.LENGTH_SHORT).show();
}else{       
  Toast.makeText(getApplicationContext(), "InValid Email Address.", Toast.LENGTH_SHORT).show();
}

Done

How to display count of notifications in app launcher icon

This is sample and best way for showing badge on notification launcher icon.

Add This Class in your application

public class BadgeUtils {

    public static void setBadge(Context context, int count) {
        setBadgeSamsung(context, count);
        setBadgeSony(context, count);
    }

    public static void clearBadge(Context context) {
        setBadgeSamsung(context, 0);
        clearBadgeSony(context);
    }


    private static void setBadgeSamsung(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    }

    private static void setBadgeSony(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }


    private static void clearBadgeSony(Context context) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(0));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }

    private static String getLauncherClassName(Context context) {

        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                String className = resolveInfo.activityInfo.name;
                return className;
            }
        }
        return null;
    }


}

==> MyGcmListenerService.java Use BadgeUtils class when notification comes.

public class MyGcmListenerService extends GcmListenerService { 

    private static final String TAG = "MyGcmListenerService"; 
    @Override
    public void onMessageReceived(String from, Bundle data) {

            String message = data.getString("Msg");
            String Type = data.getString("Type"); 
            Intent intent = new Intent(this, SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.BigTextStyle bigTextStyle= new NotificationCompat.BigTextStyle();

            bigTextStyle .setBigContentTitle(getString(R.string.app_name))
                    .bigText(message);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(getNotificationIcon())
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(message)
                    .setStyle(bigTextStyle) 
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            int color = getResources().getColor(R.color.appColor);
            notificationBuilder.setColor(color);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


            int unOpenCount=AppUtill.getPreferenceInt("NOTICOUNT",this);
            unOpenCount=unOpenCount+1;

            AppUtill.savePreferenceLong("NOTICOUNT",unOpenCount,this);  
            notificationManager.notify(unOpenCount /* ID of notification */, notificationBuilder.build()); 

// This is for bladge on home icon          
        BadgeUtils.setBadge(MyGcmListenerService.this,(int)unOpenCount);

    }


    private int getNotificationIcon() {
        boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.drawable.notification_small_icon : R.drawable.icon_launcher;
    }
}

And clear notification from preference and also with badge count

 public class SplashActivity extends AppCompatActivity { 
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_splash);

                    AppUtill.savePreferenceLong("NOTICOUNT",0,this);
                    BadgeUtils.clearBadge(this);
            }
    }
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />

Syntax error: Illegal return statement in JavaScript

If you want to return some value then wrap your statement in function

function my_function(){ 

 return my_thing; 
}

Problem is with the statement on the 1st line if you are trying to use PHP

var ask = confirm ('".$message."'); 

IF you are trying to use PHP you should use

 var ask = confirm (<?php echo "'".$message."'" ?>); //now message with be the javascript string!!

Prevent scroll-bar from adding-up to the Width of page on Chrome

I can't add comment for the first answer and it's been a long time... but that demo has a problem:

if(b.prop('scrollHeight')>b.height()){
    normalw = window.innerWidth;
    scrollw = normalw - b.width();
    $('#container').css({marginRight:'-'+scrollw+'px'});
}

b.prop('scrollHeight') always equals b.height(),

I think it should be like this:

if(b.prop('scrollHeight')>window.innerHeight) ...

At last I recommend a method:

html {
 overflow-y: scroll;
}

:root {
  overflow-y: auto;
  overflow-x: hidden;
}

:root body {
  position: absolute;
}

body {
 width: 100vw;
 overflow: hidden;
}

Decorators with parameters?

The syntax for decorators with arguments is a bit different - the decorator with arguments should return a function that will take a function and return another function. So it should really return a normal decorator. A bit confusing, right? What I mean is:

def decorator_factory(argument):
    def decorator(function):
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            result = function(*args, **kwargs)
            more_funny_stuff()
            return result
        return wrapper
    return decorator

Here you can read more on the subject - it's also possible to implement this using callable objects and that is also explained there.

implement addClass and removeClass functionality in angular2

Try to use it via [ngClass] property:

<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
         (click)="toggle(!isOn)">
         Click me!
     </div>`,

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

For OSX your path needs to include /Users/yourusername

their example: /Development/adt-bundle/sdk/platform-tools
needs to be: /Users/yourusername/Development/adt-bundle/sdk/platform-tools

How to send email to multiple recipients with addresses stored in Excel?

You have to loop through every cell in the range "D3:D6" and construct your To string. Simply assigning it to a variant will not solve the purpose. EmailTo becomes an array if you assign the range directly to it. You can do this as well but then you will have to loop through the array to create your To string

Is this what you are trying? (TRIED AND TESTED)

Option Explicit

Sub Mail_workbook_Outlook_1()
     'Working in 2000-2010
     'This example send the last saved version of the Activeworkbook
    Dim OutApp As Object
    Dim OutMail As Object
    Dim emailRng As Range, cl As Range
    Dim sTo As String

    Set emailRng = Worksheets("Selections").Range("D3:D6")

    For Each cl In emailRng 
        sTo = sTo & ";" & cl.Value
    Next

    sTo = Mid(sTo, 2)

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = sTo
        .CC = "[email protected];[email protected]"
        .BCC = ""
        .Subject = "RMA #" & Worksheets("RMA").Range("E1")
        .Body = "Attached to this email is RMA #" & _
        Worksheets("RMA").Range("E1") & _
        ". Please follow the instructions for your department included in this form."
        .Attachments.Add ActiveWorkbook.FullName
         'You can add other files also like this
         '.Attachments.Add ("C:\test.txt")

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Removing fields from struct or hiding them in JSON Response

I just published sheriff, which transforms structs to a map based on tags annotated on the struct fields. You can then marshal (JSON or others) the generated map. It probably doesn't allow you to only serialize the set of fields the caller requested, but I imagine using a set of groups would allow you to cover most cases. Using groups instead of the fields directly would most likely also increase cache-ability.

Example:

package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/hashicorp/go-version"
    "github.com/liip/sheriff"
)

type User struct {
    Username string   `json:"username" groups:"api"`
    Email    string   `json:"email" groups:"personal"`
    Name     string   `json:"name" groups:"api"`
    Roles    []string `json:"roles" groups:"api" since:"2"`
}

func main() {
    user := User{
        Username: "alice",
        Email:    "[email protected]",
        Name:     "Alice",
        Roles:    []string{"user", "admin"},
    }

    v2, err := version.NewVersion("2.0.0")
    if err != nil {
        log.Panic(err)
    }

    o := &sheriff.Options{
        Groups:     []string{"api"},
        ApiVersion: v2,
    }

    data, err := sheriff.Marshal(o, user)
    if err != nil {
        log.Panic(err)
    }

    output, err := json.MarshalIndent(data, "", "  ")
    if err != nil {
        log.Panic(err)
    }
    fmt.Printf("%s", output)
}

Difference between "@id/" and "@+id/" in Android

@id/ and @android:id/ is not the same.

@id/ referencing ID in your application, @android:id/ referencing an item in Android platform.

Eclipse is wrong.

printing all contents of array in C#

You may try this:

foreach(var item in yourArray)
{
    Console.WriteLine(item.ToString());
}

Also you may want to try something like this:

yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));

EDIT: to get output in one line [based on your comment]:

 Console.WriteLine("[{0}]", string.Join(", ", yourArray));
 //output style:  [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]

EDIT(2019): As it is mentioned in other answers it is better to use Array.ForEach<T> method and there is no need to do the ToList step.

Array.ForEach(yourArray, Console.WriteLine);

Multiple axis line chart in excel

Best and Free ( maybe only) solution for this is google sheets. i don't know whether it plots as u expected or not but certainly you can draw multiple axes.

Regards

keerthan

Check if enum exists in Java

Just use valueOf() method. If the value doesn't exist, it throws IllegalArgumentException and you can catch it like that:

      boolean isSettingCodeValid = true;

       try {
            SettingCode.valueOf(settingCode.toUpperCase());
        } catch (IllegalArgumentException e) {
            // throw custom exception or change the isSettingCodeValid value
            isSettingCodeValid = false;
        }

AngularJS ng-style with a conditional expression

For single css property

ng-style="1==1 && {'color':'red'}"

For multiple css properties below can be referred

ng-style="1==1 && {'color':'red','font-style': 'italic'}"

Replace 1==1 with your condition expression

How to modify a CSS display property from JavaScript?

It should be document.getElementById("hidden").style.display = "block"; not document.getElementById["hidden"].style.display = "block";


EDIT due to author edit:

Why are you using a <div> here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">

Firebase Storage How to store and Retrieve images

There are a couple of ways of doing I first did the way Grendal2501 did it. I then did it similar to user15163, you can store the image URL in the firebase and host the image on your firebase host or also Amazon S3;

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

eg1:
director:Settings - Editor - Inspections - Spring - Spring Core - Code - Autowiring for Bean Class 
operate:checkout ???
eg2:
1.impl class add @service
like this:
@Service
public class CityServiceImpl implements CityService{
@Autowired
private CityDao cityDao;

like this
2.dao file class add @Repository
@Repository
public interface CityDao {

Set default format of datetimepicker as dd-MM-yyyy

You can set CustomFormat property to "dd-MM-yyyy" in design mode and use dateTimePicker1.Text property to fetch string in "dd/MM/yyyy" format irrespective of display format.

What does the return keyword do in a void method in Java?

The Java language specification says you can have return with no expression if your method returns void.

How can I export tables to Excel from a webpage

Far and away, the cleanest, easiest export from tables to Excel is Jquery DataTables Table Tools plugin. You get a grid that sorts, filters, orders, and pages your data, and with just a few extra lines of code and two small files included, you get export to Excel, PDF, CSV, to clipboard and to the printer.

This is all the code that's required:

  $(document).ready( function () {
    $('#example').dataTable( {
        "sDom": 'T<"clear">lfrtip',
        "oTableTools": {
            "sSwfPath": "/swf/copy_cvs_xls_pdf.swf"
        }
    } );
} );

So, quick to deploy, no browser limitations, no server-side language required, and most of all very EASY to understand. It's a win-win. The one thing it does have limits on, though, is strict formatting of columns.

If formatting and colors are absolute dealbreakers, the only 100% reliable, cross browser method I've found is to use a server-side language to process proper Excel files from your code. My solution of choice is PHPExcel It is the only one I've found so far that positively handles export with formatting to a MODERN version of Excel from any browser when you give it nothing but HTML. Let me clarify though, it's definitely not as easy as the first solution, and also is a bit of a resource hog. However, on the plus side it also can output direct to PDF as well. And, once you get it configured, it just works, every time.

UPDATE - September 15, 2016: TableTools has been discontinued in favor of a new plugin called "buttons" These tools perform the same functions as the old TableTools extension, but are FAR easier to install and they make use of HTML5 downloads for modern browsers, with the capability to fallback to the original Flash download for browsers that don't support the HTML5 standard. As you can see from the many comments since I posted this response in 2011, the main weakness of TableTools has been addressed. I still can't recommend DataTables enough for handling large amounts of data simply, both for the developer and the user.

Creating a PHP header/footer

Besides just using include() or include_once() to include the header and footer, one thing I have found useful is being able to have a custom page title or custom head tags to be included for each page, yet still have the header in a partial include. I usually accomplish this as follows:

In the site pages:

<?php

$PageTitle="New Page Title";

function customPageHeader(){?>
  <!--Arbitrary HTML Tags-->
<?php }

include_once('header.php');

//body contents go here

include_once('footer.php');
?>

And, in the header.php file:

<!doctype html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title><?= isset($PageTitle) ? $PageTitle : "Default Title"?></title>
    <!-- Additional tags here -->
    <?php if (function_exists('customPageHeader')){
      customPageHeader();
    }?>
  </head>
  <body>

Maybe a bit beyond the scope of your original question, but it is useful to allow a bit more flexibility with the include.

MS Access DB Engine (32-bit) with Office 64-bit

Here's a workaround for installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit MS Office version installed:

  • Check the 64-bit registry key "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" before installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable.
  • If it does not contain the "mso.dll" registry value, then you will need to rename or delete the value after installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit version of MS Office installed.
  • Use the "/passive" command line parameter to install the redistributable, e.g. "C:\directory path\AccessDatabaseEngine_x64.exe" /passive
  • Delete or rename the "mso.dll" registry value, which contains the path to the 64-bit version of MSO.DLL (and should not be used by 32-bit MS Office versions).

Now you can start a 32-bit MS Office application without the "re-configuring" issue. Note that the "mso.dll" registry value will already be present if a 64-bit version of MS Office is installed. In this case the value should not be deleted or renamed.

Also if you do not want to use the "/passive" command line parameter you can edit the AceRedist.msi file to remove the MS Office architecture check:

You can now use this file to install the Microsoft Access Database Engine 2010 redistributable on a system where a "conflicting" version of MS Office is installed (e.g. 64-bit version on system with 32-bit MS Office version) Make sure that you rename the "mso.dll" registry value as explained above (if needed).

Is it possible to modify a registry entry via a .bat/.cmd script?

Yes, you can script using the reg command. Example:

reg add HKCU\Software\SomeProduct
reg add HKCU\Software\SomeProduct /v Version /t REG_SZ /d v2.4.6

This would create key HKEY_CURRENT_USER\Software\SomeProduct, and add a String value "v2.4.6" named "Version" to that key.

reg /? has the details.

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

Try it this way, I just made some light changes:

MailMessage msg = new MailMessage();

msg.From = new MailAddress("[email protected]");
msg.To.Add("[email protected]");
msg.Subject = "test";
msg.Body = "Test Content";
//msg.Priority = MailPriority.High;


using (SmtpClient client = new SmtpClient())
{
    client.EnableSsl = true;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential("[email protected]", "mypassword");
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;

    client.Send(msg);
}

Also please show your app.config file, if you have mail settings there.

Camera access through browser

The Picup app is a way to take pictures from an HTML5 page and upload them to your server. It requires some extra programming on the server, but apart from PhoneGap, I have not found another way.

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

Using LIKE in an Oracle IN clause

I prefer this

WHERE CASE WHEN my_col LIKE '%val1%' THEN 1    
           WHEN my_col LIKE '%val2%' THEN 1
           WHEN my_col LIKE '%val3%' THEN 1
           ELSE 0
           END = 1

I'm not saying it's optimal but it works and it's easily understood. Most of my queries are adhoc used once so performance is generally not an issue for me.

HTML5 required attribute seems not working

Actually speaking, when I tried this, it worked only when I set the action and method value for the form. Funny how it works though!

Is there a way to get version from package.json in nodejs code?

Option 1

Best practice is to version from package.json using npm environment variables.

process.env.npm_package_version

more information on: https://docs.npmjs.com/using-npm/config.html

This will work only when you start your service using NPM command.

Quick Info: you can read any values in pacakge.json using process.env.npm_package_[keyname]

Option 2

Setting version in environment variable using https://www.npmjs.com/package/dotenv as .env file and reading it as process.env.version

Difference between "this" and"super" keywords in Java

From your question, I take it that you are really asking about the use of this and super in constructor chaining; e.g.

public class A extends B {
    public A(...) {
        this(...);
        ...
    }
}

versus

public class A extends B {
    public A(...) {
        super(...);
        ...
    }
}

The difference is simple:

  • The this form chains to a constructor in the current class; i.e. in the A class.

  • The super form chains to a constructor in the immediate superclass; i.e. in the B class.

Format a message using MessageFormat.format() in Java

Here is a method that does not require editing the code and works regardless of the number of characters.

String text = 
  java.text.MessageFormat.format(
    "You're about to delete {0} rows.".replaceAll("'", "''"), 5);

How to extract the year from a Python datetime object?

If you want the year from a (unknown) datetime-object:

tijd = datetime.datetime(9999, 12, 31, 23, 59, 59)

>>> tijd.timetuple()
time.struct_time(tm_year=9999, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=59, tm_sec=59, tm_wday=4, tm_yday=365, tm_isdst=-1)
>>> tijd.timetuple().tm_year
9999

How to start a background process in Python?

Use subprocess.Popen() with the close_fds=True parameter, which will allow the spawned subprocess to be detached from the Python process itself and continue running even after Python exits.

https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f

import os, time, sys, subprocess

if len(sys.argv) == 2:
    time.sleep(5)
    print 'track end'
    if sys.platform == 'darwin':
        subprocess.Popen(['say', 'hello'])
else:
    print 'main begin'
    subprocess.Popen(['python', os.path.realpath(__file__), '0'], close_fds=True)
    print 'main end'

Java: How to read a text file

read the file and then do whatever you want java8 Files.lines(Paths.get("c://lines.txt")).collect(Collectors.toList());

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.

Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx

How to uninstall a windows service and delete its files without rebooting

sc delete "service name"

will delete a service. I find that the sc utility is much easier to locate than digging around for installutil. Remember to stop the service if you have not already.

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

clear() will go through the underlying Array and set each entry to null;

removeAll(collection) will go through the ArrayList checking for collection and remove(Object) it if it exists.

I would imagine that clear() is way faster then removeAll because it's not comparing, etc.

C++ sorting and keeping track of indexes

Make a std::pair in function then sort pair :

generic version :

template< class RandomAccessIterator,class Compare >
auto sort2(RandomAccessIterator begin,RandomAccessIterator end,Compare cmp) ->
   std::vector<std::pair<std::uint32_t,RandomAccessIterator>>
{
    using valueType=typename std::iterator_traits<RandomAccessIterator>::value_type;
    using Pair=std::pair<std::uint32_t,RandomAccessIterator>;

    std::vector<Pair> index_pair;
    index_pair.reserve(std::distance(begin,end));

    for(uint32_t idx=0;begin!=end;++begin,++idx){
        index_pair.push_back(Pair(idx,begin));
    }

    std::sort( index_pair.begin(),index_pair.end(),[&](const Pair& lhs,const Pair& rhs){
          return cmp(*lhs.second,*rhs.second);
    });

    return index_pair;
}

ideone

How does @synchronized lock/unlock in Objective-C?

Actually

{
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

transforms directly into:

// needs #import <objc/objc-sync.h>
{
  objc_sync_enter(self)
    id retVal = [[myString retain] autorelease];
  objc_sync_exit(self);
  return retVal;
}

This API available since iOS 2.0 and imported using...

#import <objc/objc-sync.h>

Fatal error: Cannot use object of type stdClass as array in

if you really want an array instead you can use:

$getvidids->result_array()

which would return the same information as an associative array.

Which JRE am I using?

As you are expecting it to know using the Javascript, I believe you want to know the JRE versioned being used in your browser. Hence you can include Java version tester applet which can exactly tell you the version of the current browser.

import java.applet.*;
import java.awt.*;

public class JavaVersionDisplayApplet extends Applet
{
  private Label m_labVersionVendor;

  public JavaVersionDisplayApplet() // Constructor
  {
    Color colFrameBackground = Color.pink;
    this.setBackground(colFrameBackground);
    m_labVersionVendor = new Label (" Java Version: " +
                                   System.getProperty("java.version") +
                          " from "+System.getProperty("java.vendor"));
    this.add(m_labVersionVendor);
  }
}

How do I get a list of installed CPAN modules?

To walk through the @INC directory trees without using an external program like ls(1), one could use the File::Find::Rule module, which has a nice declarative interface.

Also, you want to filter out duplicates in case previous Perl versions contain the same modules. The code to do this looks like:

#! /usr/bin/perl -l

use strict;
use warnings;
use File::Find::Rule;

my %seen;
for my $path (@INC) {
    for my $file (File::Find::Rule->name('*.pm')->in($path)) {
        my $module = substr($file, length($path)+1);
        $module =~ s/.pm$//;
        $module =~ s{[\\/]}{::}g;
        print $module unless $seen{$module}++;
    }
}

At the end of the run, you also have all your module names as keys in the %seen hash. The code could be adapted to save the canonical filename (given in $file) as the value of the key instead of a count of times seen.

C# - Create SQL Server table programmatically

If you don't like remembering SQL syntax, using Mig# you can simply:

var schema = new DbSchema(ConnectionString, DbPlatform.SqlServer2014);
schema.Alter(db => db.CreateTable("Customer")
     .WithPrimaryKeyColumn("Id", DbType.Int32).AsIdentity()
     .WithNotNullableColumn("First_Name", DbType.String).OfSize(50)
     .WithNotNullableColumn("Last_Name", DbType.String).OfSize(50)
     ...);

If you are not sure if it already exists, call DropIfExists before:

db.Tables["Customers"].DropIfExists();

Finding row index containing maximum value using R

How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:

row(y)[y==max(y)]

if you want to extract the row:

y[row(y)[y==max(y)],] # this returns unsorted rows.

To return sorted rows use:

y[sort(row(y)[y==max(y)]),]

The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y) and location of the hanging comma you can also extract columns.

y[,col(y)[y==max(y)]]

To find just the row for the max in a particular column, say column 2 you could use:

seq(along=y[,2])[y[,2]==max(y[,2])]

again the conditional is flexible to look for different requirements.

See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.

How to write a simple Java program that finds the greatest common divisor between two numbers?

Now, I just started programing about a week ago, so nothing fancy, but I had this as a problem and came up with this, which may be easier for people who are just getting into programing to understand. It uses Euclid's method like in previous examples.

public class GCD {
  public static void main(String[] args){
    int x = Math.max(Integer.parseInt(args[0]),Integer.parseInt(args[1]));    
    int y = Math.min(Integer.parseInt(args[0]),Integer.parseInt(args[1]));     
    for (int r = x % y; r != 0; r = x % y){
      x = y;
      y = r;
    }
    System.out.println(y);
  }
}

How to return result of a SELECT inside a function in PostgreSQL?

Hi please check the below link

https://www.postgresql.org/docs/current/xfunc-sql.html

EX:

CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

500 internal server error at GetResponse()

For me this error occurred because I had 2 web API actions that had the exact same signatures and both had the same verbs, HttpPost, what I did was change one of the verbs (the one used for updating) to PUT and the error was removed. The following in my catch statement helped in getting to the root of the problem:

catch (WebException webex)
{
                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string text = reader.ReadToEnd();
                }
}

How does "make" app know default target to build if no target is specified?

To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:

.DEFAULT_GOAL := mytarget

mytarget will now be the target that is run if "make" is executed and no target is specified.

If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:

.PHONY: default
default: mytarget ;

References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html

How do I add records to a DataGridView in VB.Net?

If your DataGridView is bound to a DataSet, you can not just add a new row in your DataGridView display. It will now work properly.

Instead you should add the new row in the DataSet with this code:

BindingSource[Name].AddNew()

This code will also automatically add a new row in your DataGridView display.

Maven: How do I activate a profile from command line?

Just remove activation section, I don't know why -Pdev1 doesn't override default false activation. But if you omit this:

<activation> <activeByDefault>false</activeByDefault> </activation>

then your profile will be activated only after explicit declaration as -Pdev1

Injecting Mockito mocks into a Spring bean

Update: There are now better, cleaner solutions to this problem. Please consider the other answers first.

I eventually found an answer to this by ronen on his blog. The problem I was having is due to the method Mockito.mock(Class c) declaring a return type of Object. Consequently Spring is unable to infer the bean type from the factory method return type.

Ronen's solution is to create a FactoryBean implementation that returns mocks. The FactoryBean interface allows Spring to query the type of objects created by the factory bean.

My mocked bean definition now looks like:

<bean id="mockDaoFactory" name="dao" class="com.package.test.MocksFactory">
    <property name="type" value="com.package.Dao" />
</bean>

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

If you place the dollar sign before the letter, you will affect only the column, not the row. If you want to have it affect only a row, place the dollar before the number.

You may want to use =isblank() rather than =""

I'm also confused by your comment "no values throughout spreadsheet - just text" - text is a value.

One more hint - excel has a habit of rewriting rules - I don't know how many rules I've written only to discover that excel has changed the values in the "apply to" or formula entry fields.

If you could post an example, I'll revise the answer. Conditional formatting is very finicky.

Get a list of resources from classpath directory

Based on @rob 's information above, I created the implementation which I am releasing to the public domain:

private static List<String> getClasspathEntriesByPath(String path) throws IOException {
    InputStream is = Main.class.getClassLoader().getResourceAsStream(path);

    StringBuilder sb = new StringBuilder();
    while (is.available()>0) {
        byte[] buffer = new byte[1024];
        sb.append(new String(buffer, Charset.defaultCharset()));
    }

    return Arrays
            .asList(sb.toString().split("\n"))          // Convert StringBuilder to individual lines
            .stream()                                   // Stream the list
            .filter(line -> line.trim().length()>0)     // Filter out empty lines
            .collect(Collectors.toList());              // Collect remaining lines into a List again
}

While I would not have expected getResourcesAsStream to work like that on a directory, it really does and it works well.

Pandas get the most frequent values of a column

By using mode

df.name.mode()
Out[712]: 
0     alex
1    helen
dtype: object

How to add an extra column to a NumPy array

I was also interested in this question and compared the speed of

numpy.c_[a, a]
numpy.stack([a, a]).T
numpy.vstack([a, a]).T
numpy.ascontiguousarray(numpy.stack([a, a]).T)               
numpy.ascontiguousarray(numpy.vstack([a, a]).T)
numpy.column_stack([a, a])
numpy.concatenate([a[:,None], a[:,None]], axis=1)
numpy.concatenate([a[None], a[None]], axis=0).T

which all do the same thing for any input vector a. Timings for growing a:

enter image description here

Note that all non-contiguous variants (in particular stack/vstack) are eventually faster than all contiguous variants. column_stack (for its clarity and speed) appears to be a good option if you require contiguity.


Code to reproduce the plot:

import numpy
import perfplot

perfplot.save(
    "out.png",
    setup=lambda n: numpy.random.rand(n),
    kernels=[
        lambda a: numpy.c_[a, a],
        lambda a: numpy.ascontiguousarray(numpy.stack([a, a]).T),
        lambda a: numpy.ascontiguousarray(numpy.vstack([a, a]).T),
        lambda a: numpy.column_stack([a, a]),
        lambda a: numpy.concatenate([a[:, None], a[:, None]], axis=1),
        lambda a: numpy.ascontiguousarray(
            numpy.concatenate([a[None], a[None]], axis=0).T
        ),
        lambda a: numpy.stack([a, a]).T,
        lambda a: numpy.vstack([a, a]).T,
        lambda a: numpy.concatenate([a[None], a[None]], axis=0).T,
    ],
    labels=[
        "c_",
        "ascont(stack)",
        "ascont(vstack)",
        "column_stack",
        "concat",
        "ascont(concat)",
        "stack (non-cont)",
        "vstack (non-cont)",
        "concat (non-cont)",
    ],
    n_range=[2 ** k for k in range(20)],
    xlabel="len(a)",
    logx=True,
    logy=True,
)

is python capable of running on multiple cores?

The answer is "Yes, But..."

But cPython cannot when you are using regular threads for concurrency.

You can either use something like multiprocessing, celery or mpi4py to split the parallel work into another process;

Or you can use something like Jython or IronPython to use an alternative interpreter that doesn't have a GIL.

A softer solution is to use libraries that don't run afoul of the GIL for heavy CPU tasks, for instance numpy can do the heavy lifting while not retaining the GIL, so other python threads can proceed. You can also use the ctypes library in this way.

If you are not doing CPU bound work, you can ignore the GIL issue entirely (kind of) since python won't aquire the GIL while it's waiting for IO.

How do I restart a service on a remote machine in Windows?

Well, if you have Visual Studio (I know it's in 2005, not sure about earlier versions though), you can add the remote machine to your "Server Explorer" tag. At that point, you'll have access to the SERVICES that are running, or can be ran, from that machine (as well as event logs, and queues, and a couple other interesting things).

Get ASCII value at input word

There is a major gotcha associated with getting an ASCII code of a char value.

In the proper sense, it can't be done.

It's because char has a range of 65535 whereas ASCII is restricted to 128. There is a huge amount of characters that have no ASCII representation at all.

The proper way would be to use a Unicode code point which is the standard numerical equivalent of a character in the Java universe.

Thankfully, Unicode is a complete superset of ASCII. That means Unicode numbers for Latin characters are equal to their ASCII counterparts. For example, A in Unicode is U+0041 or 65 in decimal. In contrast, ASCII has no mapping for 99% of char-s. Long story short:

char ch = 'A';
int cp = String.valueOf(ch).codePointAt(0);

Furthermore, a 16-bit primitive char actually represents a code unit, not a character and is thus restricted to Basic Multilingual Plane, for historical reasons. Entities beyond it require Character objects which deal away with the fixed bit-length limitation.

Format Date output in JSF

If you use OmniFaces you can also use it's EL functions like of:formatDate() to format Date objects. You would use it like this:

<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />

This way you can not only use it for output but also to pass it on to other JSF components.

Carriage return in C?

Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

Compare a string using sh shell

-eq is a mathematical comparison operator. I've never used it for string comparison, relying on == and != for compares.

if [ 'XYZ' == 'ABC' ]; then   # Double equal to will work in Linux but not on HPUX boxes it should be if [ 'XYZ' = 'ABC' ] which will work on both
  echo "Match"
else
  echo "No Match"
fi

HSL to RGB color conversion

PHP - shortest but precise

Here I rewrite my JS answer (math details are there) to PHP - you can run it here

function hsl2rgb($h,$s,$l) 
{
  $a = $s * min($l, 1-$l);
  $k = function($n,$h) { return ($n+$h/30)%12;};
  $f = function($n) use ($h,$s,$l,$a,$k) { 
      return $l - $a * max( min($k($n,$h)-3, 9-$k($n,$h), 1),-1);
  };
  return [ $f(0), $f(8), $f(4) ];
}   

Java: unparseable date exception

From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:

String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);

Next step is parse stringDate to Date:

Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);

Note that, parse method throws ParseException

How do you POST to a page using the PHP header() function?

There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/

XML to CSV Using XSLT

Found an XML transform stylesheet here (wayback machine link, site itself is in german)

The stylesheet added here could be helpful:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>

<xsl:strip-space elements="*" />

<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>",    </xsl:if>
<xsl:if test="position()  = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>&#xD;</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.

Unsupported major.minor version 52.0 in my app

What no one here is saying is that with Build Tools 24.0.0, Java 8 is required and most people have either 1.6 or 1.7.

So yeah, setting the build tool to 23.x.x would 'solve' the problem but the root cause is the Java version on your system.

On the long term, you might want to upgrade your dev environment to use JDK8 to make use the new language enhancements and the jack compiler.

How to find the length of a string in R

nchar(YOURSTRING)

you may need to convert to a character vector first;

nchar(as.character(YOURSTRING))

Regex to check with starts with http://, https:// or ftp://

You need a whole input match here.

System.out.println(test.matches("^(http|https|ftp)://.*$")); 

Edit:(Based on @davidchambers's comment)

System.out.println(test.matches("^(https?|ftp)://.*$")); 

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

use

Date date = new Date();
String strDate = sdf.format(date);

intead Of

Calendar cal = Calendar.getInstance();
String strDate = sdf.format(cal.getTime());

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

To pull a remote branch locally, I do the following:

git checkout -b branchname // creates a local branch with the same name and checks out on it

git pull origin branchname // pulls the remote one onto your local one

The only time I did this and it didn't work, I deleted the repo, cloned it again and repeated the above 2 steps; it worked.

Datatables Select All Checkbox

Base on Francisco Daniel's answer I modified some of the Jquery code here's My version. I removed some excess code and use "fa" instead of "far" for the icon. I also remove the "far fa-minus-square" since I can't understand its purpose.

-- Edited --

I added the "draw" event for the button icon to update whenever the table is redrawn or reloaded. Because I noticed when I tried to reload the table using "myTable.ajax.reload()" the button icon is not changing.

https://codepen.io/john-kenneth-larbo/pen/zXeYpz

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    let myTable = $('#example').DataTable({_x000D_
        columnDefs: [{_x000D_
            orderable: false,_x000D_
            className: 'select-checkbox',_x000D_
            targets: 0,_x000D_
        }],_x000D_
        select: {_x000D_
            style: 'os', // 'single', 'multi', 'os', 'multi+shift'_x000D_
            selector: 'td:first-child',_x000D_
        },_x000D_
        order: [_x000D_
            [1, 'asc'],_x000D_
        ],_x000D_
    });_x000D_
_x000D_
       myTable.on('select deselect draw', function () {_x000D_
        var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
        var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
        if (selectedRows < all) {_x000D_
            $('#MyTableCheckAllButton i').attr('class', 'fa fa-square-o');_x000D_
        } else {_x000D_
            $('#MyTableCheckAllButton i').attr('class', 'fa fa-check-square-o');_x000D_
        }_x000D_
_x000D_
    });_x000D_
_x000D_
    $('#MyTableCheckAllButton').click(function () {_x000D_
        var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
        var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
_x000D_
        if (selectedRows < all) {_x000D_
            //Added search applied in case user wants the search items will be selected_x000D_
            myTable.rows({ search: 'applied' }).deselect();_x000D_
            myTable.rows({ search: 'applied' }).select();_x000D_
        } else {_x000D_
            myTable.rows({ search: 'applied' }).deselect();_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<table id="example" class="display" style="width:100%">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th>_x000D_
                <button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">_x000D_
                <i class="far fa-square"></i>  _x000D_
                </button>_x000D_
            </th>_x000D_
            <th>Name</th>_x000D_
            <th>Position</th>_x000D_
            <th>Office</th>_x000D_
            <th>Age</th>_x000D_
            <th>Salary</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Tiger Nixon</td>_x000D_
            <td>System Architect</td>_x000D_
            <td>Edinburgh</td>_x000D_
            <td>61</td>_x000D_
            <td>$320,800</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Garrett Winters</td>_x000D_
            <td>Accountant</td>_x000D_
            <td>Tokyo</td>_x000D_
            <td>63</td>_x000D_
            <td>$170,750</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Ashton Cox</td>_x000D_
            <td>Junior Technical Author</td>_x000D_
            <td>San Francisco</td>_x000D_
            <td>66</td>_x000D_
            <td>$86,000</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Cedric Kelly</td>_x000D_
            <td>Senior Javascript Developer</td>_x000D_
            <td>Edinburgh</td>_x000D_
            <td>22</td>_x000D_
            <td>$433,060</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Airi Satou</td>_x000D_
            <td>Accountant</td>_x000D_
            <td>Tokyo</td>_x000D_
            <td>33</td>_x000D_
            <td>$162,700</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Brielle Williamson</td>_x000D_
            <td>Integration Specialist</td>_x000D_
            <td>New York</td>_x000D_
            <td>61</td>_x000D_
            <td>$372,000</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Herrod Chandler</td>_x000D_
            <td>Sales Assistant</td>_x000D_
            <td>San Francisco</td>_x000D_
            <td>59</td>_x000D_
            <td>$137,500</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Rhona Davidson</td>_x000D_
            <td>Integration Specialist</td>_x000D_
            <td>Tokyo</td>_x000D_
            <td>55</td>_x000D_
            <td>$327,900</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Colleen Hurst</td>_x000D_
            <td>Javascript Developer</td>_x000D_
            <td>San Francisco</td>_x000D_
            <td>39</td>_x000D_
            <td>$205,500</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Sonya Frost</td>_x000D_
            <td>Software Engineer</td>_x000D_
            <td>Edinburgh</td>_x000D_
            <td>23</td>_x000D_
            <td>$103,600</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td></td>_x000D_
            <td>Jena Gaines</td>_x000D_
            <td>Office Manager</td>_x000D_
            <td>London</td>_x000D_
            <td>30</td>_x000D_
            <td>$90,560</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
    <tfoot>_x000D_
        <tr>_x000D_
            <th></th>_x000D_
            <th>Name</th>_x000D_
            <th>Position</th>_x000D_
            <th>Office</th>_x000D_
            <th>Age</th>_x000D_
            <th>Salary</th>_x000D_
        </tr>_x000D_
    </tfoot>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Reset ID autoincrement ? phpmyadmin

ALTER TABLE xxx AUTO_INCREMENT =1; or clear your table by TRUNCATE

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

CSS: Auto resize div to fit container width

#wrapper
{
    min-width:960px;
    margin-left:auto;
    margin-right:auto;
    position-relative;
}
#left
{
    width:200px;
    position: absolute;
    background-color:antiquewhite;
    margin-left:10px;
    z-index: 2;
}
#content
{
    padding-left:210px;
    width:100%;
    background-color:AppWorkspace;
    position: relative;
    z-index: 1;
}

If you need the whitespace on the right of #left, then add a border-right: 10px solid #FFF; to #left and add 10px to the padding-left in #content

Escaping backslash in string - javascript

I think this is closer to the answer you're looking for:

<input type="file">

$file = $(file);
var filename = fileElement[0].files[0].name;

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

You should trigger the animation to revert once it's completed w/ javascript.

  $(".item").live("animationend webkitAnimationEnd", function(){
    $(this).removeClass('animate');
  });

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;
}

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

How to trigger click on page load?

You can do the following :-

$(document).ready(function(){
    $("#id").trigger("click");
});

Having services in React application

I am from Angular as well and trying out React, as of now, one recommended(?) way seems to be using High-Order Components:

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

Let's say you have input and textarea and like to apply the same validation logic:

const Input = (props) => (
  <input type="text"
    style={props.style}
    onChange={props.onChange} />
)
const TextArea = (props) => (
  <textarea rows="3"
    style={props.style}
    onChange={props.onChange} >
  </textarea>
)

Then write a HOC that does validate and style wrapped component:

function withValidator(WrappedComponent) {
  return class extends React.Component {
    constructor(props) {
      super(props)

      this.validateAndStyle = this.validateAndStyle.bind(this)
      this.state = {
        style: {}
      }
    }

    validateAndStyle(e) {
      const value = e.target.value
      const valid = value && value.length > 3 // shared logic here
      const style = valid ? {} : { border: '2px solid red' }
      console.log(value, valid)
      this.setState({
        style: style
      })
    }

    render() {
      return <WrappedComponent
        onChange={this.validateAndStyle}
        style={this.state.style}
        {...this.props} />
    }
  }
}

Now those HOCs share the same validating behavior:

const InputWithValidator = withValidator(Input)
const TextAreaWithValidator = withValidator(TextArea)

render((
  <div>
    <InputWithValidator />
    <TextAreaWithValidator />
  </div>
), document.getElementById('root'));

I created a simple demo.

Edit: Another demo is using props to pass an array of functions so that you can share logic composed by multiple validating functions across HOCs like:

<InputWithValidator validators={[validator1,validator2]} />
<TextAreaWithValidator validators={[validator1,validator2]} />

Edit2: React 16.8+ provides a new feature, Hook, another nice way to share logic.

const Input = (props) => {
  const inputValidation = useInputValidation()

  return (
    <input type="text"
    {...inputValidation} />
  )
}

function useInputValidation() {
  const [value, setValue] = useState('')
  const [style, setStyle] = useState({})

  function handleChange(e) {
    const value = e.target.value
    setValue(value)
    const valid = value && value.length > 3 // shared logic here
    const style = valid ? {} : { border: '2px solid red' }
    console.log(value, valid)
    setStyle(style)
  }

  return {
    value,
    style,
    onChange: handleChange
  }
}

https://stackblitz.com/edit/react-shared-validation-logic-using-hook?file=index.js

Compare two objects in Java with possible null values

Since version 3.5 Apache Commons StringUtils has the following methods:

static int  compare(String str1, String str2)
static int  compare(String str1, String str2, boolean nullIsLess)
static int  compareIgnoreCase(String str1, String str2)
static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)

These provide null safe String comparison.

Get viewport/window height in ReactJS

Answers by @speckledcarp and @Jamesl are both brilliant. In my case, however, I needed a component whose height could extend the full window height, conditional at render time.... but calling a HOC within render() re-renders the entire subtree. BAAAD.

Plus, I wasn't interested in getting the values as props but simply wanted a parent div that would occupy the entire screen height (or width, or both).

So I wrote a Parent component providing a full height (and/or width) div. Boom.

A use case:

class MyPage extends React.Component {
  render() {
    const { data, ...rest } = this.props

    return data ? (
      // My app uses templates which misbehave badly if you manually mess around with the container height, so leave the height alone here.
      <div>Yay! render a page with some data. </div>
    ) : (
      <FullArea vertical>
        // You're now in a full height div, so containers will vertically justify properly
        <GridContainer justify="center" alignItems="center" style={{ height: "inherit" }}>
          <GridItem xs={12} sm={6}>
            Page loading!
          </GridItem>
        </GridContainer>
      </FullArea>
    )

Here's the component:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class FullArea extends Component {
  constructor(props) {
    super(props)
    this.state = {
      width: 0,
      height: 0,
    }
    this.getStyles = this.getStyles.bind(this)
    this.updateWindowDimensions = this.updateWindowDimensions.bind(this)
  }

  componentDidMount() {
    this.updateWindowDimensions()
    window.addEventListener('resize', this.updateWindowDimensions)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateWindowDimensions)
  }

  getStyles(vertical, horizontal) {
    const styles = {}
    if (vertical) {
      styles.height = `${this.state.height}px`
    }
    if (horizontal) {
      styles.width = `${this.state.width}px`
    }
    return styles
  }

  updateWindowDimensions() {
    this.setState({ width: window.innerWidth, height: window.innerHeight })
  }

  render() {
    const { vertical, horizontal } = this.props
    return (
      <div style={this.getStyles(vertical, horizontal)} >
        {this.props.children}
      </div>
    )
  }
}

FullArea.defaultProps = {
  horizontal: false,
  vertical: false,
}

FullArea.propTypes = {
  horizontal: PropTypes.bool,
  vertical: PropTypes.bool,
}

export default FullArea

Detecting installed programs via registry

User-specific settings should be written to HKCU\Software, machine-specific settings to HKLM\Software. Under these keys, structure [software vendor name]\[application name] (e.g. HKLM\Software\Microsoft\Internet Explorer) may be the most common, but that's just a convention, not a law of nature.

Many (most?) applications also add their uninstall entries to HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\[app name], but again, not all applications do this.

These are the most important keys; however, contents of the registry do not have to represent the installed software exactly - maybe the application was installed once, but then was manually deleted, or maybe the uninstaller didn't remove all traces of it. If you want to be sure, check the filesystem to see if the application still exists where its registry entries say it is.

Edit:

If you're a member of the group Administrators, you can check the HKEY_USERS hive - each user's HKCU actually resides there (you'll need to know the user SID, or go through all of them).

Note: As @Brian Ensink says, "installed" is a bit of a vague concept - are we trying to find what the user could run? Some software doesn't even write to the Registry at all: search for "portable apps" to see apps that have been specifically modified to run directly from media (CD/USB) and not to leave any traces on the computer. We may also have to scan the disks, and network disks, and anything the user downloads, and world-accessible Windows shares in the Internet (yes, such things exist legitimately - \\live.sysinternals.com\tools comes to mind). In this direction, there's no real limit of what the user can run, unless prevented by system policies.

How to map an array of objects in React

try the following snippet

const renObjData = this.props.data.map(function(data, idx) {
    return <ul key={idx}>{$.map(data,(val,ind) => {
        return (<li>{val}</li>);
    }
    }</ul>;
});

jQuery toggle CSS?

For jQuery versions lower than 1.9 (see https://api.jquery.com/toggle-event):

$('#user_button').toggle(function () {
    $("#user_button").css({borderBottomLeftRadius: "0px"});
}, function () {
    $("#user_button").css({borderBottomLeftRadius: "5px"});
});

Using classes in this case would be better than setting the css directly though, look at the addClass and removeClass methods alecwh mentioned.

$('#user_button').toggle(function () {
    $("#user_button").addClass("active");
}, function () {
    $("#user_button").removeClass("active");
});

Android activity life cycle - what are all these methods for?

From the Android Developers page,

onPause():

Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

onStop():

Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.

The paused Activity gets a Resume and Stopped gets Restarted.

When you call this.finish(), onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.

I hope it's clear enough.

How can I center an image in Bootstrap?

Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto. This can be done with built-in .d-block:

<div class="container">
    <div class="row">
        <div class="col-4">
            <img class="mx-auto d-block" src="...">  
        </div>
    </div>
</div>

Or leave it as inline-block and wrapped it in a div with .text-center:

<div class="container">
    <div class="row">
        <div class="col-4">
          <div class="text-center">
            <img src="..."> 
          </div>     
        </div>
    </div>
</div>

I made a fiddle showing both ways. They are documented here as well.

MySQL user DB does not have password columns - Installing MySQL on OSX

In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'.

First choose the database:

mysql>use mysql;

And then show the tables:

mysql>show tables;

You will find the user table, now let's see its fields:

mysql> describe user;
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                  | Type                              | Null | Key | Default               | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                   | char(60)                          | NO   | PRI |                       |       |
| User                   | char(16)                          | NO   | PRI |                       |       |
| Select_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Insert_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Update_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Delete_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Create_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Drop_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Reload_priv            | enum('N','Y')                     | NO   |     | N                     |       |
| Shutdown_priv          | enum('N','Y')                     | NO   |     | N                     |       |
| Process_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| File_priv              | enum('N','Y')                     | NO   |     | N                     |       |
| Grant_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| References_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Index_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Show_db_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Super_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tmp_table_priv  | enum('N','Y')                     | NO   |     | N                     |       |
| Lock_tables_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Execute_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_slave_priv        | enum('N','Y')                     | NO   |     | N                     |       |
| Repl_client_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Create_view_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Show_view_priv         | enum('N','Y')                     | NO   |     | N                     |       |
| Create_routine_priv    | enum('N','Y')                     | NO   |     | N                     |       |
| Alter_routine_priv     | enum('N','Y')                     | NO   |     | N                     |       |
| Create_user_priv       | enum('N','Y')                     | NO   |     | N                     |       |
| Event_priv             | enum('N','Y')                     | NO   |     | N                     |       |
| Trigger_priv           | enum('N','Y')                     | NO   |     | N                     |       |
| Create_tablespace_priv | enum('N','Y')                     | NO   |     | N                     |       |
| ssl_type               | enum('','ANY','X509','SPECIFIED') | NO   |     |                       |       |
| ssl_cipher             | blob                              | NO   |     | NULL                  |       |
| x509_issuer            | blob                              | NO   |     | NULL                  |       |
| x509_subject           | blob                              | NO   |     | NULL                  |       |
| max_questions          | int(11) unsigned                  | NO   |     | 0                     |       |
| max_updates            | int(11) unsigned                  | NO   |     | 0                     |       |
| max_connections        | int(11) unsigned                  | NO   |     | 0                     |       |
| max_user_connections   | int(11) unsigned                  | NO   |     | 0                     |       |
| plugin                 | char(64)                          | NO   |     | mysql_native_password |       |
| authentication_string  | text                              | YES  |     | NULL                  |       |
| password_expired       | enum('N','Y')                     | NO   |     | N                     |       |
| password_last_changed  | timestamp                         | YES  |     | NULL                  |       |
| password_lifetime      | smallint(5) unsigned              | YES  |     | NULL                  |       |
| account_locked         | enum('N','Y')                     | NO   |     | N                     |       |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
45 rows in set (0.00 sec)

Surprise!There is no field named 'password', the password field is named ' authentication_string'. So, just do this:

update user set authentication_string=password('1111') where user='root';

Now, everything will be ok.

Compared to MySQL 5.6, the changes are quite extensive: What’s New in MySQL 5.7

PHP: date function to get month of the current date

As it's not specified if you mean the system's current date or the date held in a variable, I'll answer for latter with an example.

<?php
$dateAsString = "Wed, 11 Apr 2018 19:00:00 -0500";

// This converts it to a unix timestamp so that the date() function can work with it.
$dateAsUnixTimestamp = strtotime($dateAsString);

// Output it month is various formats according to http://php.net/date

echo date('M',$dateAsUnixTimestamp);
// Will output Apr

echo date('n',$dateAsUnixTimestamp);
// Will output 4

echo date('m',$dateAsUnixTimestamp);
// Will output 04
?>

Model summary in pytorch

Keras like model summary using torchsummary:

from torchsummary import summary
summary(model, input_size=(3, 224, 224))

How do I mock a service that returns promise in AngularJS Jasmine unit test?

I'm not sure why the way you did it doesn't work, but I usually do it with the spyOn function. Something like this:

describe('Testing remote call returning promise', function() {
  var myService;

  beforeEach(module('app.myService'));

  beforeEach(inject( function(_myService_, myOtherService, $q){
    myService = _myService_;
    spyOn(myOtherService, "makeRemoteCallReturningPromise").and.callFake(function() {
        var deferred = $q.defer();
        deferred.resolve('Remote call result');
        return deferred.promise;
    });
  }

  it('can do remote call', inject(function() {
    myService.makeRemoteCall()
      .then(function() {
        console.log('Success');
      });    
  }));

Also remember that you will need to make a $digest call for the then function to be called. See the Testing section of the $q documentation.

------EDIT------

After looking closer at what you're doing, I think I see the problem in your code. In the beforeEach, you're setting myOtherServiceMock to a whole new object. The $provide will never see this reference. You just need to update the existing reference:

beforeEach(inject( function(_myService_, $q){
    myService = _myService_;
    myOtherServiceMock.makeRemoteCallReturningPromise = function() {
        var deferred = $q.defer();
        deferred.resolve('Remote call result');
        return deferred.promise;   
    };
  }

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?

CKEditor instance already exists

you don't need to destroy the object CKeditor, you need remove() :

Change this :

CKEDITOR.instances['textarea_name'].destroy();

for that :

CKEDITOR.remove(CKEDITOR.instances['textarea_name']);

Altering column size in SQL Server

Select table--> Design--> change value in Data Type shown in following Fig.

enter image description here

Save tables design.

"echo -n" prints "-n"

Just for the most popular linux Ubuntu & it's bash:

  1. Check which shell are you using? Mostly below works, else see this:

    echo $0

  2. If above prints bash, then below will work:

    printf "hello with no new line printed at end"
    OR
    echo -n "hello with no new line printed at end"

IntelliJ: Error:java: error: release version 5 not supported

See https://stackoverflow.com/a/12900859/104891.

First of all, set the language level/release versions in pom.xml like that:

<properties>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Maven sets the default to 1.5 otherwise. You will also need to include the maven-compiler-plugin if you haven't already:

<dependency>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.8.1</version>
</dependency>

Also, try to change the Java version in each of these places:

File -> Project structure -> Project -> Project SDK -> 11.

File -> Project structure -> Project -> Project language level -> 11.

File -> Project structure -> Project -> Modules -> -> Sources --> 11

In project -> ctrl + alt + s -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Project bytecode version -> 11

In project -> ctrl + alt + s -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Module -> 1.11.

Passing a 2D array to a C++ function

Single dimensional array decays to a pointer pointer pointing to the first element in the array. While a 2D array decays to a pointer pointing to first row. So, the function prototype should be -

void myFunction(double (*myArray) [10]);

I would prefer std::vector over raw arrays.

Operation must use an updatable query. (Error 3073) Microsoft Access

check your DB (Database permission) and give full permission

Go to DB folder-> right click properties->security->edit-> give full control & Start menu ->run->type "uac" make it down (if it high)

Server Error in '/' Application. ASP.NET

Looks like you have <authentication mode="Windows" /> in your web.config file but your hosting provider won't let you use that. Just remove that line.

Download old version of package with NuGet

As the original question does not state which NuGet frontend should be used, I would like to mention that NuGet 3.5 adds support for updating to a specific version via the command line client (which works for downgrades, too):

NuGet.exe update Common.Logging -Version 1.2.0

How do I disable directory browsing?

This is not an answer, just my experience:

On my Ubuntu 12.04 apache2, didn't find Indexes in either apache2.conf or httpd.conf, luckily I found it in sites-available/default. After removing it, now it doesn't see directory listing. May have to do it for sites-available/default-ssl.

Why Maven uses JDK 1.6 but my java -version is 1.7

Please check the compatibility. I struggled with mvn 3.2.1 and jdk 1.6.0_37 for many hours. All variables were set but was not working. Finally I upgraded jdk to 1.8.0_60 and mvn 3.3.3 and that worked. Environment Variables as following:

JAVA_HOME=C:\ProgramFiles\Java\jdk1.8.0_60 
MVN_HOME=C:\ProgramFiles\apache-maven\apache-maven-3.3.3 
M2=%MVN_HOME%\bin extend system level Path- ;%M2%;%JAVA_HOME%\bin;

Getting time and date from timestamp with php

If you dont want to change the format of date and time from the timestamp, you can use the explode function in php

$timestamp = "2012-04-02 02:57:54"
$datetime = explode(" ",$timestamp);
$date = $datetime[0];
$time = $datetime[1];

Hide element by class in pure Javascript

document.getElementsByClassName returns an HTMLCollection(an array-like object) of all elements matching the class name. The style property is defined for Element not for HTMLCollection. You should access the first element using the bracket(subscript) notation.

document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';

Updated jsFiddle

To change the style rules of all elements matching the class, using the Selectors API:

[].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
  el.style.visibility = 'hidden';
});

If for...of is available:

for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';

Animate visibility modes, GONE and VISIBLE

This is a quite old question, still comments show, that still people have problems, so here is my solution with following additional features:

  • adjust the animation (speed, type, ...)
  • does not need to extend any class
  • in my case, animateLayoutChanges has problems in the new CoordinatorLayout

Function - Example (I have this function in an utility class)

public static void animateViewVisibility(final View view, final int visibility)
{
    // cancel runnning animations and remove and listeners
    view.animate().cancel();
    view.animate().setListener(null);

    // animate making view visible
    if (visibility == View.VISIBLE)
    {
        view.animate().alpha(1f).start();
        view.setVisibility(View.VISIBLE);
    }
    // animate making view hidden (HIDDEN or INVISIBLE)
    else
    {
        view.animate().setListener(new AnimatorListenerAdapter()
        {
            @Override
            public void onAnimationEnd(Animator animation)
            {
                view.setVisibility(visibility);
            }
        }).alpha(0f).start();
    }
}

Adjust animation

After calling view.animate() you can adjust the animation to whatever you want (set duration, set interpolator and more...). You may as well hide a view by scaling it instead of adjusting it's alpha value, just replace the alpha(...) with scaleX(...) or scaleY(...) in the utility method if you want that

How to detect the OS from a Bash script?

$OSTYPE

You can simply use pre-defined $OSTYPE variable e.g.:

case "$OSTYPE" in
  solaris*) echo "SOLARIS" ;;
  darwin*)  echo "OSX" ;; 
  linux*)   echo "LINUX" ;;
  bsd*)     echo "BSD" ;;
  msys*)    echo "WINDOWS" ;;
  *)        echo "unknown: $OSTYPE" ;;
esac

However it's not recognized by the older shells (such as Bourne shell).


uname

Another method is to detect platform based on uname command.

See the following script (ready to include in .bashrc):

# Detect the platform (similar to $OSTYPE)
OS="`uname`"
case $OS in
  'Linux')
    OS='Linux'
    alias ls='ls --color=auto'
    ;;
  'FreeBSD')
    OS='FreeBSD'
    alias ls='ls -G'
    ;;
  'WindowsNT')
    OS='Windows'
    ;;
  'Darwin') 
    OS='Mac'
    ;;
  'SunOS')
    OS='Solaris'
    ;;
  'AIX') ;;
  *) ;;
esac

You can find some practical example in my .bashrc.


Here is similar version used on Travis CI:

case $(uname | tr '[:upper:]' '[:lower:]') in
  linux*)
    export TRAVIS_OS_NAME=linux
    ;;
  darwin*)
    export TRAVIS_OS_NAME=osx
    ;;
  msys*)
    export TRAVIS_OS_NAME=windows
    ;;
  *)
    export TRAVIS_OS_NAME=notset
    ;;
esac

How can I get the active screen dimensions?

Add on to ffpf

Screen.FromControl(this).Bounds

Changing fonts in ggplot2

A simple answer if you don't want to install anything new

To change all the fonts in your plot plot + theme(text=element_text(family="mono")) Where mono is your chosen font.

List of default font options:

  • mono
  • sans
  • serif
  • Courier
  • Helvetica
  • Times
  • AvantGarde
  • Bookman
  • Helvetica-Narrow
  • NewCenturySchoolbook
  • Palatino
  • URWGothic
  • URWBookman
  • NimbusMon
  • URWHelvetica
  • NimbusSan
  • NimbusSanCond
  • CenturySch
  • URWPalladio
  • URWTimes
  • NimbusRom

R doesn't have great font coverage and, as Mike Wise points out, R uses different names for common fonts.

This page goes through the default fonts in detail.

Sending JWT token in the headers with Postman

I had the same issue in Flask and after trying the first 2 solutions which are the same (Authorization: Bearer <token>), and getting this:

{
    "description": "Unsupported authorization type",
    "error": "Invalid JWT header",
    "status_code": 401
}

I managed to finally solve it by using:

Authorization: jwt <token>

Thought it might save some time to people who encounter the same thing.

How to get exception message in Python properly

from traceback import format_exc


try:
    fault = 10/0
except ZeroDivision:
    print(format_exc())

Another possibility is to use the format_exc() method from the traceback module.

Git - push current branch shortcut

The simplest way: run git push -u origin feature/123-sandbox-tests once. That pushes the branch the way you're used to doing it and also sets the upstream tracking info in your local config. After that, you can just git push to push tracked branches to their upstream remote(s).

You can also do this in the config yourself by setting branch.<branch name>.merge to the remote branch name (in your case the same as the local name) and optionally, branch.<branch name>.remote to the name of the remote you want to push to (defaults to origin). If you look in your config, there's most likely already one of these set for master, so you can follow that example.

Finally, make sure you consider the push.default setting. It defaults to "matching", which can have undesired and unexpected results. Most people I know find "upstream" more intuitive, which pushes only the current branch.

Details on each of these settings can be found in the git-config man page.

On second thought, on re-reading your question, I think you know all this. I think what you're actually looking for doesn't exist. How about a bash function something like (untested):

function pushCurrent {
  git config push.default upstream
  git push
  git config push.default matching
}

100% width in React Native Flexbox

Style ={{width : "100%"}}

try this:

StyleSheet generated: {
  "width": "80%",
  "textAlign": "center",
  "marginTop": 21.8625,
  "fontWeight": "bold",
  "fontSize": 16,
  "color": "rgb(24, 24, 24)",
  "fontFamily": "Trajan Pro",
  "textShadowColor": "rgba(255, 255, 255, 0.2)",
  "textShadowOffset": {
    "width": 0,
    "height": 0.5
  }
}

Setting Elastic search limit to "unlimited"

You can use the from and size parameters to page through all your data. This could be very slow depending on your data and how much is in the index.

http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-from-size.html

How to convert an Instant to a date format?

try Parsing and Formatting

Take an example Parsing

String input = ...;
try {
    DateTimeFormatter formatter =
                      DateTimeFormatter.ofPattern("MMM d yyyy");
    LocalDate date = LocalDate.parse(input, formatter);
    System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
    System.out.printf("%s is not parsable!%n", input);
    throw exc;      // Rethrow the exception.
}

Formatting

ZoneId leavingZone = ...;
ZonedDateTime departure = ...;

try {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
    String out = departure.format(format);
    System.out.printf("LEAVING:  %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
    System.out.printf("%s can't be formatted!%n", departure);
    throw exc;
}

The output for this example, which prints both the arrival and departure time, is as follows:

LEAVING:  Jul 20 2013  07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013  10:20 PM (Asia/Tokyo)

For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

Save current directory in variable using Bash?

for a relative answer, use .

test with:

$ myDir=.
$ ls $myDir
$ cd /
$ ls $myDir

The first ls will show you everything in the current directory, the second will show you everything in the root directory (/).

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

1) Also you can use lateinit If you sure do your initialization later on onCreate() or elsewhere.

Use this

lateinit var left: Node

Instead of this

var left: Node? = null

2) And there is other way that use !! end of variable when you use it like this

queue.add(left!!) // add !!

nodejs module.js:340 error: cannot find module

If you are using a framework like express, you need to put the package.json file into the folder you are using and don't forget change main name.

How to determine if binary tree is balanced?

Well, you need a way to determine the heights of left and right, and if left and right are balanced.

And I'd just return height(node->left) == height(node->right);

As to writing a height function, read: Understanding recursion

How to hide first section header in UITableView (grouped style)

In Swift 4.2 and many earlier versions, instead of setting the first header's height to 0 like in the other answers, you can just set the other headers to nil. Say you have two sections and only want the second one (i.e., 1) to have a header. That header will have the text Foobar:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return section == 1 ? "Foobar" : nil
}

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.

Map:

class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};
    }

    add(key: string, value: T): void {
        this.items[key] = value;
    }

    has(key: string): boolean {
        return key in this.items;
    }

    get(key: string): T {
        return this.items[key];
    }
}

List:

class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(value);
    }

    get(index: number): T {
        return this.items[index];
    }
}

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;
    }

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);
    }

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   
    }
}

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));
    }

    get(index: number): ListItem<T> {
        return this.items[index];
    }
}

Here too you're looking at untested code..

Hope this helps.


Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1

C++, copy set to vector

You haven't reserved enough space in your vector object to hold the contents of your set.

std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());

HTML button opening link in new tab

Use '_blank'. It will not only open the link in a new tab but the state of the original webpage will also remain unaffected.

Clear text field value in JQuery

If you want to clear the text field, use:

$('#doc_title').val("");

Android load from URL to Bitmap

If you are using Picasso for Images you can try method below!

public static Bitmap getImageBitmapFromURL(Context context, String imageUrl){
    Bitmap imageBitmap = null;
    try {
      imageBitmap = new AsyncTask<Void, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(Void... params) {
          try {
            int targetHeight = 200;
            int targetWidth = 200;

            return Picasso.with(context).load(String.valueOf(imageUrl))
              //.resize(targetWidth, targetHeight)
              .placeholder(R.drawable.raw_image)
              .error(R.drawable.raw_error_image)
              .get();
          } catch (IOException e) {
            e.printStackTrace();
          }
          return null;
        }
      }.execute().get();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } 
  return imageBitmap;
  }

Random number generator only generating one random number

For ease of re-use throughout your application a static class may help.

public static class StaticRandom
{
    private static int seed;

    private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
        (() => new Random(Interlocked.Increment(ref seed)));

    static StaticRandom()
    {
        seed = Environment.TickCount;
    }

    public static Random Instance { get { return threadLocal.Value; } }
}

You can use then use static random instance with code such as

StaticRandom.Instance.Next(1, 100);

Member '<method>' cannot be accessed with an instance reference

I had the same issue - although a few years later, some may find a few pointers helpful:

Do not use ‘static’ gratuitously!

Understand what ‘static’ implies in terms of both run-time and compile time semantics (behavior) and syntax.

  • A static entity will be automatically constructed some time before
    its first use.

  • A static entity has one storage location allocated, and that is
    shared by all who access that entity.

  • A static entity can only be accessed through its type name, not
    through an instance of that type.

  • A static method does not have an implicit ‘this’ argument, as does an instance method. (And therefore a static method has less execution
    overhead – one reason to use them.)

  • Think about thread safety when using static entities.

Some details on static in MSDN:

Calling a javascript function recursively

Using Named Function Expressions:

You can give a function expression a name that is actually private and is only visible from inside of the function ifself:

var factorial = function myself (n) {
    if (n <= 1) {
        return 1;
    }
    return n * myself(n-1);
}
typeof myself === 'undefined'

Here myself is visible only inside of the function itself.

You can use this private name to call the function recursively.

See 13. Function Definition of the ECMAScript 5 spec:

The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).

Using arguments.callee:

Alternatively you could use arguments.callee to refer to the current function:

var factorial = function (n) {
    if (n <= 1) {
        return 1;
    }
    return n * arguments.callee(n-1);
}

The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:

(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.

Create a folder if it doesn't already exist

Here is the missing piece. You need to pass 'recursive' flag as third argument (boolean true) in mkdir call like this:

mkdir('path/to/directory', 0755, true);

Setting Environment Variables for Node to retrieve

Step 1: Add your environment variables to their appropriate file. For example, your staging environment could be called .env.staging, which contains the environment variables USER_ID and USER_KEY, specific to your staging environment.

Step 2: In your package.json file, add the following:

"scripts": {
  "build": "sh -ac '. ./.env.${REACT_APP_ENV}; react-scripts build'",
  "build:staging": "REACT_APP_ENV=staging npm run build",
  "build:production": "REACT_APP_ENV=production npm run build",
  ...
}

then call it in your deploy script like this:

npm run build:staging

Super simple set up and works like a charm!

Source: https://medium.com/@tacomanator/environments-with-create-react-app-7b645312c09d

What is move semantics?

I'm writing this to make sure I understand it properly.

Move semantics were created to avoid the unnecessary copying of large objects. Bjarne Stroustrup in his book "The C++ Programming Language" uses two examples where unnecessary copying occurs by default: one, the swapping of two large objects, and two, the returning of a large object from a method.

Swapping two large objects usually involves copying the first object to a temporary object, copying the second object to the first object, and copying the temporary object to the second object. For a built-in type, this is very fast, but for large objects these three copies could take a large amount of time. A "move assignment" allows the programmer to override the default copy behavior and instead swap references to the objects, which means that there is no copying at all and the swap operation is much faster. The move assignment can be invoked by calling the std::move() method.

Returning an object from a method by default involves making a copy of the local object and its associated data in a location which is accessible to the caller (because the local object is not accessible to the caller and disappears when the method finishes). When a built-in type is being returned, this operation is very fast, but if a large object is being returned, this could take a long time. The move constructor allows the programmer to override this default behavior and instead "reuse" the heap data associated with the local object by pointing the object being returned to the caller to heap data associated with the local object. Thus no copying is required.

In languages which do not allow the creation of local objects (that is, objects on the stack) these types of problems do not occur as all objects are allocated on the heap and are always accessed by reference.

How do I disable log messages from the Requests library?

import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)

In this way all the messages of level=INFO from urllib3 won't be present in the logfile.

So you can continue to use the level=INFO for your log messages...just modify this for the library you are using.

HTML CSS Invisible Button

You can use CSS to hide the button.

button {
  visibility: hidden;
}

If your <button> is just a clickable area on the image, why bother make it a button? You can use <map> element instead.

SOAP Action WSDL

When soapAction is missing in the SOAP 1.2 request (and many clients do not set it, even when it is specified in WSDL), some app servers (eg. jboss) infer the "actual" soapAction from {xsd:import namespace}+{wsdl:operation name}. So, to make the inferred "actual" soapAction match the expected soapAction, you can set the expected soapAction to {xsd:import namespace}+{wsdl:operation name} in your WS definition (@WebMethod(action=...) for Java EE)

Eg. for a typical Java EE case, this helps (not the Stewart's case, National Rail WS has 'soapAction' set):

@WebMethod(action = "http://packagename.of.your.webservice.class.com/methodName")

If you cannot change the server, you will have to force client to fill soapAction.

Extracting text from a PDF file using PDFMiner in python?

Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016)

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text

PDFMiner's structure changed recently, so this should work for extracting text from the PDF files.

Edit : Still working as of the June 7th of 2018. Verified in Python Version 3.x

Edit: The solution works with Python 3.7 at October 3, 2019. I used the Python library pdfminer.six, released on November 2018.

VBA: Counting rows in a table (list object)

You can use this:

    Range("MyTable[#Data]").Rows.Count

You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:

    If WorksheetFunction.CountA(Range("MyTable[#Data]"))

Position buttons next to each other in the center of page

you can add this style to your buttons:

#button1 , #button2 {
display:inline-block;
/* additional code */
}

this aligns your buttons inline. ('side by side') :)

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

Where can I download an offline installer of Cygwin?

If all you want is the UNIX command line tools I'd suggest not installing Cygwin. Cygwin wants to turn your Windows PC into a UNIX Workstation which is why it likes to install all its packages.

Have a look at GnuWin32 instead. It's Windows ports of the command line tools and nothing else. Here is the installer for the GnuWin32 diff.exe. There are offline installers for all the common tools.

(You asked for offline installers but in case you ever want one later there is a tool which will download and install everything for you.)

Method 2: make an offline install zip file for cygwin.

Don't mess with saving packages because the installed directory for cygwin can be canned in a zip file and expanded whenever you need it on any computer.

  1. Download Cygwin installer

  2. pick packages you want installed from gui.

  3. hit install and wait a really long time for everything to download.

  4. zip up the C:\Cygwin folder. Now you have your offline zip file for installing cygwin on any machine.

  5. Unzip this file on whatever computer you like. set cmd.exe paths appropriately to point to cygwin bin directory under windows control panel.

How to find MySQL process list and to kill those processes?

You can do something like this to check if any mysql process is running or not:

ps aux | grep mysqld
ps aux | grep mysql

Then if it is running you can killall by using(depending on what all processes are running currently):

killall -9 mysql
killall -9 mysqld
killall -9 mysqld_safe    

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

Execute jar file with multiple classpath libraries from command prompt

There are several options.

The easiest is likely the exec plugin.

You can also generate a jar containing all the dependencies using the assembly plugin.

Lastly, you can generate a file with the classpath in it using the dependency:classpath goal.

Peak signal detection in realtime timeseries data

And here comes the PHP implementation of the ZSCORE algo:

<?php
$y = array(1,7,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
       1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,10,3,2,5,3,2,1,1,1,0.9,1,1,3,
       2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1);

function mean($data, $start, $len) {
    $avg = 0;
    for ($i = $start; $i < $start+ $len; $i ++)
        $avg += $data[$i];
    return $avg / $len;
}
    
function stddev($data, $start,$len) {
    $mean = mean($data,$start,$len);
    $dev = 0;
    for ($i = $start; $i < $start+$len; $i++) 
        $dev += (($data[$i] - $mean) * ($data[$i] - $mean));
    return sqrt($dev / $len);
}

function zscore($data, $len, $lag= 20, $threshold = 1, $influence = 1) {

    $signals = array();
    $avgFilter = array();
    $stdFilter = array();
    $filteredY = array();
    $avgFilter[$lag - 1] = mean($data, 0, $lag);
    $stdFilter[$lag - 1] = stddev($data, 0, $lag);
    
    for ($i = 0; $i < $len; $i++) {
        $filteredY[$i] = $data[$i];
        $signals[$i] = 0;
    }


    for ($i=$lag; $i < $len; $i++) {
        if (abs($data[$i] - $avgFilter[$i-1]) > $threshold * $stdFilter[$lag - 1]) {
            if ($data[$i] > $avgFilter[$i-1]) {
                $signals[$i] = 1;
            }
            else {
                $signals[$i] = -1;
            }
            $filteredY[$i] = $influence * $data[$i] + (1 - $influence) * $filteredY[$i-1];
        } 
        else {
            $signals[$i] = 0;
            $filteredY[$i] = $data[$i];
        }
        
        $avgFilter[$i] = mean($filteredY, $i - $lag, $lag);
        $stdFilter[$i] = stddev($filteredY, $i - $lag, $lag);
    }
    return $signals;
}

$sig = zscore($y, count($y));

print_r($y); echo "<br><br>";
print_r($sig); echo "<br><br>";

for ($i = 0; $i < count($y); $i++) echo $i. " " . $y[$i]. " ". $sig[$i]."<br>";

Powershell remoting with ip-address as target

On your machine* run 'Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$ipaddress"

*Machine from where you are running PSSession

Oracle DB: How can I write query ignoring case?

You can convert both values to upper or lowercase using the upper or lower functions:

Select * from table where upper(table.name) like upper('IgNoreCaSe')

or

Select * from table where lower(table.name) like lower('IgNoreCaSe');

Add custom buttons on Slick Carousel

if you want to use icons from any icon font library, you can try this in the option while calling the slider in your js file.

prevArrow: '<div class="class-to-style"><span class="fa fa-angle-left"></span><span class="sr-only">Prev</span></div>',

nextArrow: '<div class="class-to-style"><span class="fa fa-angle-right"></span><span class="sr-only">Next</span></div>'

Here "fa" comes from FontAwesome icon font library.

MySQL Select Query - Get only first 10 characters of a value

SELECT SUBSTRING(subject, 1, 10) FROM tbl

How do I resolve a HTTP 414 "Request URI too long" error?

Under Apache, the limit is a configurable value, LimitRequestLine. Change this value to something larger than its default of 8190 if you want to support a longer request URI. The value is in /etc/apache2/apache2.conf. If not, add a new line (LimitRequestLine 10000) under AccessFileName .htaccess.

However, note that if you're actually running into this limit, you are probably abusing GET to begin with. You should use POST to transmit this sort of data -- especially since you even concede that you're using it to update values. If you check the link above, you'll notice that Apache even says "Under normal conditions, the value should not be changed from the default."

Calculating arithmetic mean (one type of average) in Python

You don't even need numpy or scipy...

>>> a = [1, 2, 3, 4, 5, 6]
>>> print(sum(a) / len(a))
3

Limiting the output of PHP's echo to 200 characters

It gives out a string of max 200 characters OR 200 normal characters OR 200 characters followed by '...'

$ur_str= (strlen($ur_str) > 200) ? substr($ur_str,0,200).'...' :$ur_str;

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

"No X11 DISPLAY variable" - what does it mean?

Very Easy, Had this same problem then what i did was to download and install an app that would help in displaying then fixed the error.

Download this app xming:

http://sourceforge.net/project/downloading.php?

Install, then use settings on this link:

http://www.geo.mtu.edu/geoschem/docs/putty_install.html or follow this steps:

Installing/Configuring PuTTy and Xming

Once PuTTy and Xming have been downloaded to the PC, install according to their respective instructions.

Configuring Xming

Once Xming is installed, run the application called 'XLaunch' and verify that the settings are as shown:

  • select Default entries on Display Settings windows, click next
  • click next on Session Type window.
  • click next on Additional parameters window(Notice clipboard checkbox is true)
  • save configuration and click to finish.

Configuring PuTTy

After installing PuTTy, double-click on the PuTTy icon on the desktop and configure as shown:

This shows creating a login profile then saving it.

  • On ssh -> X11, click on checkbox to enable X11 forwarding.
  • on X display location textbox, type localhost:0.0

save profile then connect remotely to server to test.

Cheers!!!

Why can't radio buttons be "readonly"?

I have a lengthy form (250+ fields) that posts to a db. It is an online employment application. When an admin goes to look at an application that has been filed, the form is populated with data from the db. Input texts and textareas are replaced with the text they submitted but the radios and checkboxes are useful to keep as form elements. Disabling them makes them harder to read. Setting the .checked property to false onclick won't work because they may have been checked by the user filling out the app. Anyhow...

onclick="return false;"

works like a charm for 'disabling' radios and checkboxes ipso facto.

Import multiple csv files into pandas and concatenate into one DataFrame

one liner using map, but if you'd like to specify additional args, you could do:

import pandas as pd
import glob
import functools

df = pd.concat(map(functools.partial(pd.read_csv, sep='|', compression=None), 
                    glob.glob("data/*.csv")))

Note: map by itself does not let you supply additional args.

How to return a complex JSON response with Node.js?

I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:

query.exec(function (err, results){
  if (err) res.writeHead(500, err.message)
  else if (!results.length) res.writeHead(404);
  else {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
  }
  res.end();
});

Format specifier %02x

You are actually getting the correct value out.

The way your x86 (compatible) processor stores data like this, is in Little Endian order, meaning that, the MSB is last in your output.

So, given your output:

10101010

the last two hex values 10 are the Most Significant Byte (2 hex digits = 1 byte = 8 bits (for (possibly unnecessary) clarification).

So, by reversing the memory storage order of the bytes, your value is actually: 01010101.

Hope that clears it up!

How do you read scanf until EOF in C?

I guess best way to do this is ...

int main()
{
    char str[100];
    scanf("[^EOF]",str);
    printf("%s",str);
    return 0;     
}

What data type to use for money in Java?

I like using Tiny Types which would wrap either a double, BigDecimal, or int as previous answers have suggested. (I would use a double unless precision problems crop up).

A Tiny Type gives you type safety so you don't confused a double money with other doubles.

ComboBox.SelectedText doesn't give me the SelectedText

From the documentation:

You can use the SelectedText property to retrieve or change the currently selected text in a ComboBox control. However, you should be aware that the selection can change automatically because of user interaction. For example, if you retrieve the SelectedText value in a button Click event handler, the value will be an empty string. This is because the selection is automatically cleared when the input focus moves from the combo box to the button.

When the combo box loses focus, the selection point moves to the beginning of the text and any selected text becomes unselected. In this case, getting the SelectedText property retrieves an empty string, and setting the SelectedText property adds the specified value to the beginning of the text.

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

COM is definitely not a good way to go. More specifically, it's a no go if you're dealing with web environment...

I've used with success the following open source projects:

  • ExcelPackage for OOXML formats (Office 2007)

  • NPOI for .XLS format (Office 2003)

Take a look at these blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

Use of def, val, and var in scala

With

def person = new Person("Kumar", 12) 

you are defining a function/lazy variable which always returns a new Person instance with name "Kumar" and age 12. This is totally valid and the compiler has no reason to complain. Calling person.age will return the age of this newly created Person instance, which is always 12.

When writing

person.age = 45

you assign a new value to the age property in class Person, which is valid since age is declared as var. The compiler will complain if you try to reassign person with a new Person object like

person = new Person("Steve", 13)  // Error

How to cancel a pull request on github?

Go to conversation tab then come down there is one "close pull request" button is there use that button to close pull request, Take ref of attached image

Dynamically add item to jQuery Select2 control that uses AJAX

To get dynamic tagging to work with ajax, here's what I did.

Select2 version 3.5

This is easy in version 3.5 because it offers the createSearchChoice hook. It even works for multiple select, as long as multiple: true and tags: true are set.

HTML

<input type="hidden" name="locations" value="Whistler, BC" />

JS

$('input[name="locations"]').select2({
  tags: true,
  multiple: true,
  createSearchChoice: function(term, data) {
    if (!data.length)
      return { id: term, text: term };
    },
  ajax: {
    url: '/api/v1.1/locations',
    dataType: 'json'
  }
});

The idea here is to use select2's createSearchChoice hook which passes you both the term that the user entered and the ajax response (as data). If ajax returns an empty list, then tell select2 to offer the user-entered term as an option.

Demo: https://johnny.netlify.com/select2-examples/version3


Select2 version 4.X

Version 4.X doesn't have a createSearchChoice hook anymore, but here's how I did the same thing.

HTML

  <select name="locations" multiple>
    <option value="Whistler, BC" selected>Whistler, BC</option>
  </select>

JS

$('select[name="locations"]').select2({
  ajax: {
    url: '/api/v1.1/locations',
    dataType: 'json',
    data: function(params) {
      this.data('term', params.term);
      return params;
    },
    processResults: function(data) {
      if (data.length)
        return {
          results: data
        };
      else
        return {
          results: [{ id: this.$element.data('term'), text: this.$element.data('term') }]
        };
    }
  }
});

The ideas is to stash the term that the user typed into jQuery's data store inside select2's data hook. Then in select2's processResults hook, I check if the ajax response is empty. If it is, I grab the stashed term that the user typed and return it as an option to select2.

Demo: https://johnny.netlify.com/select2-examples/version4