Programs & Examples On #Language specifications

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.

When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.

>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False

how to implement a long click listener on a listview

If you want to do it in the adapter, you can simply do this:

itemView.setOnLongClickListener(new View.OnLongClickListener()
        {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(mContext, "Long pressed on item", Toast.LENGTH_SHORT).show();
            }
        });

Why does dividing two int not yield the right value when assigned to double?

With very few exceptions (I can only think of one), C++ determines the entire meaning of an expression (or sub-expression) from the expression itself. What you do with the results of the expression doesn't matter. In your case, in the expression a / b, there's not a double in sight; everything is int. So the compiler uses integer division. Only once it has the result does it consider what to do with it, and convert it to double.

Using JavaScript to display a Blob

If you want to use fetch instead:

var myImage = document.querySelector('img');

fetch('flowers.jpg').then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Source:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

JSLint says "missing radix parameter"

To avoid this warning, instead of using:

parseInt("999", 10);

You may replace it by:

Number("999");


Note that parseInt and Number have different behaviors, but in some cases, one can replace the other.

Inline labels in Matplotlib

Nice question, a while ago I've experimented a bit with this, but haven't used it a lot because it's still not bulletproof. I divided the plot area into a 32x32 grid and calculated a 'potential field' for the best position of a label for each line according the following rules:

  • white space is a good place for a label
  • Label should be near corresponding line
  • Label should be away from the other lines

The code was something like this:

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


def my_legend(axis = None):

    if axis == None:
        axis = plt.gca()

    N = 32
    Nlines = len(axis.lines)
    print Nlines

    xmin, xmax = axis.get_xlim()
    ymin, ymax = axis.get_ylim()

    # the 'point of presence' matrix
    pop = np.zeros((Nlines, N, N), dtype=np.float)    

    for l in range(Nlines):
        # get xy data and scale it to the NxN squares
        xy = axis.lines[l].get_xydata()
        xy = (xy - [xmin,ymin]) / ([xmax-xmin, ymax-ymin]) * N
        xy = xy.astype(np.int32)
        # mask stuff outside plot        
        mask = (xy[:,0] >= 0) & (xy[:,0] < N) & (xy[:,1] >= 0) & (xy[:,1] < N)
        xy = xy[mask]
        # add to pop
        for p in xy:
            pop[l][tuple(p)] = 1.0

    # find whitespace, nice place for labels
    ws = 1.0 - (np.sum(pop, axis=0) > 0) * 1.0 
    # don't use the borders
    ws[:,0]   = 0
    ws[:,N-1] = 0
    ws[0,:]   = 0  
    ws[N-1,:] = 0  

    # blur the pop's
    for l in range(Nlines):
        pop[l] = ndimage.gaussian_filter(pop[l], sigma=N/5)

    for l in range(Nlines):
        # positive weights for current line, negative weight for others....
        w = -0.3 * np.ones(Nlines, dtype=np.float)
        w[l] = 0.5

        # calculate a field         
        p = ws + np.sum(w[:, np.newaxis, np.newaxis] * pop, axis=0)
        plt.figure()
        plt.imshow(p, interpolation='nearest')
        plt.title(axis.lines[l].get_label())

        pos = np.argmax(p)  # note, argmax flattens the array first 
        best_x, best_y =  (pos / N, pos % N) 
        x = xmin + (xmax-xmin) * best_x / N       
        y = ymin + (ymax-ymin) * best_y / N       


        axis.text(x, y, axis.lines[l].get_label(), 
                  horizontalalignment='center',
                  verticalalignment='center')


plt.close('all')

x = np.linspace(0, 1, 101)
y1 = np.sin(x * np.pi / 2)
y2 = np.cos(x * np.pi / 2)
y3 = x * x
plt.plot(x, y1, 'b', label='blue')
plt.plot(x, y2, 'r', label='red')
plt.plot(x, y3, 'g', label='green')
my_legend()
plt.show()

And the resulting plot: enter image description here

accepting HTTPS connections with self-signed certificates

The following main steps are required to achieve a secured connection from Certification Authorities which are not considered as trusted by the android platform.

As requested by many users, I've mirrored the most important parts from my blog article here:

  1. Grab all required certificates (root and any intermediate CA’s)
  2. Create a keystore with keytool and the BouncyCastle provider and import the certs
  3. Load the keystore in your android app and use it for the secured connections (I recommend to use the Apache HttpClient instead of the standard java.net.ssl.HttpsURLConnection (easier to understand, more performant)

Grab the certs

You have to obtain all certificates that build a chain from the endpoint certificate the whole way up to the Root CA. This means, any (if present) Intermediate CA certs and also the Root CA cert. You don’t need to obtain the endpoint certificate.

Create the keystore

Download the BouncyCastle Provider and store it to a known location. Also ensure that you can invoke the keytool command (usually located under the bin folder of your JRE installation).

Now import the obtained certs (don’t import the endpoint cert) into a BouncyCastle formatted keystore.

I didn’t test it, but I think the order of importing the certificates is important. This means, import the lowermost Intermediate CA certificate first and then all the way up to the Root CA certificate.

With the following command a new keystore (if not already present) with the password mysecret will be created and the Intermediate CA certificate will be imported. I also defined the BouncyCastle provider, where it can be found on my file system and the keystore format. Execute this command for each certificate in the chain.

keytool -importcert -v -trustcacerts -file "path_to_cert/interm_ca.cer" -alias IntermediateCA -keystore "res/raw/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "path_to_bouncycastle/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret

Verify if the certificates were imported correctly into the keystore:

keytool -list -keystore "res/raw/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "path_to_bouncycastle/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret

Should output the whole chain:

RootCA, 22.10.2010, trustedCertEntry, Thumbprint (MD5): 24:77:D9:A8:91:D1:3B:FA:88:2D:C2:FF:F8:CD:33:93
IntermediateCA, 22.10.2010, trustedCertEntry, Thumbprint (MD5): 98:0F:C3:F8:39:F7:D8:05:07:02:0D:E3:14:5B:29:43

Now you can copy the keystore as a raw resource in your android app under res/raw/

Use the keystore in your app

First of all we have to create a custom Apache HttpClient that uses our keystore for HTTPS connections:

import org.apache.http.*

public class MyHttpClient extends DefaultHttpClient {

    final Context context;

    public MyHttpClient(Context context) {
        this.context = context;
    }

    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        // Register for port 443 our SSLSocketFactory with our keystore
        // to the ConnectionManager
        registry.register(new Scheme("https", newSslSocketFactory(), 443));
        return new SingleClientConnManager(getParams(), registry);
    }

    private SSLSocketFactory newSslSocketFactory() {
        try {
            // Get an instance of the Bouncy Castle KeyStore format
            KeyStore trusted = KeyStore.getInstance("BKS");
            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
            try {
                // Initialize the keystore with the provided trusted certificates
                // Also provide the password of the keystore
                trusted.load(in, "mysecret".toCharArray());
            } finally {
                in.close();
            }
            // Pass the keystore to the SSLSocketFactory. The factory is responsible
            // for the verification of the server certificate.
            SSLSocketFactory sf = new SSLSocketFactory(trusted);
            // Hostname verification from certificate
            // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
            sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            return sf;
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}

We have created our custom HttpClient, now we can use it for secure connections. For example when we make a GET call to a REST resource:

// Instantiate the custom HttpClient
DefaultHttpClient client = new MyHttpClient(getApplicationContext());
HttpGet get = new HttpGet("https://www.mydomain.ch/rest/contacts/23");
// Execute the GET call and obtain the response
HttpResponse getResponse = client.execute(get);
HttpEntity responseEntity = getResponse.getEntity();

That's it ;)

How to sum columns in a dataTable?

It's a pity to use .NET and not use collections and lambda to save your time and code lines This is an example of how this works: Transform yourDataTable to Enumerable, filter it if you want , according a "FILTER_ROWS_FIELD" column, and if you want, group your data by a "A_GROUP_BY_FIELD". Then get the count, the sum, or whatever you wish. If you want a count and a sum without grouby don't group the data

var groupedData = from b in yourDataTable.AsEnumerable().Where(r=>r.Field<int>("FILTER_ROWS_FIELD").Equals(9999))
                          group b by b.Field<string>("A_GROUP_BY_FIELD") into g
                          select new
                          {
                              tag = g.Key,
                              count = g.Count(),
                              sum = g.Sum(c => c.Field<double>("rvMoney"))
                          };

Display calendar to pick a date in java

The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.

Fair disclosure: I'm the primary developer.

Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.

The most commonly used date formats are automatically supported, and additional date formats can be added if desired.

To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.

Besides the DatePicker, the library also has the TimePicker and DateTimePicker components. I pasted screenshots of all the components (and the demo program) below.

The library can be installed into your Java project from the project release page.

The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .


DateTimePicker screenshot


DateTimePicker examples


Demo screenshot

git stash -> merge stashed change with current changes

The way I do this is to git add this first then git stash apply <stash code>. It's the most simple way.

What are .NumberFormat Options In Excel VBA?

dovers gives us his great answer and based on it you can try use it like

public static class CellDataFormat
{
        public static string General { get { return "General"; } }
        public static string Number { get { return "0"; } }

        // Your custom format 
        public static string NumberDotTwoDigits { get { return "0.00"; } }

        public static string Currency { get { return "$#,##0.00;[Red]$#,##0.00"; } }
        public static string Accounting { get { return "_($* #,##0.00_);_($* (#,##0.00);_($* \" - \"??_);_(@_)"; } }
        public static string Date { get { return "m/d/yy"; } }
        public static string Time { get { return "[$-F400] h:mm:ss am/pm"; } }
        public static string Percentage { get { return "0.00%"; } }
        public static string Fraction { get { return "# ?/?"; } }
        public static string Scientific { get { return "0.00E+00"; } }
        public static string Text { get { return "@"; } }
        public static string Special { get { return ";;"; } }
        public static string Custom { get { return "#,##0_);[Red](#,##0)"; } }
}

How to remove line breaks from a file in Java?

You need to set text to the results of text.replace():

String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");

This is necessary because Strings are immutable -- calling replace doesn't change the original String, it returns a new one that's been changed. If you don't assign the result to text, then that new String is lost and garbage collected.

As for getting the newline String for any environment -- that is available by calling System.getProperty("line.separator").

Why do people say that Ruby is slow?

Ruby performs well for developer productivity. Ruby by nature forces test driven development because of the lack of types. Ruby performs well when used as a high level wrapper for C libraries. Ruby also performs well during long running processes when it is JIT-compiled to machine code via JVM or Rbx VM. Ruby does not perform well when it is required to crunch numbers in a short time with pure ruby code.

How to generate the JPA entity Metamodel?

Ok, based on what I have read here, I did it with EclipseLink this way and I did not need to put the processor dependency to the project, only as an annotationProcessorPath element of the compiler plugin.

    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <annotationProcessorPaths>
                <annotationProcessorPath>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
                    <version>2.7.7</version>
                </annotationProcessorPath>
            </annotationProcessorPaths>
            <compilerArgs>
                <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
            </compilerArgs>
        </configuration>
    </plugin>

Remove a file from the list that will be committed

Maybe you could also use stash to store temporaly your modifications in a patch file and then reapply it (after a checkout to come back to the old version). This could be related to this other topic : How would I extract a single file (or changes to a file) from a git stash?.

Disabling browser caching for all browsers from ASP.NET

I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.

What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function () {   
        // This function does nothing.  It won't spawn a confirmation dialog   
        // But it will ensure that the page is not cached by the browser.
    }  
</script>

This has disabled all caching in all browsers for me without fail.

Failed to allocate memory: 8

Looks like there are a thousand different fixes for this...none of the above worked for me, but what worked was to launch the AVD from the command line emulator-arm.exe @AVD-NAME

Somehow if launched with only emulator.exe, I would get the same error message than when trying to launch via Eclipse.

How to run stored procedures in Entity Framework Core?

We should create a property with DbQuery not DbSet in the model for the db context like below...

public class MyContextContext : DbContext
{
    public virtual DbQuery<CheckoutInvoiceModel> CheckoutInvoice { get; set; } 
}

After than a method that can be used to return result

public async Task<IEnumerable<CheckoutInvoiceModel>> GetLabReceiptByReceiptNo(string labReceiptNo)
{
    var listing = new List<CheckoutInvoiceModel>();
    try
    {
        var sqlCommand = $@"[dbo].[Checkout_GetLabReceiptByReceiptNo] {labReceiptNo}";
        
        listing = await db.Set<CheckoutInvoiceModel>().FromSqlRaw(sqlCommand).ToListAsync();                       
                        
    }
    catch (Exception ex)
    {
        return null;
    }
    return listing;
}

From above example, we can use any one option you like.

Hope this helpful for you!

Spring Resttemplate exception handling

Spring cleverly treats http error codes as exceptions, and assumes that your exception handling code has the context to handle the error. To get exchange to function as you would expect it, do this:

    try {
        return restTemplate.exchange(url, httpMethod, httpEntity, String.class);
    } catch(HttpStatusCodeException e) {
        return ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders())
                .body(e.getResponseBodyAsString());
    }

This will return all the expected results from the response.

How do I create a HTTP Client Request with a cookie?

You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.

To perform a request with a cookie attached just do the following:

var requestify = require('requestify');
requestify.post('http://google.com', {}, {
    cookies: {
        sessionCookie: 'session-cookie-data'   
    }
});

How can I rollback an UPDATE query in SQL server 2005?

Try

ROLLBACK WORK;

It usually works

How can I compile a Java program in Eclipse without running it?

You will need to go to Project->Clean...,then build your project. This will work, even when your source code does not contain any main method to run as an executable program. The .class files will appear in the bin folder of your project, in your workspace.

How can I get a random number in Kotlin?

First, you need a RNG. In Kotlin you currently need to use the platform specific ones (there isn't a Kotlin built in one). For the JVM it's java.util.Random. You'll need to create an instance of it and then call random.nextInt(n).

Using union and order by clause in mysql

You can use subqueries to do this:

select * from (select values1 from table1 order by orderby1) as a
union all
select * from (select values2 from table2 order by orderby2) as b

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

Time stamp in the C programming language

Also making aware of interactions between clock() and usleep(). usleep() suspends the program, and clock() only measures the time the program is running.

If might be better off to use gettimeofday() as mentioned here

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

In order to apply all of these great comments to my daily coding, for continuity between all my applications, I have decided to use the following in both my jquery and jquery mobile code.

window.onresize = function (event) {
  applyOrientation();
}

function applyOrientation() {
  if (window.innerHeight > window.innerWidth) {
    alert("You are now in portrait");
  } else {
    alert("You are now in landscape");
  }
}

python multithreading wait till all threads finished

Put the threads in a list and then use the Join method

 threads = []

 t = Thread(...)
 threads.append(t)

 ...repeat as often as necessary...

 # Start all threads
 for x in threads:
     x.start()

 # Wait for all of them to finish
 for x in threads:
     x.join()

Save attachments to a folder and rename them

See ReceivedTime Property

http://msdn.microsoft.com/en-us/library/office/aa171873(v=office.11).aspx

You added another \ to the end of C:\Temp\ in the SaveAs File line. Could be a problem. Do a test first before adding a path separator.

dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  
saveFolder = "C:\Temp"

You have not set objAtt so there is no need for "Set objAtt = Nothing". If there was it would be just before End Sub not in the loop.


Public Sub saveAttachtoDisk (itm As Outlook.MailItem) 
    Dim objAtt As Outlook.Attachment 
    Dim saveFolder As String Dim dateFormat
    dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  saveFolder = "C:\Temp"
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
    Next
End Sub

Re: It worked the first day I started tinkering but after that it stopped saving files.

This is usually due to Security settings. It is a "trap" set for first time users to allow macros then take it away. http://www.slipstick.com/outlook-developer/how-to-use-outlooks-vba-editor/

How to display scroll bar onto a html table

I resolved this problem by separating my content into two tables.

One table is the header row.

The seconds is also <table> tag, but wrapped by <div> with static height and overflow scroll.

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

Angular 4/5/6 Global Variables

You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.

Python urllib2: Receive JSON response from url

If the URL is returning valid JSON-encoded data, use the json library to decode that:

import urllib2
import json

response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
data = json.load(response)   
print data

Listing all extras of an Intent

Sorry if this is too verbose or too late, but this was the only way I could find to get the job done. The most complicating factor was the fact that java does not have pass by reference functions, so the get---Extra methods need a default to return and cannot modify a boolean value to tell whether or not the default value is being returned by chance, or because the results were not favorable. For this purpose, it would have been nicer to have the method raise an exception than to have it return a default.

I found my information here: Android Intent Documentation.

    //substitute your own intent here
    Intent intent = new Intent();
    intent.putExtra("first", "hello");
    intent.putExtra("second", 1);
    intent.putExtra("third", true);
    intent.putExtra("fourth", 1.01);
    // convert the set to a string array

Set Documentation

    String[] anArray = {};
    Set<String> extras1 = (Set<String>) intent.getExtras().keySet();
    String[] extras = (String[]) extras1.toArray(anArray);
    // an arraylist to hold all of the strings
    // rather than putting strings in here, you could display them
    ArrayList<String> endResult = new ArrayList<String>();
    for (int i=0; i<extras.length; i++) {
        //try using as a String
        String aString = intent.getStringExtra(extras[i]);
        // is a string, because the default return value for a non-string is null
        if (aString != null) {
            endResult.add(extras[i] + " : " + aString);
        }
        // not a string
        else {
            // try the next data type, int
            int anInt = intent.getIntExtra(extras[i], 0);
            // is the default value signifying that either it is not an int or that it happens to be 0 
            if (anInt == 0) {
                // is an int value that happens to be 0, the same as the default value
                if (intent.getIntExtra(extras[i], 1) != 1) {
                    endResult.add(extras[i] + " : " + Integer.toString(anInt));
                }
                // not an int value
                // try double (also works for float)
                else {
                    double aDouble = intent.getDoubleExtra(extras[i], 0.0);
                    // is the same as the default value, but does not necessarily mean that it is not double
                    if (aDouble == 0.0) {
                        // just happens that it was 0.0 and is a double
                        if (intent.getDoubleExtra(extras[i], 1.0) != 1.0) {
                            endResult.add(extras[i] + " : " + Double.toString(aDouble));
                        }
                        // keep looking...
                        else {
                            // lastly check for boolean
                            boolean aBool = intent.getBooleanExtra(extras[i], false);
                            // same as default, but not necessarily not a bool (still could be a bool)
                            if (aBool == false) {
                                // it is a bool!
                                if (intent.getBooleanExtra(extras[i], true) != true) {
                                    endResult.add(extras[i] + " : " + Boolean.toString(aBool));
                                }
                                else {
                                    //well, the road ends here unless you want to add some more data types
                                }
                            }
                            // it is a bool
                            else {
                                endResult.add(extras[i] + " : " + Boolean.toString(aBool));
                            }
                        }
                    }
                    // is a double
                    else {
                        endResult.add(extras[i] + " : " + Double.toString(aDouble));
                    }
                }
            }
            // is an int value
            else {
                endResult.add(extras[i] + " : " + Integer.toString(anInt));
            }
        }
    }
    // to display at the end
    for (int i=0; i<endResult.size(); i++) {
        Toast.makeText(this, endResult.get(i), Toast.LENGTH_SHORT).show();
    }

How can I create a dynamically sized array of structs?

If you want to dynamically allocate arrays, you can use malloc from stdlib.h.

If you want to allocate an array of 100 elements using your words struct, try the following:

words* array = (words*)malloc(sizeof(words) * 100);

The size of the memory that you want to allocate is passed into malloc and then it will return a pointer of type void (void*). In most cases you'll probably want to cast it to the pointer type you desire, which in this case is words*.

The sizeof keyword is used here to find out the size of the words struct, then that size is multiplied by the number of elements you want to allocate.

Once you are done, be sure to use free() to free up the heap memory you used in order to prevent memory leaks:

free(array);

If you want to change the size of the allocated array, you can try to use realloc as others have mentioned, but keep in mind that if you do many reallocs you may end up fragmenting the memory. If you want to dynamically resize the array in order to keep a low memory footprint for your program, it may be better to not do too many reallocs.

How do I change the background color with JavaScript?

I would suggest the following code:

<div id="example" onClick="colorize()">Click on this text to change the
background color</div>
<script type='text/javascript'>
function colorize() {
var element = document.getElementById("example");
element.style.backgroundColor='#800';
element.style.color='white';
element.style.textAlign='center';
}
</script>

Upload files from Java client to a HTTP server

Here is how you would do it with Apache HttpClient (this solution is for those who don't mind using a 3rd party library):

    HttpEntity entity = MultipartEntityBuilder.create()
                       .addPart("file", new FileBody(file))
                       .build();

    HttpPost request = new HttpPost(url);
    request.setEntity(entity);

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(request);

Show spinner GIF during an $http request in AngularJS?

Since the functionality of position:fixed changed recently, I had difficulty showing the gif loader above all elements, so I had to use angular's inbuilt jQuery.

Html

<div ng-controller="FetchController">
      <div id="spinner"></div>
</div>

Css

#spinner {display: none}
body.spinnerOn #spinner { /* body tag not necessary actually */
   display: block;
   height: 100%;
   width: 100%;
   background: rgba(207, 13, 48, 0.72) url(img/loader.gif) center center no-repeat;
   position: fixed;
   top: 0;
   left: 0;
   z-index: 9999;
}
body.spinnerOn main.content { position: static;} /* and whatever content needs to be moved below your fixed loader div */

Controller

app.controller('FetchController', ['$scope', '$http', '$templateCache', '$location', '$q',
function($scope, $http, $templateCache, $location, $q) {

angular.element('body').addClass('spinnerOn'); // add Class to body to show spinner

$http.post( // or .get(
    // your data here
})
.then(function (response) {
    console.info('success');     
    angular.element('body').removeClass('spinnerOn'); // hide spinner

    return response.data;               
}, function (response) {                   
    console.info('error'); 
    angular.element('body').removeClass('spinnerOn'); // hide spinner
});

})

Hope this helps :)

How do I copy the contents of a String to the clipboard in C#?

Use try-catch, even if it has an error it will still copy.

Try
   Clipboard.SetText("copy me to clipboard")
Catch ex As Exception

End Try

If you use a message box to capture the exception, it will show you error, but the value is still copied to clipboard.

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

The above answers are incorrect in that most over-ride the 'is this connection HTTPS' test to allow serving the pages over http irrespective of connection security.

The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )

The OP should use:

server {
  listen        12345;
  server_name   php.myadmin.com;

  root         /var/www/php;

  ssl           on;

  # If they come here using HTTP, bounce them to the correct scheme
  error_page 497 https://$server_name:$server_port$request_uri;

  [....]
}

In C - check if a char exists in a char array

strchr for searching a char from start (strrchr from the end):

  char str[] = "This is a sample string";

  if (strchr(str, 'h') != NULL) {
      /* h is in str */
  }

CSS media query to target iPad and iPad only?

Well quite same question and there is also an answer =)

http://css-tricks.com/forums/discussion/12708/target-ipad-ipad-only./p1

@media only screen and (device-width: 768px) ...
@media only screen and (max-device-width: 1024px) ...

I can not test it currently so please test it =)

Also found some more:

http://perishablepress.com/press/2010/10/20/target-iphone-and-ipad-with-css3-media-queries/

Or you check the navigator with some javascript and generate / add a css file with javascript

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

How to handle static content in Spring MVC?

Place static contents like css ,js in following path

resources 
        ->static
               ->css
               ->js
(or) 
resources 
        ->public
               ->css
               ->js

if arguments is equal to this string, define a variable like this string

Don't forget about spaces:

source=""
samples=("")
if [ $1 = "country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
  echo "try again"
fi

Default settings Raspberry Pi /etc/network/interfaces

For my Raspberry Pi 3B model it was

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

How to print the contents of RDD?

You can also save as a file: rdd.saveAsTextFile("alicia.txt")

How to get first two characters of a string in oracle query?

Try select substr(orderno, 1,2) from shipment;

Find length (size) of an array in jquery

Because 2 isn't an array, it's a number. Numbers have no length.

Perhaps you meant to write testvar.length; this is also undefined, since objects (created using the { ... } notation) do not have a length.

Only arrays have a length property:

var testvar = [  ];
testvar[1] = 2;
testvar[2] = 3;
alert(testvar.length);    // 3

Note that Javascript arrays are indexed starting at 0 and are not necessarily sparse (hence why the result is 3 and not 2 -- see this answer for an explanation of when the array will be sparse and when it won't).

ThreadStart with parameters

One of the 2 overloads of the Thread constructor takse a ParameterizedThreadStart delegate which allows you to pass a single parameter to the start method. Unfortunately though it only allows for a single parameter and it does so in an unsafe way because it passes it as object. I find it's much easier to use a lambda expression to capture the relevant parameters and pass them in a strongly typed fashion.

Try the following

public Thread StartTheThread(SomeType param1, SomeOtherType param2) {
  var t = new Thread(() => RealStart(param1, param2));
  t.Start();
  return t;
}

private static void RealStart(SomeType param1, SomeOtherType param2) {
  ...
}

Resetting a setTimeout

var redirectionDelay;
function startRedirectionDelay(){
    redirectionDelay = setTimeout(redirect, 115000);
}
function resetRedirectionDelay(){
    clearTimeout(redirectionDelay);
}

function redirect(){
    location.href = 'file.php';
}

// in your click >> fire those
resetRedirectionDelay();
startRedirectionDelay();

here is an elaborated example for what's really going on http://jsfiddle.net/ppjrnd2L/

Image re-size to 50% of original size in HTML

You did not do anything wrong here, it will any other thing that is overriding the image size.

You can check this working fiddle.

And in this fiddle I have alter the image size using %, and it is working.

Also try using this code:

<img src="image.jpg" style="width: 50%; height: 50%"/>?

Here is the example fiddle.

Return multiple values in JavaScript?

Since ES6 you can do this

let newCodes = function() {  
    const dCodes = fg.codecsCodes.rs
    const dCodes2 = fg.codecsCodes2.rs
    return {dCodes, dCodes2}
};

let {dCodes, dCodes2} = newCodes()

Return expression {dCodes, dCodes2} is property value shorthand and is equivalent to this {dCodes: dCodes, dCodes2: dCodes2}.

This assignment on last line is called object destructing assignment. It extracts property value of an object and assigns it to variable of same name. If you'd like to assign return values to variables of different name you could do it like this let {dCodes: x, dCodes2: y} = newCodes()

Remove Safari/Chrome textinput/textarea glow

This solution worked for me.

input:focus {
    outline: none !important;
    box-shadow: none !important;
}

phpmailer error "Could not instantiate mail function"

I was having this issue while sending files with regional characters in their names like: VeryRegiónal file - name.pdf.

The solution was to clear filename before attaching it to the email.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

e.printStackTrace equivalent in python

Adding to the other great answers, we can use the Python logging library's debug(), info(), warning(), error(), and critical() methods. Quoting from the docs for Python 3.7.4,

There are three keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message.

What this means is, you can use the Python logging library to output a debug(), or other type of message, and the logging library will include the stack trace in its output. With this in mind, we can do the following:

import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def f():
    a = { 'foo': None }
    # the following line will raise KeyError
    b = a['bar']

def g():
    f()

try:
    g()
except Exception as e:
    logger.error(str(e), exc_info=True)

And it will output:

'bar'
Traceback (most recent call last):
  File "<ipython-input-2-8ae09e08766b>", line 18, in <module>
    g()
  File "<ipython-input-2-8ae09e08766b>", line 14, in g
    f()
  File "<ipython-input-2-8ae09e08766b>", line 10, in f
    b = a['bar']
KeyError: 'bar'

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

_x000D_
_x000D_
var regex =/^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,64}$/;

 
function test() {

 if(regex.test(document.getElementById("txtPassword").value)===false)
 {
 alert("Min 6,Max 64,At Least One Uppercase Character,One Lowercase Character,One Numeric Value And One Special Character(!@#$%^&*) Required ");
 }
 else
 {
 alert("Success");
 }
}
_x000D_
<input type="text" id="txtPassword" />
<button id="testBtn" onclick=test()>CheckPassword</button>
_x000D_
_x000D_
_x000D_

How to customize an end time for a YouTube video?

Use parameters(seconds) i.e. youtube.com/v/VIDEO_ID?start=4&end=117

Live DEMO:
https://puvox.software/software/youtube_trimmer.php

What is Activity.finish() method doing exactly?

Also notice if you call finish() after an intent you can't go back to the previous activity with the "back" button

startActivity(intent);
finish();

Set ANDROID_HOME environment variable in mac

The above answer is correct. Works really well. There is also quick way to do this.

  1. Open command prompt
  2. Type - echo export "ANDROID_HOME=/Users/yourName/Library/Android/sdk" >> ~/.bash_profile

    Thats's it.

  3. Close your terminal.

  4. Open it again.

  5. Type - echo $ANDROID_HOME to check if the home is set.

mvn clean install vs. deploy vs. release

The clean, install and deploy phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.

mvn clean install

This command invokes the clean phase and then the install phase sequentially:

  • clean: removes files generated at build-time in a project's directory (target by default)
  • install: installs the package into the local repository, for use as a dependency in other projects locally.

mvn deploy

This command invokes the deploy phase:

  • deploy: copies the final package to the remote repository for sharing with other developers and projects.

mvn release

This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare and perform. As documented:

Preparing a release goes through the following release phases:

  • Check that there are no uncommitted changes in the sources
  • Check that there are no SNAPSHOT dependencies
  • Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
  • Transform the SCM information in the POM to include the final destination of the tag
  • Run the project tests against the modified POMs to confirm everything is in working order
  • Commit the modified POMs
  • Tag the code in the SCM with a version name (this will be prompted for)
  • Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
  • Commit the modified POMs

And then:

Performing a release runs the following release phases:

  • Checkout from an SCM URL with optional tag
  • Run the predefined Maven goals to release the project (by default, deploy site-deploy)

See also

Java String split removed empty values

you may have multiple separators, including whitespace characters, commas, semicolons, etc. take those in repeatable group with []+, like:

 String[] tokens = "a , b,  ,c; ;d,      ".split( "[,; \t\n\r]+" );

you'll have 4 tokens -- a, b, c, d

leading separators in the source string need to be removed before applying this split.

as answer to question asked:

String data = "5|6|7||8|9||";
String[] split = data.split("[\\| \t\n\r]+");

whitespaces added just in case if you'll have those as separators along with |

Reading from text file until EOF repeats last line

There's an alternative approach to this:

#include <iterator>
#include <algorithm>

// ...

    copy(istream_iterator<int>(iFile), istream_iterator<int>(),
         ostream_iterator<int>(cerr, "\n"));

Updating version numbers of modules in a multi-module Maven project

The given answer assumes that the project in question use project inheritance in addition to module aggregation. In fact those are distinct concepts:

https://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Project_Inheritance_vs_Project_Aggregation

Some projects may be an aggregation of modules, yet not have a parent-child relationship between aggregator POM and the aggregated modules. (There may be no parent-child relationship at all, or the child modules may use a separate POM altogether as the "parent".) In these situations the given answer will not work.

After much reading and experimentation, it turns out there is a way to use the Versions Maven Plugin to update not only the aggregator POM but also all aggregated modules as well; it is the processAllModules option. The following command must be done in the directory of the aggregator project:

mvn versions:set -DnewVersion=2.50.1-SNAPSHOT -DprocessAllModules

The Versions Maven Plugin will not only update the versions of all contained modules, it will also update inter-module dependencies!!!! This is a huge win and will save a lot of time and prevent all sorts of problems.

Of course don't forget to commit the changes in all modules, which you can also do with the same switch:

mvn versions:commit -DprocessAllModules

You may decide to dispense with the backup POMS altogether and do everything in one command:

mvn versions:set -DnewVersion=2.50.1-SNAPSHOT -DprocessAllModules -DgenerateBackupPoms=false

How to set UITextField height?

My pathetic contribution to this dumb problem. In IB set the style to none so you can set the height, then in IB set the class to be a subclass of UITextField that forces the style to be rounded rect.

@interface JLTForcedRoundedRectTextField : UITextField
@end

@implementation JLTForcedRoundedRectTextField
- (void)awakeFromNib
{
    self.borderStyle = UITextBorderStyleRoundedRect;
}
@end

It kept me from having to hack the XIB file or writing style code into my view controller.

How to config Tomcat to serve images from an external folder outside webapps?

After none of solutions based on defining XMLs worked for me, I found this answer very helpful. Took about a minute, and a small code change: I modified this line

this.basePath = getServletContext().getRealPath(getInitParameter("basePath"));

into

this.basePath = getInitParameter("basePath");

Importing Maven project into Eclipse

I was unable to import a Maven project with the steps suggested above until I figured out why it was not importing:

A maven project will not import if you have another Maven project with the same artifact id. Make sure that your project's artifact ID is unique in your eclipse workspace.

Opening a CHM file produces: "navigation to the webpage was canceled"

Moving to local folder is the quickest solution, nothing else worked for me esp because I was not admin on my system (can't edit registery etc), which is a typical case in a work environment.

Create a folder in C:\help drive, lets call it help and copy the files there and open.

Do not copy to mydocuments or anywhere else, those locations are usually on network drive in office setup and will not work.

What is the simplest way to convert array to vector?

Personally, I quite like the C++2011 approach because it neither requires you to use sizeof() nor to remember adjusting the array bounds if you ever change the array bounds (and you can define the relevant function in C++2003 if you want, too):

#include <iterator>
#include <vector>
int x[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(std::begin(x), std::end(x));

Obviously, with C++2011 you might want to use initializer lists anyway:

std::vector<int> v({ 1, 2, 3, 4, 5 });

Running Node.js in apache?

The common method for doing what you're looking to do is to run them side by side, and either proxy requests from apache to node.js based on domain / url, or simply have your node.js content be pulled from the node.js port. This later method works very well for having things like socket.io powered widgets on your site and such.


If you're going to be doing all of your dynamic content generation in node however, you might as well just use node.js as your primary webserver too, it does a very good job at serving both static and dynamic http requests.

See:

http://expressjs.com/

https://github.com/joyent/node/wiki/modules

How would one write object-oriented code in C?

Trivial example with an Animal and Dog: You mirror C++'s vtable mechanism (largely anyway). You also separate allocation and instantiation (Animal_Alloc, Animal_New) so we don't call malloc() multiple times. We must also explicitly pass the this pointer around.

If you were to do non-virtual functions, that's trival. You just don't add them to the vtable and static functions don't require a this pointer. Multiple inheritance generally requires multiple vtables to resolve ambiguities.

Also, you should be able to use setjmp/longjmp to do exception handling.

struct Animal_Vtable{
    typedef void (*Walk_Fun)(struct Animal *a_This);
    typedef struct Animal * (*Dtor_Fun)(struct Animal *a_This);

    Walk_Fun Walk;
    Dtor_Fun Dtor;
};

struct Animal{
    Animal_Vtable vtable;

    char *Name;
};

struct Dog{
    Animal_Vtable vtable;

    char *Name; // Mirror member variables for easy access
    char *Type;
};

void Animal_Walk(struct Animal *a_This){
    printf("Animal (%s) walking\n", a_This->Name);
}

struct Animal* Animal_Dtor(struct Animal *a_This){
    printf("animal::dtor\n");
    return a_This;
}

Animal *Animal_Alloc(){
    return (Animal*)malloc(sizeof(Animal));
}

Animal *Animal_New(Animal *a_Animal){
    a_Animal->vtable.Walk = Animal_Walk;
    a_Animal->vtable.Dtor = Animal_Dtor;
    a_Animal->Name = "Anonymous";
    return a_Animal;
}

void Animal_Free(Animal *a_This){
    a_This->vtable.Dtor(a_This);

    free(a_This);
}

void Dog_Walk(struct Dog *a_This){
    printf("Dog walking %s (%s)\n", a_This->Type, a_This->Name);
}

Dog* Dog_Dtor(struct Dog *a_This){
    // Explicit call to parent destructor
    Animal_Dtor((Animal*)a_This);

    printf("dog::dtor\n");

    return a_This;
}

Dog *Dog_Alloc(){
    return (Dog*)malloc(sizeof(Dog));
}

Dog *Dog_New(Dog *a_Dog){
    // Explict call to parent constructor
    Animal_New((Animal*)a_Dog);

    a_Dog->Type = "Dog type";
    a_Dog->vtable.Walk = (Animal_Vtable::Walk_Fun) Dog_Walk;
    a_Dog->vtable.Dtor = (Animal_Vtable::Dtor_Fun) Dog_Dtor;

    return a_Dog;
}

int main(int argc, char **argv){
    /*
      Base class:

        Animal *a_Animal = Animal_New(Animal_Alloc());
    */
    Animal *a_Animal = (Animal*)Dog_New(Dog_Alloc());

    a_Animal->vtable.Walk(a_Animal);

    Animal_Free(a_Animal);
}

PS. This is tested on a C++ compiler, but it should be easy to make it work on a C compiler.

Why I've got no crontab entry on OS X when using vim?

The error crontab: temp file must be edited in place is because of the way vim treats backup files.

To use vim with cron, add the following lines in your .bash_profile
export EDITOR=vim
alias crontab="VIM_CRONTAB=true crontab"

Source the file:
source .bash_profile

And then in your .vimrc add:
if $VIM_CRONTAB == "true" set nobackup set nowritebackup endif

This will disable backups when using vim with cron. And you will be able to use crontab -e to add/edit cronjobs.

On successfully saving your cronjob, you will see the message:
crontab: installing new crontab

Source:
http://drawohara.com/post/6344279/crontab-temp-file-must-be-edited-in-placeenter link description here

Getting Google+ profile picture url with user_id

Google had changed their policy so the old way for getting the Google profile image will not work now, which was

https://plus.google.com/s2/photos/profile/(user_id)?sz=150

New Way for doing this is

Request URL

https://www.googleapis.com/plus/v1/people/115950284...320?fields=image&key={YOUR_API_KEY}

That will give the Google profile image url in json format as given below

Response :

{
    "image": 
    {
         "url": "https://lh3.googleusercontent.com/-OkM...AANA/ltpH4BFZ2as/photo.jpg?sz=50"
    }
}

More parameters can be found to send with URL which you may need from here

For more detail you can also check the given question where I have answered for same type of problem How to get user image through user id in Google plus?

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


How to implement infinity in Java?

To use Infinity, you can use Double which supports Infinity: -

    System.out.println(Double.POSITIVE_INFINITY);
    System.out.println(Double.POSITIVE_INFINITY * -1);
    System.out.println(Double.NEGATIVE_INFINITY);

    System.out.println(Double.POSITIVE_INFINITY - Double.NEGATIVE_INFINITY);
    System.out.println(Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY);

OUTPUT: -

Infinity
-Infinity
-Infinity

Infinity 
NaN

Remove a specific string from an array of string

import java.util.*;

class Array {
    public static void main(String args[]) {
        ArrayList al = new ArrayList();
        al.add("google");
        al.add("microsoft");
        al.add("apple");
        System.out.println(al);
        //i only remove the apple//
        al.remove(2);
        System.out.println(al);
    }
}

Overflow:hidden dots at the end

Check the following snippet for your problem

_x000D_
_x000D_
div{_x000D_
  width : 100px;_x000D_
  overflow:hidden;_x000D_
  display:inline-block;_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<div>_x000D_
    The Alsos Mission was an Allied unit formed to investigate Axis scientific developments, especially nuclear, chemical and biological weapons, as part of the Manhattan Project during World War II. Colonel Boris Pash, a former Manhattan P_x000D_
</div>
_x000D_
_x000D_
_x000D_

Upgrade to python 3.8 using conda

Open Anaconda Prompt (base):

  1. Update conda:
conda update -n base -c defaults conda
  1. Create new environment with Python 3.8:
conda create -n python38 python=3.8
  1. Activate your new Python 3.8 environment:
conda activate python38
  1. Start Python 3.8:
python

Check last modified date of file in C#

Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.

The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.

  [TestMethod]
  public void TestLastModifiedTimeStamps()
  {
     var tempFile = Path.GetTempFileName();
     var lastModified = File.GetLastWriteTime(tempFile);
     using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
     {

     }
     Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
  }

See File.GetLastWriteTime seems to be returning 'out of date' value

Your options:

a) live with the occasional omissions.

b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).

c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.

/// <summary>
/// type to set signals or check for them using a central file 
/// </summary>
public class FileSignal
{
    /// <summary>
    /// path to the central file for signal control
    /// </summary>
    public string FilePath { get; private set; }

    /// <summary>
    /// numbers of retries when not able to retrieve (exclusive) file access
    /// </summary>
    public int MaxCollisions { get; private set; }

    /// <summary>
    /// timespan to wait until next try
    /// </summary>
    public TimeSpan SleepOnCollisionInterval { get; private set; }

    /// <summary>
    /// Timestamp of the last signal
    /// </summary>
    public DateTime LastSignal { get; private set; }

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
    /// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
    public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
    {
        FilePath = filePath;
        MaxCollisions = maxCollisions;
        SleepOnCollisionInterval = sleepOnCollisionInterval;
        LastSignal = GetSignalTimeStamp();
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>        
    public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
    {
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>        
    public FileSignal(string filePath) : this(filePath, 10)
    {
    }

    private Stream GetFileStream(FileAccess fileAccess)
    {
        var i = 0;
        while (true)
        {
            try
            {
                return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
            }
            catch (Exception e)
            {
                i++;
                if (i >= MaxCollisions)
                {
                    throw e;
                }
                Thread.Sleep(SleepOnCollisionInterval);
            };
        };
    }

    private DateTime GetSignalTimeStamp()
    {
        if (!File.Exists(FilePath))
        {
            return DateTime.MinValue;
        }
        using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if(stream.Length == 0)
            {
                return DateTime.MinValue;
            }
            using (var reader = new BinaryReader(stream))
            {
                return DateTime.FromBinary(reader.ReadInt64());
            };                
        }
    }

    /// <summary>
    /// overwrites the existing central file and writes the current time into it.
    /// </summary>
    public void Signal()
    {
        LastSignal = DateTime.Now;
        using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(LastSignal.ToBinary());
            }
        }
    }

    /// <summary>
    /// returns true if the file signal has changed, otherwise false.
    /// </summary>        
    public bool CheckIfSignalled()
    {
        var signal = GetSignalTimeStamp();
        var signalTimestampChanged = LastSignal != signal;
        LastSignal = signal;
        return signalTimestampChanged;
    }
}

Some tests for it:

    [TestMethod]
    public void TestSignal()
    {
        var fileSignal = new FileSignal(Path.GetTempFileName());
        var fileSignal2 = new FileSignal(fileSignal.FilePath);
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        fileSignal.Signal();
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsTrue(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
    }

What is referencedColumnName used for in JPA?

Quoting API on referencedColumnName:

The name of the column referenced by this foreign key column.

Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.

Q/A

Where this would be used?

When there is a composite PK in referenced table, then you need to specify column name you are referencing.

How can I check if a Perl array contains a particular value?

@files is an existing array

my @new_values =  grep(/^2[\d].[\d][A-za-z]?/,@files);

print join("\n", @new_values);

print "\n";

/^2[\d].[\d][A-za-z]?/ = vaues starting from 2 here you can put any regular expression

not-null property references a null or transient value

for followers, this error message can also mean "you have it referencing a foreign object that hasn't been saved to the DB yet" (even though it's there, and is non null).

SQL SERVER: Check if variable is null and then assign statement for Where Clause

is null can be used to check whether null data is coming from a query as in following example:

 declare @Mem varchar(20),@flag int
select @mem=MemberClub from [dbo].[UserMaster] where UserID=@uid
if(@Mem is null)
begin
    set @flag= 0;
end
else
begin
    set @flag=1;
end
return @flag;

How can I get a list of all classes within current module in Python?

import pyclbr
print(pyclbr.readmodule(__name__).keys())

Note that the stdlib's Python class browser module uses static source analysis, so it only works for modules that are backed by a real .py file.

How to print something when running Puppet client?

Just as alternative you may consider using execs... (I wouldn't recommend it though)

exec { 'this will output stuff':
  path      => '/bin',
  command   => 'echo Hello World!',
  logoutput => true,
}

So when you run puppet you should find some output like so:

notice: /Stage[main]//Exec[this will output stuff]/returns: Hello World!
notice: /Stage[main]//Exec[this will output stuff]/returns: executed successfully
notice: Finished catalog run in 0.08 seconds

The first line being logged output.

How to center the text in a JLabel?

The following constructor, JLabel(String, int), allow you to specify the horizontal alignment of the label.

JLabel label = new JLabel("The Label", SwingConstants.CENTER);

How do I properly 'printf' an integer and a string in C?

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

'ssh-keygen' is not recognized as an internal or external command

In my machine, ssh-keygen was available from powershell.

How do you pass view parameters when navigating from an action in JSF2?

The unintuitive thing about passing parameters in JSF is that you do not decide what to send (in the action), but rather what you wish to receive (in the target page).

When you do an action that ends with a redirect, the target page metadata is loaded and all required parameters are read and appended to the url as params.

Note that this is exactly the same mechanism as with any other JSF binding: you cannot read inputText's value from one place and have it write somewhere else. The value expression defined in viewParam is used both for reading (before the redirect) and for writing (after the redirect).

With your bean you just do:

@ManagedBean
@RequestScoped
public class MyBean {

private int id;

public String submit() {
    //Does stuff
    id = setID();
    return "success?faces-redirect=true&includeViewParams=true";
}

// setter and getter for id

If the receiving side has:

    <f:metadata>
        <f:viewParam name="id" value="#{myBean.id}" />
    </f:metadata>

It will do exactly what you want.

Remove all the elements that occur in one list from another

Use the Python set type. That would be the most Pythonic. :)

Also, since it's native, it should be the most optimized method too.

See:

http://docs.python.org/library/stdtypes.html#set

http://docs.python.org/library/sets.htm (for older python)

# Using Python 2.7 set literal format.
# Otherwise, use: l1 = set([1,2,6,8])
#
l1 = {1,2,6,8}
l2 = {2,3,5,8}
l3 = l1 - l2

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

jQuery: select all elements of a given class, except for a particular Id

Using the .not() method with selecting an entire element is also an option.

This way could be usefull if you want to do another action with that element directly.

$(".thisClass").not($("#thisId")[0].doAnotherAction()).doAction();

Font is not available to the JVM with Jasper Reports

sudo apt-get install msttcorefonts works (on our Ubuntu development environment), but is not a very good solution.

Instead, we bundled the fonts with our application based on this tip. Their JAR file bundles the following fonts,

  • Arial
  • Times New Roman
  • Courier New
  • Comic Sans MS
  • Georgia
  • Verdana
  • Monospaced

Direct Link to download jar: Maven ver 1.0. DynamicFonts

"Non-static method cannot be referenced from a static context" error

setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.

You may want to look into some basic object-oriented tutorials to see how static/instance members work.

How to delete files recursively from an S3 bucket

With s3cmd package installed on a Linux machine, you can do this

s3cmd rm s3://foo/bar --recursive

How do I do a bulk insert in mySQL using node.js

This is a fast "raw-copy-paste" snipped to push a file column in mysql with node.js >= 11

250k row in few seconds

'use strict';

const mysql = require('promise-mysql');
const fs = require('fs');
const readline = require('readline');

async function run() {
  const connection = await mysql.createConnection({
    host: '1.2.3.4',
    port: 3306,
    user: 'my-user',
    password: 'my-psw',
    database: 'my-db',
  });

  const rl = readline.createInterface({ input: fs.createReadStream('myfile.txt') });

  let total = 0;
  let buff = [];
  for await (const line of rl) {
    buff.push([line]);
    total++;
    if (buff.length % 2000 === 0) {
      await connection.query('INSERT INTO Phone (Number) VALUES ?', [buff]);
      console.log(total);
      buff = [];
    }
  }

  if (buff.length > 0) {
    await connection.query('INSERT INTO Phone (Number) VALUES ?', [buff]);
    console.log(total);
  }

  console.log('end');
  connection.close();
}

run().catch(console.log);

How to write and read java serialized objects into a file

Simple program to write objects to file and read objects from file.

_x000D_
_x000D_
package program;_x000D_
_x000D_
import java.io.File;_x000D_
import java.io.FileInputStream;_x000D_
import java.io.FileOutputStream;_x000D_
import java.io.ObjectInputStream;_x000D_
import java.io.ObjectOutputStream;_x000D_
import java.io.Serializable;_x000D_
_x000D_
public class TempList {_x000D_
_x000D_
  public static void main(String[] args) throws Exception {_x000D_
    Counter counter = new Counter(10);_x000D_
_x000D_
    File f = new File("MyFile.txt");_x000D_
    FileOutputStream fos = new FileOutputStream(f);_x000D_
    ObjectOutputStream oos = new ObjectOutputStream(fos);_x000D_
    oos.writeObject(counter);_x000D_
    oos.close();_x000D_
_x000D_
    FileInputStream fis = new FileInputStream(f);_x000D_
    ObjectInputStream ois = new ObjectInputStream(fis);_x000D_
    Counter newCounter = (Counter) ois.readObject();_x000D_
    System.out.println(newCounter.count);_x000D_
    ois.close();_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
class Counter implements Serializable {_x000D_
_x000D_
  private static final long serialVersionUID = -628789568975888036 L;_x000D_
_x000D_
  int count;_x000D_
_x000D_
  Counter(int count) {_x000D_
    this.count = count;_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

After running the program the output in your console window will be 10 and you can find the file inside Test folder by clicking on the icon show in below image.

enter image description here

How to concatenate two numbers in javascript?

Use

var value = "" + 5 + 6;

to force it to strings.

How do I force make/GCC to show me the commands?

Depending on your automake version, you can also use this:

make AM_DEFAULT_VERBOSITY=1

Reference: AM_DEFAULT_VERBOSITY

Note: I added this answer since V=1 did not work for me.

How do I bind to list of checkbox values with AngularJS?

I think the easiest workaround would be to use 'select' with 'multiple' specified:

<select ng-model="selectedfruit" multiple ng-options="v for v in fruit"></select>

Otherwise, I think you'll have to process the list to construct the list (by $watch()ing the model array bind with checkboxes).

How can I extract substrings from a string in Perl?

This just requires a small change to my last answer:

my ($guid, $scheme, $star) = $line =~ m{
    The [ ] Scheme [ ] GUID: [ ]
    ([a-zA-Z0-9-]+)          #capture the guid
    [ ]
    \(  (.+)  \)             #capture the scheme 
    (?:
        [ ]
        ([*])                #capture the star 
    )?                       #if it exists
}x;

Custom events in jQuery?

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Indexing vectors and arrays with +:

Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:

logic [31: 0] a_vect;
logic [0 :31] b_vect;
logic [63: 0] dword;
integer sel;
a_vect[ 0 +: 8] // == a_vect[ 7 : 0]
a_vect[15 -: 8] // == a_vect[15 : 8]
b_vect[ 0 +: 8] // == b_vect[0 : 7]
b_vect[15 -: 8] // == b_vect[8 :15]
dword[8*sel +: 8] // variable part-select with fixed width

If sel is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel is 7 then dword[8*(7) +: 8] == dword[63:56]

The value to the left always the starting index. The number to the right is the width and must be a positive constant. the + and - indicates to select the bits of a higher or lower index value then the starting index.

Assuming address is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2]) is the equivalent of if({address[2*pointer+1],address[2*pointer]})

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Your code should be something like this

$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM Users WHERE UserName LIKE '$username'";
echo $query;
$result = mysql_query($query);

if($result === FALSE) {
    die(mysql_error("error message for the user")); 
}

while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}

Once done with that, you would get the query printed on the screen. Try this query on your server and see if it produces the desired results. Most of the times the error is in the query. Rest of the code is correct.

Count number of times value appears in particular column in MySQL

SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name

Open file with associated application

This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.

var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
    Arguments = Path.GetFileName(path),
    UseShellExecute = true,
    WorkingDirectory = Path.GetDirectoryName(path),
    FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
    Verb = "OPEN"
};
Process.Start(pi)

Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.

Textarea to resize based on content length

You can check the content's height by setting to 1px and then reading the scrollHeight property:

_x000D_
_x000D_
function textAreaAdjust(element) {
  element.style.height = "1px";
  element.style.height = (25+element.scrollHeight)+"px";
}
_x000D_
<textarea onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea>
_x000D_
_x000D_
_x000D_

It works under Firefox 3, IE 7, Safari, Opera and Chrome.

Difference between number and integer datatype in oracle dictionary views

Integer is only there for the sql standard ie deprecated by Oracle.

You should use Number instead.

Integers get stored as Number anyway by Oracle behind the scenes.

Most commonly when ints are stored for IDs and such they are defined with no params - so in theory you could look at the scale and precision columns of the metadata views to see of no decimal values can be stored - however 99% of the time this will not help.

As was commented above you could look for number(38,0) columns or similar (ie columns with no decimal points allowed) but this will only tell you which columns cannot take decimals, and not what columns were defined so that INTS can be stored.

Suggestion: do a data profile on the number columns. Something like this:

 select max( case when trunc(column_name,0)=column_name then 0 else 1 end ) as has_dec_vals
 from table_name

jquery: get id from class selector

When you add a click event, this returns the element that has been clicked. So you can just use this.id;

$(".test").click(function(){
   alert(this.id); 
});

Example: http://jsfiddle.net/jonathon/rfbrp/

Laravel orderBy on a relationship

Using sortBy... could help.

$users = User::all()->with('rated')->get()->sortByDesc('rated.rating');

no such file to load -- rubygems (LoadError)

This is the first answer when Googling 'require': cannot load such file -- ubygems (LoadError) after Google autocorrected "ubygems" to "rubygems". Turns out this was an intentional change between Ruby 2.4 and 2.5 (Bug #14322). Scripts that detect the user gems directory without taking into account the ruby version will most likely fail.

Ruby 2.4

ruby -rubygems -e 'puts Gem.user_dir'

Ruby 2.5

ruby -rrubygems -e 'puts Gem.user_dir'

Reverse / invert a dictionary mapping

I would do it that way in python 2.

inv_map = {my_map[x] : x for x in my_map}

How to add action listener that listens to multiple buttons

Using my approach, you can write the button click event handler in the 'classical way', just like how you did it in VB or MFC ;)

Suppose we have a class for a frame window which contains 2 buttons:

class MainWindow {
    Jbutton searchButton;
    Jbutton filterButton;
}

You can use my 'router' class to route the event back to your MainWindow class:

class MainWindow {
    JButton searchButton;
    Jbutton filterButton;
    ButtonClickRouter buttonRouter = new ButtonClickRouter(this);
    
    void initWindowContent() {
        // create your components here...
        
        // setup button listeners
        searchButton.addActionListener(buttonRouter);
        filterButton.addActionListener(buttonRouter);
    }

    void on_searchButton() {
        // TODO your handler goes here...
    }
    
    void on_filterButton() {
        // TODO your handler goes here...
    }
}

Do you like it? :)

If you like this way and hate the Java's anonymous subclass way, then you are as old as I am. The problem of 'addActionListener(new ActionListener {...})' is that it squeezes all button handlers into one outer method which makes the programme look wired. (in case you have a number of buttons in one window)

Finally, the router class is at below. You can copy it into your programme without the need for any update.

Just one thing to mention: the button fields and the event handler methods must be accessible to this router class! To simply put, if you copy this router class in the same package of your programme, your button fields and methods must be package-accessible. Otherwise, they must be public.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ButtonClickRouter implements ActionListener {
    private Object target;

    ButtonClickRouter(Object target) {
        this.target = target;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        // get source button
        Object sourceButton = actionEvent.getSource();

        // find the corresponding field of the button in the host class
        Field fieldOfSourceButton = null;
        for (Field field : target.getClass().getDeclaredFields()) {
            try {
                if (field.get(target).equals(sourceButton)) {
                    fieldOfSourceButton = field;
                    break;
                }
            } catch (IllegalAccessException e) {
            }
        }

        if (fieldOfSourceButton == null)
            return;

        // make the expected method name for the source button
        // rule: suppose the button field is 'searchButton', then the method
        // is expected to be 'void on_searchButton()'
        String methodName = "on_" + fieldOfSourceButton.getName();

        // find such a method
        Method expectedHanderMethod = null;
        for (Method method : target.getClass().getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                expectedHanderMethod = method;
                break;
            }
        }

        if (expectedHanderMethod == null)
            return;

        // fire
        try {
            expectedHanderMethod.invoke(target);
        } catch (IllegalAccessException | InvocationTargetException e) { }
    }
}

I'm a beginner in Java (not in programming), so maybe there are anything inappropriate in the above code. Review it before using it, please.

Installing Numpy on 64bit Windows 7 with Python 2.7.3

It is not improbable, that programmers looking for python on windows, also use the Python Tools for Visual Studio. In this case it is easy to install additional packages, by taking advantage of the included "Python Environment" Window. "Overview" is selected within the window as default. You can select "Pip" there.

Then you can install numpy without additional work by entering numpy into the seach window. The coresponding "install numpy" instruction is already suggested.

Nevertheless I had 2 easy to solve Problems in the beginning:

  • "error: Unable to find vcvarsall.bat": This problem has been solved here. Although I did not find it at that time and instead installed the C++ Compiler for Python.
  • Then the installation continued but failed because of an additional inner exception. Installing .NET 3.5 solved this.

Finally the installation was done. It took some time (5 minutes), so don't cancel the process to early.

Django templates: If false?

Just ran into this again (certain I had before and came up with a less-than-satisfying solution).

For a tri-state boolean semantic (for example, using models.NullBooleanField), this works well:

{% if test.passed|lower == 'false' %} ... {% endif %}

Or if you prefer getting excited over the whole thing...

{% if test.passed|upper == 'FALSE' %} ... {% endif %}

Either way, this handles the special condition where you don't care about the None (evaluating to False in the if block) or True case.

How to print the data in byte array as characters?

Try it:

public static String print(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    for (byte b : bytes) {
        sb.append(String.format("0x%02X ", b));
    }
    sb.append("]");
    return sb.toString();
}

Example:

 public static void main(String []args){
    byte[] bytes = new byte[] { 
        (byte) 0x01, (byte) 0xFF, (byte) 0x2E, (byte) 0x6E, (byte) 0x30
    };

    System.out.println("bytes = " + print(bytes));
 }

Output: bytes = [ 0x01 0xFF 0x2E 0x6E 0x30 ]

How can I plot with 2 different y-axes?

I too suggests, twoord.stackplot() in the plotrix package plots with more of two ordinate axes.

data<-read.table(text=
"e0AL fxAL e0CO fxCO e0BR fxBR anos
 51.8  5.9 50.6  6.8 51.0  6.2 1955
 54.7  5.9 55.2  6.8 53.5  6.2 1960
 57.1  6.0 57.9  6.8 55.9  6.2 1965
 59.1  5.6 60.1  6.2 57.9  5.4 1970
 61.2  5.1 61.8  5.0 59.8  4.7 1975
 63.4  4.5 64.0  4.3 61.8  4.3 1980
 65.4  3.9 66.9  3.7 63.5  3.8 1985
 67.3  3.4 68.0  3.2 65.5  3.1 1990
 69.1  3.0 68.7  3.0 67.5  2.6 1995
 70.9  2.8 70.3  2.8 69.5  2.5 2000
 72.4  2.5 71.7  2.6 71.1  2.3 2005
 73.3  2.3 72.9  2.5 72.1  1.9 2010
 74.3  2.2 73.8  2.4 73.2  1.8 2015
 75.2  2.0 74.6  2.3 74.2  1.7 2020
 76.0  2.0 75.4  2.2 75.2  1.6 2025
 76.8  1.9 76.2  2.1 76.1  1.6 2030
 77.6  1.9 76.9  2.1 77.1  1.6 2035
 78.4  1.9 77.6  2.0 77.9  1.7 2040
 79.1  1.8 78.3  1.9 78.7  1.7 2045
 79.8  1.8 79.0  1.9 79.5  1.7 2050
 80.5  1.8 79.7  1.9 80.3  1.7 2055
 81.1  1.8 80.3  1.8 80.9  1.8 2060
 81.7  1.8 80.9  1.8 81.6  1.8 2065
 82.3  1.8 81.4  1.8 82.2  1.8 2070
 82.8  1.8 82.0  1.7 82.8  1.8 2075
 83.3  1.8 82.5  1.7 83.4  1.9 2080
 83.8  1.8 83.0  1.7 83.9  1.9 2085
 84.3  1.9 83.5  1.8 84.4  1.9 2090
 84.7  1.9 83.9  1.8 84.9  1.9 2095
 85.1  1.9 84.3  1.8 85.4  1.9 2100", header=T)

require(plotrix)
twoord.stackplot(lx=data$anos, rx=data$anos, 
                 ldata=cbind(data$e0AL, data$e0BR, data$e0CO),
                 rdata=cbind(data$fxAL, data$fxBR, data$fxCO),
                 lcol=c("black","red", "blue"),
                 rcol=c("black","red", "blue"), 
                 ltype=c("l","o","b"),
                 rtype=c("l","o","b"), 
                 lylab="Años de Vida", rylab="Hijos x Mujer", 
                 xlab="Tiempo",
                 main="Mortalidad/Fecundidad:1950–2100",
                 border="grey80")
legend("bottomright", c(paste("Proy:", 
                      c("A. Latina", "Brasil", "Colombia"))), cex=1,
        col=c("black","red", "blue"), lwd=2, bty="n",  
        lty=c(1,1,2), pch=c(NA,1,1) )

How to get the index of an element in an IEnumerable?

The way I'm currently doing this is a bit shorter than those already suggested and as far as I can tell gives the desired result:

 var index = haystack.ToList().IndexOf(needle);

It's a bit clunky, but it does the job and is fairly concise.

When is the finalize() method called in Java?

finalize() is called just before garbage collection. It is not called when an object goes out of scope. This means that you cannot know when or even if finalize() will be executed.

Example:

If your program end before garbage collector occur, then finalize() will not execute. Therefore, it should be used as backup procedure to ensure the proper handling of other resources, or for special use applications, not as the means that your program uses in its normal operation.

Hosting a Maven repository on github

The best solution I've been able to find consists of these steps:

  1. Create a branch called mvn-repo to host your maven artifacts.
  2. Use the github site-maven-plugin to push your artifacts to github.
  3. Configure maven to use your remote mvn-repo as a maven repository.

There are several benefits to using this approach:

  • Maven artifacts are kept separate from your source in a separate branch called mvn-repo, much like github pages are kept in a separate branch called gh-pages (if you use github pages)
  • Unlike some other proposed solutions, it doesn't conflict with your gh-pages if you're using them.
  • Ties in naturally with the deploy target so there are no new maven commands to learn. Just use mvn deploy as you normally would

The typical way you deploy artifacts to a remote maven repo is to use mvn deploy, so let's patch into that mechanism for this solution.

First, tell maven to deploy artifacts to a temporary staging location inside your target directory. Add this to your pom.xml:

<distributionManagement>
    <repository>
        <id>internal.repo</id>
        <name>Temporary Staging Repository</name>
        <url>file://${project.build.directory}/mvn-repo</url>
    </repository>
</distributionManagement>

<plugins>
    <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.1</version>
        <configuration>
            <altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
        </configuration>
    </plugin>
</plugins>

Now try running mvn clean deploy. You'll see that it deployed your maven repository to target/mvn-repo. The next step is to get it to upload that directory to GitHub.

Add your authentication information to ~/.m2/settings.xml so that the github site-maven-plugin can push to GitHub:

<!-- NOTE: MAKE SURE THAT settings.xml IS NOT WORLD READABLE! -->
<settings>
  <servers>
    <server>
      <id>github</id>
      <username>YOUR-USERNAME</username>
      <password>YOUR-PASSWORD</password>
    </server>
  </servers>
</settings>

(As noted, please make sure to chmod 700 settings.xml to ensure no one can read your password in the file. If someone knows how to make site-maven-plugin prompt for a password instead of requiring it in a config file, let me know.)

Then tell the GitHub site-maven-plugin about the new server you just configured by adding the following to your pom:

<properties>
    <!-- github server corresponds to entry in ~/.m2/settings.xml -->
    <github.global.server>github</github.global.server>
</properties>

Finally, configure the site-maven-plugin to upload from your temporary staging repo to your mvn-repo branch on Github:

<build>
    <plugins>
        <plugin>
            <groupId>com.github.github</groupId>
            <artifactId>site-maven-plugin</artifactId>
            <version>0.11</version>
            <configuration>
                <message>Maven artifacts for ${project.version}</message>  <!-- git commit message -->
                <noJekyll>true</noJekyll>                                  <!-- disable webpage processing -->
                <outputDirectory>${project.build.directory}/mvn-repo</outputDirectory> <!-- matches distribution management repository url above -->
                <branch>refs/heads/mvn-repo</branch>                       <!-- remote branch name -->
                <includes><include>**/*</include></includes>
                <repositoryName>YOUR-REPOSITORY-NAME</repositoryName>      <!-- github repo name -->
                <repositoryOwner>YOUR-GITHUB-USERNAME</repositoryOwner>    <!-- github username  -->
            </configuration>
            <executions>
              <!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
              <execution>
                <goals>
                  <goal>site</goal>
                </goals>
                <phase>deploy</phase>
              </execution>
            </executions>
        </plugin>
    </plugins>
</build>

The mvn-repo branch does not need to exist, it will be created for you.

Now run mvn clean deploy again. You should see maven-deploy-plugin "upload" the files to your local staging repository in the target directory, then site-maven-plugin committing those files and pushing them to the server.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building DaoCore 1.3-SNAPSHOT
[INFO] ------------------------------------------------------------------------
...
[INFO] --- maven-deploy-plugin:2.5:deploy (default-deploy) @ greendao ---
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.jar (77 KB at 2936.9 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.pom (3 KB at 1402.3 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/maven-metadata.xml (768 B at 150.0 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/maven-metadata.xml (282 B at 91.8 KB/sec)
[INFO] 
[INFO] --- site-maven-plugin:0.7:site (default) @ greendao ---
[INFO] Creating 24 blobs
[INFO] Creating tree with 25 blob entries
[INFO] Creating commit with SHA-1: 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] Updating reference refs/heads/mvn-repo from ab7afb9a228bf33d9e04db39d178f96a7a225593 to 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.595s
[INFO] Finished at: Sun Dec 23 11:23:03 MST 2012
[INFO] Final Memory: 9M/81M
[INFO] ------------------------------------------------------------------------

Visit github.com in your browser, select the mvn-repo branch, and verify that all your binaries are now there.

enter image description here

Congratulations!

You can now deploy your maven artifacts to a poor man's public repo simply by running mvn clean deploy.

There's one more step you'll want to take, which is to configure any poms that depend on your pom to know where your repository is. Add the following snippet to any project's pom that depends on your project:

<repositories>
    <repository>
        <id>YOUR-PROJECT-NAME-mvn-repo</id>
        <url>https://github.com/YOUR-USERNAME/YOUR-PROJECT-NAME/raw/mvn-repo/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Now any project that requires your jar files will automatically download them from your github maven repository.

Edit: to avoid the problem mentioned in the comments ('Error creating commit: Invalid request. For 'properties/name', nil is not a string.'), make sure you state a name in your profile on github.

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

How to split a string content into an array of strings in PowerShell?

As of PowerShell 2, simple:

$recipients = $addresses -split "; "

Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplit to force case-sensitivity. See about_Split for more details.

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

For iPhone 5.5" display you need to change the simulator to "Physical Size" on iPhone 8 Plus

Physical size

window.close() doesn't work - Scripts may close only the windows that were opened by it

You can't close a current window or any window or page that is opened using '_self' But you can do this

var customWindow = window.open('', '_blank', '');
    customWindow.close();

Select random lines from a file

seq 1 100 | python3 -c 'print(__import__("random").choice(__import__("sys").stdin.readlines()))'

How to concatenate two layers in keras?

You can experiment with model.summary() (notice the concatenate_XX (Concatenate) layer size)

# merge samples, two input must be same shape
inp1 = Input(shape=(10,32))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=0) # Merge data must same row column
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge row must same column size
inp1 = Input(shape=(20,10))
inp2 = Input(shape=(32,10))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

# merge column must same row size
inp1 = Input(shape=(10,20))
inp2 = Input(shape=(10,32))
cc1 = concatenate([inp1, inp2],axis=1)
output = Dense(30, activation='relu')(cc1)
model = Model(inputs=[inp1, inp2], outputs=output)
model.summary()

You can view notebook here for detail: https://nbviewer.jupyter.org/github/anhhh11/DeepLearning/blob/master/Concanate_two_layer_keras.ipynb

How can I run MongoDB as a Windows service?

The simplest way is,

  1. Create folder C:\data\db
  2. Create file C:\data\db\log.txt
  3. Open command prompt as "Run as Administrator" and make sure the mogodb bin directory path is correct and write

    C:\Program Files\MongoDB\Server\3.4\bin> mongod.exe --install mongod --dbpath="c:\data\db" --logpath="c:\data\db\log.txt" 
    
  4. Start mongodb service:

    net run MongoDB
    

PHP mail not working for some reason

For HostGator, you need to use the following for your headers:

$headers = 'From: [email protected]' . " " .
'Reply-To: [email protected]' . " " .
'X-Mailer: PHP/' . phpversion();

It only worked for me when the from user was host e-mail while the Reply-To can be something different e.g. From: [email protected], Reply-To: [email protected]

http://support.hostgator.com/articles/specialized-help/technical/php-email-from-header http://support.hostgator.com/articles/specialized-help/technical/how-to-use-sendmail-with-php

convert a JavaScript string variable to decimal/money

I made a little helper function to do this and catch all malformed data

function convertToPounds(str) { 
    var n = Number.parseFloat(str);
    if(!str || isNaN(n) || n < 0) return 0;
    return n.toFixed(2);
}

Demo is here

jQuery table sort

If you want to avoid all the bells and whistles then may I suggest this simple sortElements plugin. Usage:

var table = $('table');

$('.sortable th')
    .wrapInner('<span title="sort this column"/>')
    .each(function(){

        var th = $(this),
            thIndex = th.index(),
            inverse = false;

        th.click(function(){

            table.find('td').filter(function(){

                return $(this).index() === thIndex;

            }).sortElements(function(a, b){

                if( $.text([a]) == $.text([b]) )
                    return 0;

                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;

            }, function(){

                // parentNode is the element we want to move
                return this.parentNode; 

            });

            inverse = !inverse;

        });

    });

And a demo. (click the "city" and "facility" column-headers to sort)

Converting Float to Dollars and Cents

you said that:

`mony = float(1234.5)
print(money)      #output is 1234.5
'${:,.2f}'.format(money)
print(money)

did not work.... Have you coded exactly that way? This should work (see the little difference):

money = float(1234.5)      #next you used format without printing, nor affecting value of "money"
amountAsFormattedString = '${:,.2f}'.format(money)
print( amountAsFormattedString )

Where's my JSON data in my incoming Django request?

Its important to remember Python 3 has a different way to represent strings - they are byte arrays.

Using Django 1.9 and Python 2.7 and sending the JSON data in the main body (not a header) you would use something like:

mydata = json.loads(request.body)

But for Django 1.9 and Python 3.4 you would use:

mydata = json.loads(request.body.decode("utf-8"))

I just went through this learning curve making my first Py3 Django app!

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

This is all perfectly normal. Microsoft added sequences in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look here for some explanation.

If you want to have the old behaviour, you can:

  1. use trace flag 272 - this will cause a log record to be generated for each generated identity value. The performance of identity generation may be impacted by turning on this trace flag.
  2. use a sequence generator with the NO CACHE setting (http://msdn.microsoft.com/en-us/library/ff878091.aspx)

Save matplotlib file to a directory

According to the docs savefig accepts a file path, so all you need is to specify a full (or relative) path instead of a file name.

HTML input textbox with a width of 100% overflows table cells

You could use the CSS3 box-sizing property to include the external padding and border:

input[type="text"] {
     width: 100%; 
     box-sizing: border-box;
     -webkit-box-sizing:border-box;
     -moz-box-sizing: border-box;
}

angular-cli server - how to proxy API requests to another server?

UPDATE 2017

Better documentation is now available and you can use both JSON and JavaScript based configurations: angular-cli documentation proxy

sample https proxy configuration

{
  "/angular": {
     "target":  {
       "host": "github.com",
       "protocol": "https:",
       "port": 443
     },
     "secure": false,
     "changeOrigin": true,
     "logLevel": "info"
  }
}

To my knowledge with Angular 2.0 release setting up proxies using .ember-cli file is not recommended. official way is like below

  1. edit "start" of your package.json to look below

    "start": "ng serve --proxy-config proxy.conf.json",

  2. create a new file called proxy.conf.json in the root of the project and inside of that define your proxies like below

    {
      "/api": {
        "target": "http://api.yourdomai.com",
        "secure": false
      }
    }
    
  3. Important thing is that you use npm start instead of ng serve

Read more from here : Proxy Setup Angular 2 cli

How to disable and then enable onclick event on <div> with javascript

To enable use bind() method

$("#id").bind("click",eventhandler);

call this handler

 function  eventhandler(){
      alert("Bind click")
    }

To disable click useunbind()

$("#id").unbind("click");

pycharm convert tabs to spaces automatically

For me it was having a file called ~/.editorconfig that was overriding my tab settings. I removed that (surely that will bite me again someday) but it fixed my pycharm issue

Pandas: Setting no. of max rows

As @hanleyhansen noted in a comment, as of version 0.18.1, the display.height option is deprecated, and says "use display.max_rows instead". So you just have to configure it like this:

pd.set_option('display.max_rows', 500)

See the Release Notes — pandas 0.18.1 documentation:

Deprecated display.height, display.width is now only a formatting option does not control triggering of summary, similar to < 0.11.0.

What is the best way to remove accents (normalize) in a Python unicode string?

perfplot

import unicodedata
from random import choice

import perfplot
import regex
import text_unidecode


def remove_accent_chars_regex(x: str):
    return regex.sub(r'\p{Mn}', '', unicodedata.normalize('NFKD', x))


def remove_accent_chars_join(x: str):
    # answer by MiniQuark
    # https://stackoverflow.com/a/517974/7966259
    return u"".join([c for c in unicodedata.normalize('NFKD', x) if not unicodedata.combining(c)])


perfplot.show(
    setup=lambda n: ''.join([choice('Málaga François Phút Hon ??') for i in range(n)]),
    kernels=[
        remove_accent_chars_regex,
        remove_accent_chars_join,
        text_unidecode.unidecode,
    ],
    labels=['regex', 'join', 'unidecode'],
    n_range=[2 ** k for k in range(22)],
    equality_check=None, relative_to=0, xlabel='str len'
)

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);

What's the difference between struct and class in .NET?

From Microsoft's Choosing Between Class and Struct ...

As a rule of thumb, the majority of types in a framework should be classes. There are, however, some situations in which the characteristics of a value type make it more appropriate to use structs.

? CONSIDER a struct instead of a class:

  • If instances of the type are small and commonly short-lived or are commonly embedded in other objects.

X AVOID a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable. (cannot be changed)
  • It will not have to be boxed frequently.

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

I searched for the error in the web and came to this page. I am using Visual Studio 2015 and this is my first MVC project.

If you miss the @ symbol before the render section you will get the same error. I would like to share this for future beginners.

 @RenderSection("headscripts", required: false)

Formatting struct timespec

I wanted to ask the same question. Here is my current solution to obtain a string like this: 2013-02-07 09:24:40.749355372 I am not sure if there is a more straight forward solution than this, but at least the string format is freely configurable with this approach.

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

#define NANO 1000000000L

// buf needs to store 30 characters
int timespec2str(char *buf, uint len, struct timespec *ts) {
    int ret;
    struct tm t;

    tzset();
    if (localtime_r(&(ts->tv_sec), &t) == NULL)
        return 1;

    ret = strftime(buf, len, "%F %T", &t);
    if (ret == 0)
        return 2;
    len -= ret - 1;

    ret = snprintf(&buf[strlen(buf)], len, ".%09ld", ts->tv_nsec);
    if (ret >= len)
        return 3;

    return 0;
}

int main(int argc, char **argv) {
    clockid_t clk_id = CLOCK_REALTIME;
    const uint TIME_FMT = strlen("2012-12-31 12:59:59.123456789") + 1;
    char timestr[TIME_FMT];

    struct timespec ts, res;
    clock_getres(clk_id, &res);
    clock_gettime(clk_id, &ts);

    if (timespec2str(timestr, sizeof(timestr), &ts) != 0) {
        printf("timespec2str failed!\n");
        return EXIT_FAILURE;
    } else {
        unsigned long resol = res.tv_sec * NANO + res.tv_nsec;
        printf("CLOCK_REALTIME: res=%ld ns, time=%s\n", resol, timestr);
        return EXIT_SUCCESS;
    }
}

output:

gcc mwe.c -lrt 
$ ./a.out 
CLOCK_REALTIME: res=1 ns, time=2013-02-07 13:41:17.994326501

intellij idea - Error: java: invalid source release 1.9

For anyone struggling with this issue who tried DeanM's solution but to no avail, there's something else worth checking, which is the version of the JDK you have configured for your project. What I'm trying to say is that if you have configured JDK 8u191 (for example) for your project, but have the language level set to anything higher than 8, you're gonna get this error.

In this case, it's probably better to ask whoever's in charge of the project, which version of the JDK would be preferable to compile the sources.

Detect if a page has a vertical scrollbar?

Let's bring this question back from the dead ;) There is a reason Google doesn't give you a simple solution. Special cases and browser quirks affect the calculation, and it is not as trivial as it seems to be.

Unfortunately, there are problems with the solutions outlined here so far. I don't mean to disparage them at all - they are great starting points and touch on all the key properties needed for a more robust approach. But I wouldn't recommend copying and pasting the code from any of the other answers because

  • they don't capture the effect of positioned content in a way that is reliable cross-browser. The answers which are based on body size miss this entirely (the body is not the offset parent of such content unless it is positioned itself). And those answers checking $( document ).width() and .height() fall prey to jQuery's buggy detection of document size.
  • Relying on window.innerWidth, if the browser supports it, makes your code fail to detect scroll bars in mobile browsers, where the width of the scroll bar is generally 0. They are just shown temporarily as an overlay and don't take up space in the document. Zooming on mobile also becomes a problem that way (long story).
  • The detection can be thrown off when people explicitly set the overflow of both the html and body element to non-default values (what happens then is a little involved - see this description).
  • In most answers, body padding, borders or margins are not detected and distort the results.

I have spent more time than I would have imagined on a finding a solution that "just works" (cough). The algorithm I have come up with is now part of a plugin, jQuery.isInView, which exposes a .hasScrollbar method. Have a look at the source if you wish.

In a scenario where you are in full control of the page and don't have to deal with unknown CSS, using a plugin may be overkill - after all, you know which edge cases apply, and which don't. However, if you need reliable results in an unknown environment, then I don't think the solutions outlined here will be enough. You are better off using a well-tested plugin - mine or anybody elses.

Adb install failure: INSTALL_CANCELED_BY_USER

I had the same problem before. Here was my solution:

  1. Go to Setting ? find Developer options in System, and click.
  2. TURN ON install via USB in the Debuging section.
  3. Try Run app in Android Studio again!

How do I add a Fragment to an Activity with a programmatically created content view

Here is what I came up with after reading Tony Wong's comment:

public class DebugExampleTwo extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addFragment(android.R.id.content,
                    new DebugExampleTwoFragment(),
                    DebugExampleTwoFragment.FRAGMENT_TAG);
    }

}

...

public abstract class BaseActivity extends Activity {

    protected void addFragment(@IdRes int containerViewId,
                               @NonNull Fragment fragment,
                               @NonNull String fragmentTag) {
        getSupportFragmentManager()
                .beginTransaction()
                .add(containerViewId, fragment, fragmentTag)
                .disallowAddToBackStack()
                .commit();
    }

    protected void replaceFragment(@IdRes int containerViewId,
                                   @NonNull Fragment fragment,
                                   @NonNull String fragmentTag,
                                   @Nullable String backStackStateName) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(containerViewId, fragment, fragmentTag)
                .addToBackStack(backStackStateName)
                .commit();
    }

}

...

public class DebugExampleTwoFragment extends Fragment {

    public static final String FRAGMENT_TAG = 
        BuildConfig.APPLICATION_ID + ".DEBUG_EXAMPLE_TWO_FRAGMENT_TAG";

    // ...

}

Kotlin

If you are using Kotlin make sure to take a look at what the Kotlin extensions by Google provide or just write your own.

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.

A possible solution is

  • Download Xcode 10.2 from a direkt link (not from App Store).
  • Rename it for example to Xcode102.
  • Put it into /Applications. It's possible to have multiple Xcode versions in the same directory.
  • Create a symbolic link in Terminal.app to have access to the 12.2 device support folder in Xcode 10.2

    ln -s /Applications/Xcode102.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/12.2\ \(16E226\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
    

You can move Xcode 10.2 to somewhere else but then you have to adjust the path.

Now Xcode 10.1 supports devices running iOS 12.2

How to remove stop words using nltk or python

I will show you some example First I extract the text data from the data frame (twitter_df) to process further as following

     from nltk.tokenize import word_tokenize
     tweetText = twitter_df['text']

Then to tokenize I use the following method

     from nltk.tokenize import word_tokenize
     tweetText = tweetText.apply(word_tokenize)

Then, to remove stop words,

     from nltk.corpus import stopwords
     nltk.download('stopwords')

     stop_words = set(stopwords.words('english'))
     tweetText = tweetText.apply(lambda x:[word for word in x if word not in stop_words])
     tweetText.head()

I Think this will help you

String concatenation in MySQL

Try:

select concat(first_name,last_name) as "Name" from test.student

or, better:

select concat(first_name," ",last_name) as "Name" from test.student

document.all vs. document.getElementById

Actually, document.all is only minimally comparable to document.getElementById. You wouldn't use one in place of the other, they don't return the same things.

If you were trying to filter through browser capabilities you could use them as in Marcel Korpel's answer like this:

if(document.getElementById){  //DOM
    element = document.getElementById(id);
} else if (document.all) {    //IE
    element = document.all[id];
} else if (document.layers){  //Netscape < 6
    element = document.layers[id];
}


But, functionally, document.getElementsByTagName('*') is more equivalent to document.all.

For example, if you were actually going to use document.all to examine all the elements on a page, like this:

var j = document.all.length;
for(var i = 0; i < j; i++){
   alert("Page element["+i+"] has tagName:"+document.all(i).tagName);
}

you would use document.getElementsByTagName('*') instead:

var k = document.getElementsByTagName("*");
var j = k.length; 
for (var i = 0; i < j; i++){
    alert("Page element["+i+"] has tagName:"+k[i].tagName); 
}

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

I faced a similar issue. I checked for the below:

  1. if ssh is not installed on your machine, you will have to install it firstly. (You will get a message saying ssh is not recognized as a command).
  2. Port 22 is open or not on the server you are trying to ssh.
  3. If the control of remote server is in your hands and you have permissions, try to disable firewall on it.
  4. Try to ssh again.

If port is not an issue then you would have to check for firewall settings as it is the one that is blocking your connection.

For me too it was a firewall issue between my machine and remote server.I disabled the firewall on the remote server and I was able to make a connection using ssh.

How can I view an old version of a file with Git?

Doing this by date looks like this if the commit happened within the last 90 days:

git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt

Note that HEAD@{2013-02-25} means "where HEAD was on 2013-02-25" in this repository (using the reflog), not "the last commit before 2013-02-25 in this branch in history".

This is important! It means that, by default, this method only works for history within the last 90 days. Otherwise, you need to do this:

git show $(git rev-list -1 --before="2013-02-26" HEAD):./fileInCurrentDirectory.txt

How to iterate through a String

If you want to use enhanced loop, you can convert the string to charArray

for (char ch : exampleString.toCharArray()) {
  System.out.println(ch);
}

Anaconda / Python: Change Anaconda Prompt User Path

If you want to access folder you specified using Anaconda Prompt, try typing

cd C:\Users\u354590

Lightbox to show videos from Youtube and Vimeo?

I've had a LOT of trouble with pretty photo and IE9. I also had issues with fancybox in IE.

For youtube.com, I'm having a lot of luck with CeeBox.

http://catcubed.com/2008/12/23/ceebox-a-thickboxvideobox-mashup/

Indexes of all occurrences of character in a string

String word = "bannanas";

String guess = "n";

String temp = word;

while(temp.indexOf(guess) != -1) {
     int index = temp.indexOf(guess);
     System.out.println(index);
     temp = temp.substring(index + 1);
}

Push to GitHub without a password using ssh-key

In case you are indeed using the SSH URL, but still are asked for username and password when git pushing:

git remote set-url origin [email protected]:<Username>/<Project>.git

You should try troubleshooting with:

ssh -vT [email protected]

Below is a piece of sample output:

...
debug1: Trying private key: /c/Users/Yuci/.ssh/id_rsa
debug1: Trying private key: /c/Users/Yuci/.ssh/id_dsa
debug1: Trying private key: /c/Users/Yuci/.ssh/id_ecdsa
debug1: Trying private key: /c/Users/Yuci/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).

I actually have already added the public key to GitHub before, and I also have the private key locally. However, my private key is of a different name called /c/Users/Yuci/.ssh/github_rsa.

According to the sample output, Git is trying /c/Users/Yuci/.ssh/id_rsa, which I don't have. Therefore, I could simply copy github_rsa to id_rsa in the same directory.

cp /c/Users/Yuci/.ssh/github_rsa /c/Users/Yuci/.ssh/id_rsa

Now when I run ssh -vT [email protected] again, I have:

...
debug1: Trying private key: /c/Users/Yuci/.ssh/id_rsa
debug1: Authentication succeeded (publickey).
...
Hi <my username>! You've successfully authenticated, but GitHub does not provide shell access.
...

And now I can push to GitHub without being asked for username and password :-)

Tomcat 7 is not running on browser(http://localhost:8080/ )

You may face two errors while testing tomcat server startup.

  1. Error in the Eclipse inbuilt browser - This page can’t be displayed Turn on TLS 1.0, TLS 1.1, and TLS 1.2 in Advanced settings and try connecting to https://localhost:8080 again. If this error persists, it is possible that this site uses an unsupported protocol. Please contact the site administrator.
  2. 404 error in the normal browsers.

Fixes -

  1. For the eclipse browser error, check whether you are using secured URL - https://localhost:8080. This should be http://localhost:8080
  2. For the 404 error: Go to Tomcat server in the console. Do a right click, select properties. In the properties window, Click "Switch location" and then click OK. Followed by that, Go to Tomcat server in the console, double click it, Under "server locations" select "Use Tomcat installation" radio button. Save it.

The reason for choosing this option is, When the default option is given as eclipse location, we will see 404 error as it changes Catalina parameters (sometimes). But if we change it to Tomcat location, it works fine.

How to get numeric position of alphabets in java?

Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.

This sounds like homework. If so, please tag it as such.

Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.

Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.

Word-wrap in an HTML table

Problem with

<td style="word-break:break-all;">longtextwithoutspace</td>

is that it will work not so good when text has some spaces, e.g.

<td style="word-break:break-all;">long text with andthenlongerwithoutspaces</td>

If word andthenlongerwithoutspaces fits into table cell in one line but long text with andthenlongerwithoutspaces does not, the long word will be broken in two, instead of being wrapped.

Alternative solution: insert U+200B (ZWSP), U+00AD (soft hyphen) or U+200C (ZWNJ) in every long word after every, say, 20th character (however, see warning below):

_x000D_
_x000D_
td {_x000D_
  border: 1px solid;_x000D_
}
_x000D_
<table style="width: 100%;">_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div style="word-wrap: break-word;">_x000D_
        Looooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooooooooo&#xAD;oooooooooooooong word_x000D_
      </div>_x000D_
    </td>_x000D_
    <td><span style="display: inline;">Short word</span></td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Warning: inserting additional, zero-length characters does not affect reading. However, it does affect text copied into clipboard (these characters are of course copied as well). If the clipboard text is later used in some search function in the web app... search is going to be broken. Although this solution can be seen in some well known web applications, avoid if possible.

Warning: when inserting additional characters, you should not separate multiple code points within grapheme. See https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries for more info.

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

How to clear browser cache with php?

It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.

You can do it by subfolders (example /css/v1/style.css) or by filename (example: css/style_v1.css) or even by setting different folders for your website, example:

www.mywebsite.com/site1

www.mywebsite.com/site2

www.mywebsite.com/site3

And use a .htaccess or even change httpd.conf to redirect to your current application.

If's about one image or page:

    <?$time = date("H:i:s");?>
    <img src="myfile.jpg?time=<?$time;?>">

You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.

Creating Roles in Asp.net Identity MVC 5

My application was hanging on startup when I used Peter Stulinski & Dave Gordon's code samples with EF 6.0. I changed:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

to

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(**context**));

Which makes sense when in the seed method you don't want instantiate another instance of the ApplicationDBContext. This might have been compounded by the fact that I had Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); in the constructor of ApplicationDbContext

String comparison - Android

This one work for me:

 if (email.equals("[email protected]") && pass.equals("123ss") ){
        Toast.makeText(this,"Logged in",Toast.LENGTH_LONG).show();
    }
    else{

        Toast.makeText(this,"Logged out",Toast.LENGTH_LONG).show();
    }

What does %s and %d mean in printf in the C language?

"%s%d%s%d\n" is the format string; it tells the printf function how to format and display the output. Anything in the format string that doesn't have a % immediately in front of it is displayed as is.

%s and %d are conversion specifiers; they tell printf how to interpret the remaining arguments. %s tells printf that the corresponding argument is to be treated as a string (in C terms, a 0-terminated sequence of char); the type of the corresponding argument must be char *. %d tells printf that the corresponding argument is to be treated as an integer value; the type of the corresponding argument must be int. Since you're coming from a Java background, it's important to note that printf (like other variadic functions) is relying on you to tell it what the types of the remaining arguments are. If the format string were "%d%s%d%s\n", printf would attempt to treat "Length of string" as an integer value and i as a string, with tragic results.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

In my case, I was getting this error in AndroidStudio 4.1.1 while updating compileSdkVersion to 29.

If you are having dependent project in build.gradle, All you need to do is Update same compileSdkVersion in dependent project's build.gradle as well.

Steps:

  1. Click on your app folder in Project view of AndroidStudio.
  2. Select Open Module Settings.
  3. In Project Structure >> Check how many modules are there?
  4. If there are more than one modules, you will have to update compileSdkVersion, buildToolsVersion & Project dependency as well.

That worked for me :)

Use CSS3 transitions with gradient backgrounds

Based on the css code in your question, I have try code as follows and it works for me (run the code snippet), and please try by yourself :

_x000D_
_x000D_
#container div a {_x000D_
  display: inline-block;_x000D_
  margin-top: 10%;_x000D_
  padding: 1em 2em;_x000D_
  font-size: 2em;_x000D_
  color: #fff;_x000D_
  font-family: arial, sans-serif;_x000D_
  text-decoration: none;_x000D_
  border-radius: 0.3em;_x000D_
  position: relative;_x000D_
  background-color: #ccc;_x000D_
  background-image: linear-gradient(to top, #C0357E, #EE5840);_x000D_
  -webkit-backface-visibility: hidden;_x000D_
  z-index: 1;_x000D_
}_x000D_
     _x000D_
#container div a:after {_x000D_
  position: absolute;_x000D_
  content: '';_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  border-radius: 0.3em;_x000D_
  background-image: linear-gradient(to top, #6d8aa0, #343436);_x000D_
  transition: opacity 0.5s ease-out;_x000D_
  z-index: 2;_x000D_
  opacity: 0;_x000D_
}_x000D_
    _x000D_
#container div a:hover:after {_x000D_
  opacity: 1;_x000D_
}_x000D_
#container div a span {_x000D_
  position: relative;_x000D_
  z-index: 3;_x000D_
}
_x000D_
<div id="container"><div><a href="#"><span>Press Me</span></a></div></div>
_x000D_
_x000D_
_x000D_

Based on the css code in your question, I have try code as follows and it works for me, and please try by yourself :

    #container div a {
  display: inline-block;
  margin-top: 10%;
  padding: 1em 2em;
  font-size: 2em;
  color: #fff;
  font-family: arial, sans-serif;
  text-decoration: none;
  border-radius: 0.3em;
  position: relative;
  background-color: #ccc;
  background-image: linear-gradient(to top, #C0357E, #EE5840);
  -webkit-backface-visibility: hidden;
  z-index: 1;
}

#container div a:after {
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 0.3em;
  background-image: linear-gradient(to top, #6d8aa0, #343436);
  transition: opacity 0.5s ease-out;
  z-index: 2;
  opacity: 0;
}

#container div a:hover:after {
  opacity: 1;
}
#container div a span {
  position: relative;
  z-index: 3;
}

Does it works for you? Change the color based on your need :)

How to do multiline shell script in Ansible

https://support.ansible.com/hc/en-us/articles/201957837-How-do-I-split-an-action-into-a-multi-line-format-

mentions YAML line continuations.

As an example (tried with ansible 2.0.0.2):

---
- hosts: all
  tasks:
    - name: multiline shell command
      shell: >
        ls --color
        /home
      register: stdout

    - name: debug output
      debug: msg={{ stdout }}

The shell command is collapsed into a single line, as in ls --color /home

How to read from standard input in the console?

Cleanly read in a couple prompted values:

// Create a single reader which can be called multiple times
reader := bufio.NewReader(os.Stdin)
// Prompt and read
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Print("Enter More text: ")
text2, _ := reader.ReadString('\n')
// Trim whitespace and print
fmt.Printf("Text1: \"%s\", Text2: \"%s\"\n",
    strings.TrimSpace(text), strings.TrimSpace(text2))

Here's a run:

Enter text: Jim
Enter More text: Susie
Text1: "Jim", Text2: "Susie"

Get list of databases from SQL Server

Don't Get confused, Use the below simple query to get all the databases,

select * from sys.databases

If u need only the User defined databases;

select * from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb'); 

Some of the System database names are (resource,distribution,reportservice,reportservicetempdb) just insert it into the query. If u have the above db's in your machine as default.

read word by word from file in C++

If I may I could give you some new code for the same task, in my code you can create a so called 'document'(not really)and it is saved, and can be opened up again. It is also stored as a string file though(not a document). Here is the code:

#include "iostream"

#include "windows.h"

#include "string"

#include "fstream"

using namespace std;

int main() {

string saveload;


cout << "---------------------------" << endl;
cout << "|enter 'text' to write your document    |" << endl;
cout << "|enter 'open file' to open the document |" << endl;
cout << "----------------------------------------" << endl;
while (true){
    getline(cin, saveload);

    if (saveload == "open file"){
        string filenamet;
        cout << "file name? " << endl;
        getline(cin, filenamet, '*');
        ifstream loadFile;

        loadFile.open(filenamet, ifstream::in);

        cout << "the text you entered was: ";

        while (loadFile.good()){

            cout << (char)loadFile.get();

            Sleep(100);
        }

        cout << "" << endl;

        loadFile.close();

    }

    if (saveload == "text") {
        string filename;
        cout << "file name: " << endl;
        getline(cin, filename,'*');
        string textToSave;
        cout << "Enter your text: " << endl;
        getline(cin, textToSave,'*');

        ofstream saveFile(filename);

        saveFile << textToSave;

        saveFile.close();

    }
}
return 0;
}

Just take this code and change it to serve your purpose. DREAM BIG,THINK BIG, DO BIG

Difference between File.separator and slash in paths

OK let's inspect some code.
File.java lines 428 to 435 in File.<init>:

String p = uri.getPath();
if (p.equals(""))
    throw new IllegalArgumentException("URI path component is empty");

// Okay, now initialize
p = fs.fromURIPath(p);
if (File.separatorChar != '/')
p = p.replace('/', File.separatorChar);

And let's read fs/*(FileSystem)*/.fromURIPath() docs:

java.io.FileSystem
public abstract String fromURIPath(String path)
Post-process the given URI path string if necessary. This is used on win32, e.g., to transform "/c:/foo" into "c:/foo". The path string still has slash separators; code in the File class will translate them after this method returns.

This means FileSystem.fromURIPath() does post processing on URI path only in Windows, and because in the next line:

p = p.replace('/', File.separatorChar);

It replaces each '/' with system dependent seperatorChar, you can always be sure that '/' is safe in every OS.

Get full path of a file with FileUpload Control

This dumps the file in your temp folder with file name, then after that you can call it and not worry about it. Because it will get deleted if it is in your temp folder for an amount of days.

string filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(),".xls"));
                File.WriteAllBytes(filename, FileUploadControl.FileBytes);

How to remove the left part of a string?

This is very similar in technique to other answers, but with no repeated string operations, ability to tell if the prefix was there or not, and still quite readable:

parts = the_string.split(prefix_to_remove, 1):
    if len(parts) == 2:
        #  do things with parts[1]
        pass

Is there any way to do HTTP PUT in python

This was made better in python3 and documented in the stdlib documentation

The urllib.request.Request class gained a method=... parameter in python3.

Some sample usage:

req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')
urllib.request.urlopen(req)

javascript: optional first argument in function

Or you also can differentiate by what type of content you got. Options used to be an object the content is used to be a string, so you could say:

if ( typeof content === "object" ) {
  options = content;
  content = null;
}

Or if you are confused with renaming, you can use the arguments array which can be more straightforward:

if ( arguments.length === 1 ) {
  options = arguments[0];
  content = null;
}

How to set null to a GUID property

Since "Guid" is not nullable, use "Guid.Empty" as default value.

Redirect from asp.net web api post action

Sure:

public HttpResponseMessage Post()
{
    // ... do the job

    // now redirect
    var response = Request.CreateResponse(HttpStatusCode.Moved);
    response.Headers.Location = new Uri("http://www.abcmvc.com");
    return response;
}

Move the most recent commit(s) to a new branch with Git

This doesn't "move" them in the technical sense but it has the same effect:

A--B--C  (branch-foo)
 \    ^-- I wanted them here!
  \
   D--E--F--G  (branch-bar)
      ^--^--^-- Opps wrong branch!

While on branch-bar:
$ git reset --hard D # remember the SHAs for E, F, G (or E and G for a range)

A--B--C  (branch-foo)
 \
  \
   D-(E--F--G) detached
   ^-- (branch-bar)

Switch to branch-foo
$ git cherry-pick E..G

A--B--C--E'--F'--G' (branch-foo)
 \   E--F--G detached (This can be ignored)
  \ /
   D--H--I (branch-bar)

Now you won't need to worry about the detached branch because it is basically
like they are in the trash can waiting for the day it gets garbage collected.
Eventually some time in the far future it will look like:

A--B--C--E'--F'--G'--L--M--N--... (branch-foo)
 \
  \
   D--H--I--J--K--.... (branch-bar)

How to use callback with useState hook in react

You can use useEffect/useLayoutEffect to achieve this:

const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

More about it over here.

If you are looking for an out of the box solution, check out this custom hook that works like useState but accepts as second parameter a callback function:

// npm install use-state-with-callback

import useStateWithCallback from 'use-state-with-callback';

const SomeOtherComponent = () => {
  const [count, setCount] = useStateWithCallback(0, count => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  });

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

I need to round a float to two decimal places in Java

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118);
// 1.30

How to get a complete list of ticker symbols from Yahoo Finance?

There is a nice C# wrapper for the Yahoo.Finance API at http://code.google.com/p/yahoo-finance-managed/ that will get you there. Unfortunately there is no direct way to download the ticker list but the following creates the list by iterating through the alphabetical groups:

        AlphabeticIDIndexDownload dl1 = new AlphabeticIDIndexDownload();
        dl1.Settings.TopIndex = null;
        Response<AlphabeticIDIndexResult> resp1 = dl1.Download();

        writeStream.WriteLine("Id|Isin|Name|Exchange|Type|Industry");

        foreach (var alphabeticalIndex in resp1.Result.Items)
        {
            AlphabeticalTopIndex topIndex = (AlphabeticalTopIndex) alphabeticalIndex;
            dl1.Settings.TopIndex = topIndex;
            Response<AlphabeticIDIndexResult> resp2 = dl1.Download();

            foreach (var index in resp2.Result.Items)
            {
                IDSearchDownload dl2 = new IDSearchDownload();
                Response<IDSearchResult> resp3 = dl2.Download(index);


                int i = 0;
                foreach (var item in resp3.Result.Items)
                {
                    writeStream.WriteLine(item.ID + "|" + item.ISIN + "|" + item.Name + "|" + item.Exchange + "|" + item.Type + "|" + item.Industry);
                }

            }
        }

It gave me a list of about 75,000 securities in about 4 mins.

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

7-Zip command to create and extract a password-protected ZIP file on Windows?

From http://www.dotnetperls.com:

7z a secure.7z * -pSECRET

Where:

7z        : name and path of 7-Zip executable
a         : add to archive
secure.7z : name of destination archive
*         : add all files from current directory to destination archive
-pSECRET  : specify the password "SECRET"

To open :

7z x secure.7z

Then provide the SECRET password

Note: If the password contains spaces or special characters, then enclose it with single quotes

7z a secure.7z * -p"pa$$word @|"

How can I de-install a Perl module installed via `cpan`?

There are scripts on CPAN which attempt to uninstall modules:

ExtUtils::Packlist shows sample module removing code, modrm.

Cancel split window in Vim

Press Control+w, then hit q to close each window at a time.

Update: Also consider eckes answer which may be more useful to you, involving :on (read below) if you don't want to do it one window at a time.

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

How do you display JavaScript datetime in 12 hour AM/PM format?

Here is another way that is simple, and very effective:

        var d = new Date();

        var weekday = new Array(7);
        weekday[0] = "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";

        var month = new Array(11);
        month[0] = "January";
        month[1] = "February";
        month[2] = "March";
        month[3] = "April";
        month[4] = "May";
        month[5] = "June";
        month[6] = "July";
        month[7] = "August";
        month[8] = "September";
        month[9] = "October";
        month[10] = "November";
        month[11] = "December";

        var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');

        document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());

    </script></div><!-- #time -->

Javascript Regexp dynamic generation from variables?

The RegExp constructor creates a regular expression object for matching text with a pattern.

    var pattern1 = ':\\(|:=\\(|:-\\(';
    var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
    var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
    str.match(regex);

Above code works perfectly for me...

Load HTML File Contents to Div [without the use of iframes]

Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

If you need IE<8 compatibility, do this first to bring those browsers up to speed:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.

How to use sed to replace only the first occurrence in a file?

A sed script that will only replace the first occurrence of "Apple" by "Banana"

Example

     Input:      Output:

     Apple       Banana
     Apple       Apple
     Orange      Orange
     Apple       Apple

This is the simple script: Editor's note: works with GNU sed only.

sed '0,/Apple/{s/Apple/Banana/}' input_filename

The first two parameters 0 and /Apple/ are the range specifier. The s/Apple/Banana/ is what is executed within that range. So in this case "within the range of the beginning (0) up to the first instance of Apple, replace Apple with Banana. Only the first Apple will be replaced.

Background: In traditional sed the range specifier is also "begin here" and "end here" (inclusive). However the lowest "begin" is the first line (line 1), and if the "end here" is a regex, then it is only attempted to match against on the next line after "begin", so the earliest possible end is line 2. So since range is inclusive, smallest possible range is "2 lines" and smallest starting range is both lines 1 and 2 (i.e. if there's an occurrence on line 1, occurrences on line 2 will also be changed, not desired in this case). GNU sed adds its own extension of allowing specifying start as the "pseudo" line 0 so that the end of the range can be line 1, allowing it a range of "only the first line" if the regex matches the first line.

Or a simplified version (an empty RE like // means to re-use the one specified before it, so this is equivalent):

sed '0,/Apple/{s//Banana/}' input_filename

And the curly braces are optional for the s command, so this is also equivalent:

sed '0,/Apple/s//Banana/' input_filename

All of these work on GNU sed only.

You can also install GNU sed on OS X using homebrew brew install gnu-sed.

Disable vertical scroll bar on div overflow: auto

You should use only

overflow-y:hidden; - Use this for hiding the Vertical scroll

overflow-x:auto; - Use this to show Horizontal scroll

Luke has mentioned as both hidden. so I have given this separately.

How do I exit a WPF application programmatically?

Try

App.Current.Shutdown();

For me

Application.Current.Shutdown(); 

didn't work.

Get all files that have been modified in git branch

Update Nov 2020:

To get the list of files modified (and committed!) in the current branch you can use the shortest console command using standard git:

git diff --name-only master...


  • If your local "master" branch is outdated (behind the remote), add a remote name (assuming its "origin") git diff --name-only origin/master...

  • If you want to include uncommitted changes as well, remove the ...:

    git diff --name-only master

  • If you use different main branch name (eg: "main"), substitute it:

    git diff --name-only origin/main...

  • If your want to output to stdout (so its copyable)

    git diff --name-only master... | cat


per really nice detailed explanation of different options https://blog.jpalardy.com/posts/git-how-to-find-modified-files-on-a-branch/