Programs & Examples On #Avx

Advanced Vector Extensions (AVX) is an extension to the x86 instruction set architecture for microprocessors from Intel and AMD.

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

What is this warning about?

Modern CPUs provide a lot of low-level instructions, besides the usual arithmetic and logic, known as extensions, e.g. SSE2, SSE4, AVX, etc. From the Wikipedia:

Advanced Vector Extensions (AVX) are extensions to the x86 instruction set architecture for microprocessors from Intel and AMD proposed by Intel in March 2008 and first supported by Intel with the Sandy Bridge processor shipping in Q1 2011 and later on by AMD with the Bulldozer processor shipping in Q3 2011. AVX provides new features, new instructions and a new coding scheme.

In particular, AVX introduces fused multiply-accumulate (FMA) operations, which speed up linear algebra computation, namely dot-product, matrix multiply, convolution, etc. Almost every machine-learning training involves a great deal of these operations, hence will be faster on a CPU that supports AVX and FMA (up to 300%). The warning states that your CPU does support AVX (hooray!).

I'd like to stress here: it's all about CPU only.

Why isn't it used then?

Because tensorflow default distribution is built without CPU extensions, such as SSE4.1, SSE4.2, AVX, AVX2, FMA, etc. The default builds (ones from pip install tensorflow) are intended to be compatible with as many CPUs as possible. Another argument is that even with these extensions CPU is a lot slower than a GPU, and it's expected for medium- and large-scale machine-learning training to be performed on a GPU.

What should you do?

If you have a GPU, you shouldn't care about AVX support, because most expensive ops will be dispatched on a GPU device (unless explicitly set not to). In this case, you can simply ignore this warning by

# Just disables the warning, doesn't take advantage of AVX/FMA to run faster
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

... or by setting export TF_CPP_MIN_LOG_LEVEL=2 if you're on Unix. Tensorflow is working fine anyway, but you won't see these annoying warnings.


If you don't have a GPU and want to utilize CPU as much as possible, you should build tensorflow from the source optimized for your CPU with AVX, AVX2, and FMA enabled if your CPU supports them. It's been discussed in this question and also this GitHub issue. Tensorflow uses an ad-hoc build system called bazel and building it is not that trivial, but is certainly doable. After this, not only will the warning disappear, tensorflow performance should also improve.

Class has no member named

Did you remember to include the closing brace in main?

#include <iostream>
#include "Attack.h"

using namespace std;

int main()
{
  Attack attackObj;
  attackObj.printShiz();
}

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Here is My Code

protected void btnExcel_Click(object sender, ImageClickEventArgs e)
    {
        if (gvDetail.Rows.Count > 0)
        {
            System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
            gvDetail.RenderControl(htmlWrite1);

            gvDetail.AllowPaging = false;
            Search();
            sh.ExportToExcel(gvDetail, "Report");
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

Google Chromecast sender error if Chromecast extension is not installed or using incognito

If you want to temporarily get rid of these console errors (like I did) you can install the extension here: https://chrome.google.com/webstore/detail/google-cast/boadgeojelhgndaghljhdicfkmllpafd/reviews?hl=en

I left a review asking for a fix. You can also do a bug report via the extension (after you install it) here. Instructions for doing so are here: https://support.google.com/chromecast/answer/3187017?hl=en

I hope Google gets on this. I need my console to show my errors, etc. Not theirs.

Export pictures from excel file into jpg using VBA

New versions of excel have made old answers obsolete. It took a long time to make this, but it does a pretty good job. Note that the maximum image size is limited and the aspect ratio is ever so slightly off, as I was not able to perfectly optimize the reshaping math. Note that I've named one of my worksheets wsTMP, you can replace it with Sheet1 or the like. Takes about 1 second to print the screenshot to target path.

Option Explicit

Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

Sub weGucciFam()

Dim tmp As Variant, str As String, h As Double, w As Double

Application.PrintCommunication = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
If Application.StatusBar = False Then Application.StatusBar = "EVENTS DISABLED"

keybd_event vbKeyMenu, 0, 0, 0 'these do just active window
keybd_event vbKeySnapshot, 0, 0, 0
keybd_event vbKeySnapshot, 0, 2, 0
keybd_event vbKeyMenu, 0, 2, 0 'sendkeys alt+printscreen doesn't work
wsTMP.Paste
DoEvents
Const dw As Double = 1186.56
Const dh As Double = 755.28

str = "C:\Users\YOURUSERNAMEHERE\Desktop\Screenshot.jpeg"
w = wsTMP.Shapes(1).Width
h = wsTMP.Shapes(1).Height

Application.DisplayAlerts = False
Set tmp = Charts.Add
On Error Resume Next
With tmp
    .PageSetup.PaperSize = xlPaper11x17
    .PageSetup.TopMargin = IIf(w > dw, dh - dw * h / w, dh - h) + 28
    .PageSetup.BottomMargin = 0
    .PageSetup.RightMargin = IIf(h > dh, dw - dh * w / h, dw - w) + 36
    .PageSetup.LeftMargin = 0
    .PageSetup.HeaderMargin = 0
    .PageSetup.FooterMargin = 0
    .SeriesCollection(1).Delete
    DoEvents
    .Paste
    DoEvents
    .Export Filename:=str, Filtername:="jpeg"
    .Delete
End With
On Error GoTo 0
Do Until wsTMP.Shapes.Count < 1
    wsTMP.Shapes(1).Delete
Loop

Application.PrintCommunication = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False

End Sub

How to get the current directory of the cmdlet being executed

Try :

(Get-Location).path

or:

($pwd).path

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

The "if" expression tests for truthiness, while the double-equal tests for type-independent equivalency. A string is always truthy, as others here have pointed out. If the double-equal were testing both of its operands for truthiness and then comparing the results, then you'd get the outcome you were intuitively assuming, i.e. ("0" == true) === true. As Doug Crockford says in his excellent JavaScript: the Good Parts, "the rules by which [== coerces the types of its operands] are complicated and unmemorable.... The lack of transitivity is alarming." It suffices to say that one of the operands is type-coerced to match the other, and that "0" ends up being interpreted as a numeric zero, which is in turn equivalent to false when coerced to boolean (or false is equivalent to zero when coerced to a number).

runOnUiThread in fragment

Use a Kotlin extension function

fun Fragment?.runOnUiThread(action: () -> Unit) {
    this ?: return
    if (!isAdded) return // Fragment not attached to an Activity
    activity?.runOnUiThread(action)
}

Then, in any Fragment you can just call runOnUiThread. This keeps calls consistent across activities and fragments.

runOnUiThread {
    // Call your code here
}

NOTE: If Fragment is no longer attached to an Activity, callback will not be called and no exception will be thrown

If you want to access this style from anywhere, you can add a common object and import the method:

object ThreadUtil {
    private val handler = Handler(Looper.getMainLooper())

    fun runOnUiThread(action: () -> Unit) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            handler.post(action)
        } else {
            action.invoke()
        }
    }
}

PHP: HTTP or HTTPS?

If your request is sent by HTTPS you will have an extra server variable named 'HTTPS'

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { //HTTPS } 

Why am I getting ImportError: No module named pip ' right after installing pip?

I'v solved this error by setting the correct path variables

    C:\Users\name\AppData\Local\Programs\Python\Python37\Scripts
    C:\Users\name\AppData\Local\Programs\Python\Python37\Lib\site-packages

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})

document.body.appendChild(i)

You could try

document.getElementsByTagName('body')[0].appendChild(i);

Now that won't do you any good if the code is running in the <head>, and running before the <body> has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script> block to the very end of the document instead of the <head>.

How to escape special characters in building a JSON string?

Most of these answers either does not answer the question or is unnecessarily long in the explanation.

OK so JSON only uses double quotation marks, we get that!

I was trying to use JQuery AJAX to post JSON data to server and then later return that same information. The best solution to the posted question I found was to use:

var d = {
    name: 'whatever',
    address: 'whatever',
    DOB: '01/01/2001'
}
$.ajax({
    type: "POST",
    url: 'some/url',
    dataType: 'json',
    data: JSON.stringify(d),
    ...
}

This will escape the characters for you.

This was also suggested by Mark Amery, Great answer BTW

Hope this helps someone.

What is the JUnit XML format specification that Hudson supports?

Good answers here on using python: (there are many ways to do it) Python unittests in Jenkins?

IMHO the best way is write python unittest tests and install pytest (something like 'yum install pytest') to get py.test installed. Then run tests like this: 'py.test --junitxml results.xml test.py'. You can run any unittest python script and get jUnit xml results.

https://docs.python.org/2.7/library/unittest.html

In jenkins build configuration Post-build actions Add a "Publish JUnit test result report" action with result.xml and any more test result files you produce.

AngularJS toggle class using ng-class

autoscroll will be defined and modified in the controller:

<span ng-class= "autoscroll?'class_if_true':'class_if_false'"></span>

Add multiple classes based on condition by:

<span ng-class= "autoscroll?'first second third':'classes_if_false'"></span>

How to save and load cookies using Python + Selenium WebDriver

Remember, you can only add a cookie for the current domain.

If you want to add a cookie for your Google account, do

browser.get('http://google.com')
for cookie in cookies:
    browser.add_cookie(cookie)

How to get the clicked link's href with jquery?

You're looking for $(this).attr("href");

How to enable local network users to access my WAMP sites?

In WAMPServer 3 you dont do this in httpd.conf

Instead edit \wamp\bin\apache\apache{version}\conf\extra\httpd-vhost.conf and do the same chnage to the Virtual Host defined for localhost

WAMPServer 3 comes with a Virtual Host pre defined for localhost

How to reset (clear) form through JavaScript?

Clear the form as follows

document.forms[0].reset();

You can simply clear the form elements within the group. by using this forms[0].

Meaning of 'const' last in a function declaration of a class?

The const qualifier means that the methods can be called on any value of foobar. The difference comes when you consider calling a non-const method on a const object. Consider if your foobar type had the following extra method declaration:

class foobar {
  ...
  const char* bar();
}

The method bar() is non-const and can only be accessed from non-const values.

void func1(const foobar& fb1, foobar& fb2) {
  const char* v1 = fb1.bar();  // won't compile
  const char* v2 = fb2.bar();  // works
}

The idea behind const though is to mark methods which will not alter the internal state of the class. This is a powerful concept but is not actually enforceable in C++. It's more of a promise than a guarantee. And one that is often broken and easily broken.

foobar& fbNonConst = const_cast<foobar&>(fb1);

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

How do I check if file exists in jQuery or pure JavaScript?

What you'd have to do is send a request to the server for it to do the check, and then send back the result to you.

What type of server are you trying to communicate with? You may need to write a small service to respond to the request.

Bash: If/Else statement in one line

There is no need to explicitly check $?. Just do:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0 

Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:

if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi

adding .css file to ejs

In order to serve up a static CSS file in express app (i.e. use a css style file to style ejs "templates" files in express app). Here are the simple 3 steps that need to happen:

  1. Place your css file called "styles.css" in a folder called "assets" and the assets folder in a folder called "public". Thus the relative path to the css file should be "/public/assets/styles.css"

  2. In the head of each of your ejs files you would simply call the css file (like you do in a regular html file) with a <link href=… /> as shown in the code below. Make sure you copy and paste the code below directly into your ejs file <head> section

    <link href= "/public/assets/styles.css" rel="stylesheet" type="text/css" />
    
  3. In your server.js file, you need to use the app.use() middleware. Note that a middleware is nothing but a term that refers to those operations or code that is run between the request and the response operations. By putting a method in middleware, that method will automatically be called everytime between the request and response methods. To serve up static files (such as a css file) in the app.use() middleware there is already a function/method provided by express called express.static(). Lastly, you also need to specify a request route that the program will respond to and serve up the files from the static folder everytime the middleware is called. Since you will be placing the css files in your public folder. In the server.js file, make sure you have the following code:

    // using app.use to serve up static CSS files in public/assets/ folder when /public link is called in ejs files
    // app.use("/route", express.static("foldername"));
    app.use('/public', express.static('public'));
    

After following these simple 3 steps, every time you res.render('ejsfile') in your app.get() methods you will automatically see the css styling being called. You can test by accessing your routes in the browser.

What is *.o file?

It is important to note that object files are assembled to binary code in a format that is relocatable. This is a form which allows the assembled code to be loaded anywhere into memory for use with other programs by a linker.

Instructions that refer to labels will not yet have an address assigned for these labels in the .o file.

These labels will be written as '0' and the assembler creates a relocation record for these unknown addresses. When the file is linked and output to an executable the unknown addresses are resolved and the program can be executed.

You can use the nm tool on an object file to list the symbols defined in a .o file.

What is SELF JOIN and when would you use it?

SQL self-join simply is a normal join which is used to join a table to itself.

Example:

Select *
FROM Table t1, Table t2
WHERE t1.Id = t2.ID

Oracle SQL update based on subquery between two tables

As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

Specific Time Range Query in SQL Server

select * from table where 
(dtColumn between #3/1/2009# and #3/31/2009#) and 
(hour(dtColumn) between 6 and 22) and 
(weekday(dtColumn, 1) between 2 and 4) 

What is a postback?

So far I've seen the right answer alluded to repeatedly, and almost everyone has come shy of what I consider subjectively to be the mark.

Let's start with the basics:

An HTTP request can be any of the HTTP verbs, but the two that people use most are GET and POST. Well, those are the two a programmer uses most frequently. The others all have some purpose, if they're implemented on the server. When you send information to the server, you can do so either through the use of the URL (to request a page) or within the body of the request (POST, PUT, DELETE, for instance).

Now you'll remark (I'm sure) that the URL in a GET request often contains data, and this is true, but according to W3C, you should not use GET to alter state, and yet we do often. It's sort of a hack that we all agree is an actual use, and not a hack. Whether that makes it a hack or an actual implementation detail I leave up to you.

So when you send the body of the POST (skipping the others for now, you can figure it out from here) with the form elements, you're sending back certain elements. How those elements are defined is up to you and to the environment you're working in. You could post to a server with a JSON element in the body, or with XML, or with form fields. Generally we do posts from a FORM element in the body of the HTML.

Now everyone says, "oh, a postback is a subsequent request to a page." But, that's not true. A postback is when you send data via POST -> back to the server. I say this because the difference between a GET request and a POST request is if data is included in the body (and the verb used, but the client usually knows how to deal with that). You could postback to the page on the first time the page is visited, and in fact ASP.NET has tools for doing that in the library. You could certainly have a desktop client POST data to a server (think Twitter) without showing any webpage at all from the server (ok, so twitter is probably not the best concept to use for an example here, but I want to illustrate that you can use a client that doesn't show the webpage, so no request is necessary).

So really what you should read there in "postback" is "I'm POSTing data BACK to the server for processing". It's presumed that you retrieved the page initially with a GET to show the user the <form> element that has <input> fields for them to interact with, and that at the end you're sending data back. But I hope you can see that it doesn't have to be in that order.

So here's something else to consider:

What if you gave the user a page with a bunch of <input>s and no <form> but instead, had a button wired up in javascript to concat all those <input>s with &value-n= and send them as a GET? Does the same thing, but violates that concept of only using GET for requests. (possibly) ensuing discussion encourages me to reinforce that GET should have no side effects (no updating values)

It's how come you can send someone a link to a google search, for instance. So we don't ALWAYS have to POST BACK to the server to get data.

Hope this helps. Cheers

Checking Value of Radio Button Group via JavaScript?

Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).

document.querySelector('input[name="gender"]:checked').value

Converting a generic list to a CSV string

Here is my extension method, it returns a string for simplicity but my implementation writes the file to a data lake.

It provides for any delimiter, adds quotes to string (in case they contain the delimiter) and deals will nulls and blanks.

    /// <summary>
    /// A class to hold extension methods for C# Lists 
    /// </summary>
    public static class ListExtensions
    {
        /// <summary>
        /// Convert a list of Type T to a CSV
        /// </summary>
        /// <typeparam name="T">The type of the object held in the list</typeparam>
        /// <param name="items">The list of items to process</param>
        /// <param name="delimiter">Specify the delimiter, default is ,</param>
        /// <returns></returns>
        public static string ToCsv<T>(this List<T> items, string delimiter = ",")
        {
            Type itemType = typeof(T);
            var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance).OrderBy(p => p.Name);

            var csv = new StringBuilder();

            // Write Headers
            csv.AppendLine(string.Join(delimiter, props.Select(p => p.Name)));

            // Write Rows
            foreach (var item in items)
            {
                // Write Fields
                csv.AppendLine(string.Join(delimiter, props.Select(p => GetCsvFieldasedOnValue(p, item))));
            }

            return csv.ToString();
        }

        /// <summary>
        /// Provide generic and specific handling of fields
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private static object GetCsvFieldasedOnValue<T>(PropertyInfo p, T item)
        {
            string value = "";

            try
            {
                value = p.GetValue(item, null)?.ToString();
                if (value == null) return "NULL";  // Deal with nulls
                if (value.Trim().Length == 0) return ""; // Deal with spaces and blanks

                // Guard strings with "s, they may contain the delimiter!
                if (p.PropertyType == typeof(string))
                {
                    value = string.Format("\"{0}\"", value);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return value;
        }
    }

Usage:

 // Tab Delimited (TSV)
 var csv = MyList.ToCsv<MyClass>("\t");

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Using DISTINCT inner join in SQL

SELECT DISTINCT C.valueC 
FROM C 
  LEFT JOIN B ON C.id = B.lookupC
  LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.


EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

PHP how to get the base domain/url?

2 lines to solve it

$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$myDomain = preg_replace('/^www\./', '', parse_url($actual_link, PHP_URL_HOST));

Change default icon

If your designated icon shows when you run the EXE but not when you run it from Visual Studio, then, for a WPF project add the following at the top of your XAML: Icon="Images\MyIcon.ico". Put this just where you have the Title, and xmlns definitions. (Assuming you have an Images folder in your project, and that you added MyIcon.ico there).

Change IPython/Jupyter notebook working directory

OS Windows 10 Python Anaconda 2018 ver

CHANGE WORKING DIRECTORY OF JUPYTER NOTEBOOK BY CONFIGURATION FILE:

  1. Open cmd prompt (or Anaconda Prompt), then type 'jupyter notebook --generate-config' and press enter

  2. This auto create a file 'jupyter_notebook_config' in the 'C:\Users\username.jupyter\' folder

  3. Look for the created file 'jupyter_notebook_config'and edit it.

  4. Find for #c.NotebookApp.notebook_dir = ''

  5. Put you're desired path inside double quote, it becomes ---> c.NotebookApp.notebook_dir = 'D:/my_folder/jupiter'

    • Note the forward slash (/) is used, and the comment (#) was remove.

Hence,

#c.NotebookApp.notebook_dir = '' 

Edit to becomes

c.NotebookApp.notebook_dir = 'D:/your/desired/path'
  1. Let's modify the path of the Jupyter Notebook shortcut icon 6.0 On start menu, right-click on the shortcut, open folder location. 6.1 Once inside the folder, recommended to create a copy of Jupyter shortcut, 6.2 right click on the new shortcut icon to open properties,

Finally,

6.3 on Target text box, remove %USERPROFILE% at the end of path, The very long path should end with jupyter-notebook-script.py

searcch my vid Jupyter Notebook - Change working folder path from default to desired path

SQL error "ORA-01722: invalid number"

The ORA-01722 error is pretty straightforward. According to Tom Kyte:

We've attempted to either explicity or implicity convert a character string to a number and it is failing.

However, where the problem is is often not apparent at first. This page helped me to troubleshoot, find, and fix my problem. Hint: look for places where you are explicitly or implicitly converting a string to a number. (I had NVL(number_field, 'string') in my code.)

jQuery remove all list items from an unordered list

   var ul = document.getElementById("yourElementId");

     while (ul.firstChild)
         ul.removeChild(ul.firstChild);

How to change the plot line color from blue to black?

If you get the object after creation (for instance after "seasonal_decompose"), you can always access and edit the properties of the plot; for instance, changing the color of the first subplot from blue to black:

plt.axes[0].get_lines()[0].set_color('black')

Can you get the number of lines of code from a GitHub repository?

You can use GitHub API to get the sloc like the following function

function getSloc(repo, tries) {

    //repo is the repo's path
    if (!repo) {
        return Promise.reject(new Error("No repo provided"));
    }

    //GitHub's API may return an empty object the first time it is accessed
    //We can try several times then stop
    if (tries === 0) {
        return Promise.reject(new Error("Too many tries"));
    }

    let url = "https://api.github.com/repos" + repo + "/stats/code_frequency";

    return fetch(url)
        .then(x => x.json())
        .then(x => x.reduce((total, changes) => total + changes[1] + changes[2], 0))
        .catch(err => getSloc(repo, tries - 1));
}

Personally I made an chrome extension which shows the number of SLOC on both github project list and project detail page. You can also set your personal access token to access private repositories and bypass the api rate limit.

You can download from here https://chrome.google.com/webstore/detail/github-sloc/fkjjjamhihnjmihibcmdnianbcbccpnn

Source code is available here https://github.com/martianyi/github-sloc

Regular expression for only characters a-z, A-Z

With POSIX Bracket Expressions (not supported by Javascript) it can be done this way:

/[:alpha:]+/

Any alpha character A to Z or a to z.

or

/^[[:alpha:]]+$/s

to match strictly with spaces.

When is std::weak_ptr useful?

shared_ptr : holds the real object.

weak_ptr : uses lock to connect to the real owner or returns a NULL shared_ptr otherwise.

weak ptr

Roughly speaking, weak_ptr role is similar to the role of housing agency. Without agents, to get a house on rent we may have to check random houses in the city. The agents make sure that we visit only those houses which are still accessible and available for rent.

How to use the CSV MIME-type?

You could try to force the browser to open a "Save As..." dialog by doing something like:

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";

Which should work across most major browsers.

What is a non-capturing group in regular expressions?

In complex regular expressions you may have the situation arise where you wish to use a large number of groups some of which are there for repetition matching and some of which are there to provide back references. By default the text matching each group is loaded into the backreference array. Where we have lots of groups and only need to be able to reference some of them from the backreference array we can override this default behaviour to tell the regular expression that certain groups are there only for repetition handling and do not need to be captured and stored in the backreference array.

How to un-commit last un-pushed git commit without losing the changes

PLease make sure to backup your changes before running these commmand in a separate folder

git checkout branch_name

Checkout on your branch

git merge --abort

Abort the merge

git status

Check status of the code after aborting the merge

git reset --hard origin/branch_name

these command will reset your changes and align your code with the branch_name (branch) code.

Sort Pandas Dataframe by Date

You can use pd.to_datetime() to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it.

>>> import pandas as pd
>>> df = pd.DataFrame( {'Symbol':['A','A','A'] ,
    'Date':['02/20/2015','01/15/2016','08/21/2015']})
>>> df
         Date Symbol
0  02/20/2015      A
1  01/15/2016      A
2  08/21/2015      A
>>> df['Date'] =pd.to_datetime(df.Date)
>>> df.sort('Date') # This now sorts in date order
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

For future search, you can change the sort statement:

>>> df.sort_values(by='Date') # This now sorts in date order
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

Add a new item to a dictionary in Python

It can be as simple as:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item. An example:

default_data.update({'item4': 4, 'item5': 5})

Please see the documentation about dictionaries as data structures and dictionaries as built-in types.

How to position a Bootstrap popover?

Sure you can. Fortunately there is a clean way to do that and it is in the Bootstrap popover / tooltip documentation as well.

let mySpecialTooltip = $('#mySpecialTooltip); 
mySpecialTooltip.tooltip({
 container: 'body',
 placement: 'bottom',
 html: true,
 template: '<div class="tooltip your-custom-class" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
}); 

in your css file:-

.your-custom-class {
 bottom: your value;
}

Make sure to add the template in bootstrap's tooltip documentation and add your custom class name and style it using css

And, that's it. You can find more about this on https://getbootstrap.com/docs/4.0/components/tooltips/

Better way to check if a Path is a File or a Directory?

I use the following, it also tests the extension which means it can be used for testing if the path supplied is a file but a file that doesn't exist.

private static bool isDirectory(string path)
{
    bool result = true;
    System.IO.FileInfo fileTest = new System.IO.FileInfo(path);
    if (fileTest.Exists == true)
    {
        result = false;
    }
    else
    {
        if (fileTest.Extension != "")
        {
            result = false;
        }
    }
    return result;
}

Why both no-cache and no-store should be used in HTTP response?

If you want to prevent all caching (e.g. force a reload when using the back button) you need:

  • no-cache for IE

  • no-store for Firefox

There's my information about this here:

http://blog.httpwatch.com/2008/10/15/two-important-differences-between-firefox-and-ie-caching/

html div onclick event

Try this

$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
    alert('123');
});

$('#ancherComplaint').click(function (event) {
    alert($(this).attr("id"));
    event.stopPropagation()
})

DEMO

Convert a Pandas DataFrame to a dictionary

df = pd.DataFrame([['p',1,3,2], ['q',4,3,2], ['r',4,0,9]], columns=['ID','A','B','C'])
my_dict = {k:list(v) for k,v in zip(df['ID'], df.drop(columns='ID').values)}
print(my_dict)

with output

{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

Changing the Git remote 'push to' default

Another technique I just found for solving this (even if I deleted origin first, what appears to be a mistake) is manipulating git config directly:

git config remote.origin.url url-to-my-other-remote

Disabling tab focus on form elements

Similar to Yipio, I added notab="notab" as an attribute to any element I wanted to disable the tab too. My jQuery is then one line.

$('input[notab=notab]').on('keydown', function(e){ if (e.keyCode == 9)  e.preventDefault() });

Btw, keypress doesn't work for many control keys.

PostgreSQL delete with inner join

Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.

WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id 
AND B.m_pricelist_version_id = '1000020';

HTTP POST using JSON in Java

For Java 11 you can use new HTTP client:

 HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost/api"))
        .header("Content-Type", "application/json")
        .POST(ofInputStream(() -> getClass().getResourceAsStream(
            "/some-data.json")))
        .build();

    client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println)
        .join();

You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.

How to create and add users to a group in Jenkins for authentication?

You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.

Update a dataframe in pandas while iterating row by row

You can assign values in the loop using df.set_value:

for i, row in df.iterrows():
    ifor_val = something
    if <condition>:
        ifor_val = something_else
    df.set_value(i,'ifor',ifor_val)

If you don't need the row values you could simply iterate over the indices of df, but I kept the original for-loop in case you need the row value for something not shown here.

update

df.set_value() has been deprecated since version 0.21.0 you can use df.at() instead:

for i, row in df.iterrows():
    ifor_val = something
    if <condition>:
        ifor_val = something_else
    df.at[i,'ifor'] = ifor_val

Convert hex string (char []) to int?

Or if you want to have your own implementation, I wrote this quick function as an example:

/**
 * hex2int
 * take a hex string and convert it to a 32bit number (max 8 hex digits)
 */
uint32_t hex2int(char *hex) {
    uint32_t val = 0;
    while (*hex) {
        // get current character then increment
        uint8_t byte = *hex++; 
        // transform hex character to the 4bit equivalent number, using the ascii table indexes
        if (byte >= '0' && byte <= '9') byte = byte - '0';
        else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
        else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;    
        // shift 4 to make space for new digit, and add the 4 bits of the new digit 
        val = (val << 4) | (byte & 0xF);
    }
    return val;
}

Limiting the number of characters per line with CSS

Another approach to this would put a span element with a display:block style inside the p element each time you need the content to break. It would only be useful when your p content is static.

<p>this is a not-dynamic text and I want to put<span style="display:block">the following words in the next line</span>and these other words in a third one</p>

It would output:

This is a not-dynamic text and I want to put

the following words in the next line

and these others in a third one

This allows you to change your text line-breaks in different viewports without JS.

Can we update primary key values of a table?

Short answer: yes you can. Of course you'll have to make sure that the new value doesn't match any existing value and other constraints are satisfied (duh).

What exactly are you trying to do?

Validation of radio button group using jQuery validation plugin

With newer releases of jquery (1.3+ I think), all you have to do is set one of the members of the radio set to be required and jquery will take care of the rest:

<input type="radio" name="myoptions" value="blue" class="required"> Blue<br />
<input type="radio" name="myoptions" value="red"> Red<br />
<input type="radio" name="myoptions" value="green"> Green

The above would require at least 1 of the 3 radio options w/ the name of "my options" to be selected before proceeding.

The label suggestion by Mahes, btw, works wonderfully!

Spring Data JPA find by embedded object property

This method name should do the trick:

Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);

More info on that in the section about query derivation of the reference docs.

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

This had occurred to me and I have found out that it was because of faulty internet connection. If I use the public wifi at my place, which blocks various websites for security reasons, Mongo refuses to connect. But if I were to use my own mobile data, I can connect to the database.

Dictionary text file

There's also WordNet. Its data files format are well-documented.
I used it for building an embeddable dictionary library for iOS developers (www.lexicontext.com) and also in one of my apps.

Make one div visible and another invisible

Making it invisible with visibility still makes it use up space. Rather try set the display to none to make it invisible, and then set the display to block to make it visible.

DD/MM/YYYY Date format in Moment.js

This actually worked for me:

moment(mydate).format('L');

Get operating system info

If you want very few info like a class in your html for common browsers for instance, you could use:

function get_browser()
{
    $browser = '';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
    elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];

    return $browser;
}

which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

Page scroll when soft keyboard popped up

Ok, I have searched several hours now to find the problem, and I found it.

None of the changes like fillViewport="true" or android:windowSoftInputMode="adjustResize" helped me.

I use Android 4.4 and this is the big mistake:

android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

Somehow, the Fullscreen themes prevent the ScrollViews from scrolling when the SoftKeyboard is visible.

At the moment, I ended up using this instead:

android:theme="@android:style/Theme.Black.NoTitleBar

I don't know how to get rid of the top system bar with time and battery display, but at least I got the problem.

Hope this helps others who have the same problem.

EDIT: I got a little workaround for my case, so I posted it here:

I am not sure if this will work for you, but it will definitely help you in understanding, and clear some things up.

EDIT2: Here is another good topic that will help you to go in the right direction or even solve your problem.

Centering text in a table in Twitter Bootstrap

In Bootstrap 3 (3.0.3) adding the "text-center" class to a td element works out of the box.

I.e., the following centers some text in a table cell:

<td class="text-center">some text</td>

Mapping composite keys using EF code first

Through Configuration, you can do this:

Model1
{
    int fk_one,
    int fk_two
}

Model2
{
    int pk_one,
    int pk_two,
}

then in the context config

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Model1>()
            .HasRequired(e => e.Model2)
            .WithMany(e => e.Model1s)
            .HasForeignKey(e => new { e.fk_one, e.fk_two })
            .WillCascadeOnDelete(false);
    }
}

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

Simple way to transpose columns and rows in SQL?

There are several ways that you can transform this data. In your original post, you stated that PIVOT seems too complex for this scenario, but it can be applied very easily using both the UNPIVOT and PIVOT functions in SQL Server.

However, if you do not have access to those functions this can be replicated using UNION ALL to UNPIVOT and then an aggregate function with a CASE statement to PIVOT:

Create Table:

CREATE TABLE yourTable([color] varchar(5), [Paul] int, [John] int, [Tim] int, [Eric] int);

INSERT INTO yourTable
    ([color], [Paul], [John], [Tim], [Eric])
VALUES
    ('Red', 1, 5, 1, 3),
    ('Green', 8, 4, 3, 5),
    ('Blue', 2, 2, 9, 1);

Union All, Aggregate and CASE Version:

select name,
  sum(case when color = 'Red' then value else 0 end) Red,
  sum(case when color = 'Green' then value else 0 end) Green,
  sum(case when color = 'Blue' then value else 0 end) Blue
from
(
  select color, Paul value, 'Paul' name
  from yourTable
  union all
  select color, John value, 'John' name
  from yourTable
  union all
  select color, Tim value, 'Tim' name
  from yourTable
  union all
  select color, Eric value, 'Eric' name
  from yourTable
) src
group by name

See SQL Fiddle with Demo

The UNION ALL performs the UNPIVOT of the data by transforming the columns Paul, John, Tim, Eric into separate rows. Then you apply the aggregate function sum() with the case statement to get the new columns for each color.

Unpivot and Pivot Static Version:

Both the UNPIVOT and PIVOT functions in SQL server make this transformation much easier. If you know all of the values that you want to transform, you can hard-code them into a static version to get the result:

select name, [Red], [Green], [Blue]
from
(
  select color, name, value
  from yourtable
  unpivot
  (
    value for name in (Paul, John, Tim, Eric)
  ) unpiv
) src
pivot
(
  sum(value)
  for color in ([Red], [Green], [Blue])
) piv

See SQL Fiddle with Demo

The inner query with the UNPIVOT performs the same function as the UNION ALL. It takes the list of columns and turns it into rows, the PIVOT then performs the final transformation into columns.

Dynamic Pivot Version:

If you have an unknown number of columns (Paul, John, Tim, Eric in your example) and then an unknown number of colors to transform you can use dynamic sql to generate the list to UNPIVOT and then PIVOT:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),
    @colsPivot as  NVARCHAR(MAX)

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('yourtable') and
               C.name <> 'color'
         for xml path('')), 1, 1, '')

select @colsPivot = STUFF((SELECT  ',' 
                      + quotename(color)
                    from yourtable t
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query 
  = 'select name, '+@colsPivot+'
      from
      (
        select color, name, value
        from yourtable
        unpivot
        (
          value for name in ('+@colsUnpivot+')
        ) unpiv
      ) src
      pivot
      (
        sum(value)
        for color in ('+@colsPivot+')
      ) piv'

exec(@query)

See SQL Fiddle with Demo

The dynamic version queries both yourtable and then the sys.columns table to generate the list of items to UNPIVOT and PIVOT. This is then added to a query string to be executed. The plus of the dynamic version is if you have a changing list of colors and/or names this will generate the list at run-time.

All three queries will produce the same result:

| NAME | RED | GREEN | BLUE |
-----------------------------
| Eric |   3 |     5 |    1 |
| John |   5 |     4 |    2 |
| Paul |   1 |     8 |    2 |
|  Tim |   1 |     3 |    9 |

How to update/refresh specific item in RecyclerView

I got to solve this issue by catching the position of the item that needed to be modified and then in the adapter call

public void refreshBlockOverlay(int position) {
    notifyItemChanged(position);
}

, this will call onBindViewHolder(ViewHolder holder, int position) for this specific item at this specific position.

How to position the div popup dialog to the center of browser screen?

Its a classical problem, when you scroll the modal popup generated on the screen stays at it place and does not scroll along, so the user might be blocked as he might not see the popup on his viewable screen.

The following link also provides CSS only code for generating a modal box along with its absolute position.

http://settledcuriosity.wordpress.com/2014/10/03/centering-a-popup-box-absolutely-at-the-center-of-screen/

How to place Text and an Image next to each other in HTML?

You want to use css float for this, you can put it directly in your code.

<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).

HTML:

<body>
  <img src="website_art.png" class="myImage"/>
  <h3 class="heading">The Art of Gaming</h3>
</body>

CSS:

.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

Is it good practice to make the constructor throw an exception?

As mentioned in another answer here, in Guideline 7-3 of the Java Secure Coding Guidelines, throwing an exception in the constructor of a non-final class opens a potential attack vector:

Guideline 7-3 / OBJECT-3: Defend against partially initialized instances of non-final classes When a constructor in a non-final class throws an exception, attackers can attempt to gain access to partially initialized instances of that class. Ensure that a non-final class remains totally unusable until its constructor completes successfully.

From JDK 6 on, construction of a subclassable class can be prevented by throwing an exception before the Object constructor completes. To do this, perform the checks in an expression that is evaluated in a call to this() or super().

    // non-final java.lang.ClassLoader
    public abstract class ClassLoader {
        protected ClassLoader() {
            this(securityManagerCheck());
        }
        private ClassLoader(Void ignored) {
            // ... continue initialization ...
        }
        private static Void securityManagerCheck() {
            SecurityManager security = System.getSecurityManager();
            if (security != null) {
                security.checkCreateClassLoader();
            }
            return null;
        }
    }

For compatibility with older releases, a potential solution involves the use of an initialized flag. Set the flag as the last operation in a constructor before returning successfully. All methods providing a gateway to sensitive operations must first consult the flag before proceeding:

    public abstract class ClassLoader {

        private volatile boolean initialized;

        protected ClassLoader() {
            // permission needed to create ClassLoader
            securityManagerCheck();
            init();

            // Last action of constructor.
            this.initialized = true;
        }
        protected final Class defineClass(...) {
            checkInitialized();

            // regular logic follows
            ...
        }

        private void checkInitialized() {
            if (!initialized) {
                throw new SecurityException(
                    "NonFinal not initialized"
                );
            }
        }
    }

Furthermore, any security-sensitive uses of such classes should check the state of the initialization flag. In the case of ClassLoader construction, it should check that its parent class loader is initialized.

Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it, thereby circumventing the SecurityManager check. While the initialized flag does not prevent access to the partially initialized object, it does prevent methods on that object from doing anything useful for the attacker.

Use of an initialized flag, while secure, can be cumbersome. Simply ensuring that all fields in a public non-final class contain a safe value (such as null) until object initialization completes successfully can represent a reasonable alternative in classes that are not security-sensitive.

A more robust, but also more verbose, approach is to use a "pointer to implementation" (or "pimpl"). The core of the class is moved into a non-public class with the interface class forwarding method calls. Any attempts to use the class before it is fully initialized will result in a NullPointerException. This approach is also good for dealing with clone and deserialization attacks.

    public abstract class ClassLoader {

        private final ClassLoaderImpl impl;

        protected ClassLoader() {
            this.impl = new ClassLoaderImpl();
        }
        protected final Class defineClass(...) {
            return impl.defineClass(...);
        }
    }

    /* pp */ class ClassLoaderImpl {
        /* pp */ ClassLoaderImpl() {
            // permission needed to create ClassLoader
            securityManagerCheck();
            init();
        }

        /* pp */ Class defineClass(...) {
            // regular logic follows
            ...
        }
    }

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

I solve this by SQL command:

ALTER USER 'mysqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlUsernamePassword';

which is referenced by https://dev.mysql.com/doc/refman/8.0/en/alter-user.html

if you are creating new user

 CREATE USER 'jeffrey'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

which is referenced by https://dev.mysql.com/doc/refman/8.0/en/create-user.html

this works for me

How to scan a folder in Java?

import java.io.File;
public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );
        }
    }
}

It displays indistinctly files and folders.

See the methods in File class to order them or avoid directory print etc.

http://java.sun.com/javase/6/docs/api/java/io/File.html

Why do we check up to the square root of a prime number to determine if it is prime?

Given any number n, then one way to find its factors is to get its square root p:

sqrt(n) = p

Of course, if we multiply p by itself, then we get back n:

p*p = n

It can be re-written as:

a*b = n

Where p = a = b. If a increases, then b decreases to maintain a*b = n. Therefore, p is the upper limit.

Update: I am re-reading this answer again today and it became clearer to me more. The value p does not necessarily mean an integer because if it is, then n would not be a prime. So, p could be a real number (ie, with fractions). And instead of going through the whole range of n, now we only need to go through the whole range of p. The other p is a mirror copy so in effect we halve the range. And then, now I am seeing that we can actually continue re-doing the square root and doing it to p to further half the range.

How to install SQL Server 2005 Express in Windows 8

Microsoft SQL Server 2005 Express Edition Service Pack 4 on Windows Server 2012 R2

Those steps are based on previous howto from https://stackoverflow.com/users/2385/eduardo-molteni

  1. download SQLEXPR.EXE
  2. run SQLEXPR.EXE
  3. copy c:\generated_installation_dir to inst.bak
  4. quit install
  5. run inst.bak/setuip/sqlncli_x64.msi
  6. run SQLEXPR.EXE
  7. enjoy!

This works with Microsoft SQL Server 2005 Express Edition Service Pack 4 http://www.microsoft.com/en-us/download/details.aspx?id=184

Default Xmxsize in Java 8 (max heap size)

On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize printed : uintx MaxHeapSize := 266338304, which is approx 266MB and is 1/4th of my total RAM.

How do I ignore a directory with SVN?

Jason's answer will do the trick. However, instead of setting svn:ignore to "." on the cache directory, you may want to include "cache" in the parent directory's svn:ignore property, in case the cache directory is not always present. I do this on a number of "throwaway" folders.

SpringMVC RequestMapping for GET parameters

If you are willing to change your uri, you could also use PathVariable.

@RequestMapping(value="/mapping/foo/{foo}/{bar}", method=RequestMethod.GET)
public String process(@PathVariable String foo,@PathVariable String bar) {
    //Perform logic with foo and bar
}

NB: The first foo is part of the path, the second one is the PathVariable

Sql connection-string for localhost server

string str = @"Data Source=HARIHARAN-PC\SQLEXPRESS;Initial Catalog=master;Integrated Security=True" ;

How to set image on QPushButton?

Just use this code

QPixmap pixmap("path_to_icon");
QIcon iconBack(pixmap);

Note that:"path_to_icon" is the path of image icon in file .qrc of your project You can find how to add .qrc file here

Pandas groupby month and year

You can also do it by creating a string column with the year and month as follows:

df['date'] = df.index
df['year-month'] = df['date'].apply(lambda x: str(x.year) + ' ' + str(x.month))
grouped = df.groupby('year-month')

However this doesn't preserve the order when you loop over the groups, e.g.

for name, group in grouped:
    print(name)

Will give:

2007 11
2007 12
2008 1
2008 10
2008 11
2008 12
2008 2
2008 3
2008 4
2008 5
2008 6
2008 7
2008 8
2008 9
2009 1
2009 10

So then, if you want to preserve the order, you must do as suggested by @Q-man above:

grouped = df.groupby([df.index.year, df.index.month])

This will preserve the order in the above loop:

(2007, 11)
(2007, 12)
(2008, 1)
(2008, 2)
(2008, 3)
(2008, 4)
(2008, 5)
(2008, 6)
(2008, 7)
(2008, 8)
(2008, 9)
(2008, 10)

How to kill an application with all its activities?

My understanding of the Android application framework is that this is specifically not permitted. An application is closed automatically when it contains no more current activities. Trying to create a "kill" button is apparently contrary to the intended design of the application system.

To get the sort of effect you want, you could initiate your various activities with startActivityForResult(), and have the exit button send back a result which tells the parent activity to finish(). That activity could then send the same result as part of its onDestroy(), which would cascade back to the main activity and result in no running activities, which should cause the app to close.

Using Node.js require vs. ES6 import/export

I personally use import because, we can import the required methods, members by using import.

import {foo, bar} from "dep";

FileName: dep.js

export foo function(){};
export const bar = 22

Credit goes to Paul Shan. More info.

Call of overloaded function is ambiguous

replace p.setval(0); with the following.

const unsigned int param = 0;
p.setval(param);

That way it knows for sure which type the constant 0 is.

Upload files with HTTPWebrequest (multipart/form-data)

I can never get the examples to work properly, I always receive a 500 error when sending it to the server.

However I came across a very elegant method of doing it in this url

It is easily extendible and obviously works with binary files as well as XML.

You call it using something similar to this

class Program
{
    public static string gsaFeedURL = "http://yourGSA.domain.com:19900/xmlfeed";

    static void Main()
    {
        try
        {
            postWebData();
        }
        catch (Exception ex)
        {
        }
    }

    // new one I made from C# web service
    public static void postWebData()
    {
        StringDictionary dictionary = new StringDictionary();
        UploadSpec uploadSpecs = new UploadSpec();
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] bytes;
        Uri gsaURI = new Uri(gsaFeedURL);  // Create new URI to GSA feeder gate
        string sourceURL = @"C:\FeedFile.xml"; // Location of the XML feed file
        // Two parameters to send
        string feedtype = "full";
        string datasource = "test";            

        try
        {
            // Add the parameter values to the dictionary
            dictionary.Add("feedtype", feedtype);
            dictionary.Add("datasource", datasource);

            // Load the feed file created and get its bytes
            XmlDocument xml = new XmlDocument();
            xml.Load(sourceURL);
            bytes = Encoding.UTF8.GetBytes(xml.OuterXml);

            // Add data to upload specs
            uploadSpecs.Contents = bytes;
            uploadSpecs.FileName = sourceURL;
            uploadSpecs.FieldName = "data";

            // Post the data
            if ((int)HttpUpload.Upload(gsaURI, dictionary, uploadSpecs).StatusCode == 200)
            {
                Console.WriteLine("Successful.");
            }
            else
            {
                // GSA POST not successful
                Console.WriteLine("Failure.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Invalid attempt to read when no data is present

I just had this error, I was calling dr.NextResult() instead of dr.Read().

Equal sized table cells to fill the entire width of the containing table

You don't even have to set a specific width for the cells, table-layout: fixed suffices to spread the cells evenly.

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid hotpink;_x000D_
    vertical-align: middle;_x000D_
    word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that for table-layout to work the table styled element must have a width set (100% in my example).

How can I pop-up a print dialog box using Javascript?

if problem:

 mywindow.print();

altenative using:

'<scr'+'ipt>print()</scr'+'ipt>'

Full:

 $('.print-ticket').click(function(){

        var body = $('body').html();
        var ticket_area = '<aside class="widget tickets">' + $('.widget.tickets').html() + '</aside>';

        $('body').html(ticket_area);
        var print_html = '<html lang="tr">' + $('html').html() + '<scr'+'ipt>print()</scr'+'ipt>' + '</html>'; 
        $('body').html(body);

        var mywindow = window.open('', 'my div', 'height=600,width=800');
        mywindow.document.write(print_html);
        mywindow.document.close(); // necessary for IE >= 10'</html>'
        mywindow.focus(); // necessary for IE >= 10
        //mywindow.print();
        mywindow.close();

        return true;
    });

Jquery: Find Text and replace

Try This

$("#id1 p:contains('dogsss')").replaceWith("dollsss");

Rails 4 - Strong Parameters - Nested Objects

I found this suggestion useful in my case:

  def product_params
    params.require(:product).permit(:name).tap do |whitelisted|
      whitelisted[:data] = params[:product][:data]
    end
  end

Check this link of Xavier's comment on github.

This approach whitelists the entire params[:measurement][:groundtruth] object.

Using the original questions attributes:

  def product_params
    params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
      whitelisted[:groundtruth] = params[:measurement][:groundtruth]
    end
  end

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

There are several valid and helpful responses here, but I would like to add that in my case the simplest solution was:

  1. Delete package-lock.json;
  2. Remove folder AppData\Local\npm\cache or AppData\Roaming\npm\cache;
  3. Remove folder node_modules.staging;
  4. Run npm install again.

After that everything ran smoothly.

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.

VBA: Convert Text to Number

Using aLearningLady's answer above, you can make your selection range dynamic by looking for the last row with data in it instead of just selecting the entire column.

The below code worked for me.

Dim lastrow as Integer

lastrow = Cells(Rows.Count, 2).End(xlUp).Row

Range("C2:C" & lastrow).Select
With Selection
    .NumberFormat = "General"
    .Value = .Value
End With

Cannot access a disposed object - How to fix?

It looks like a threading issue.
Hypothesis: Maybe you have the main thread and a timer thread accessing this control. The main thread shuts down - calling Control.Dispose() to indicate that I'm done with this Control and I shall make no more calls to this. However, the timer thread is still active - a context switch to that thread, where it may call methods on the same control. Now the control says I'm Disposed (already given up my resources) and I shall not work anymore. ObjectDisposed exception.

How to solve this: In the timer thread, before calling methods/properties on the control, do a check with

if ControlObject.IsDisposed then return; // or do whatever - but don't call control methods

OR stop the timer thread BEFORE disposing the object.

Detect iPad users using jQuery?

I use this:

//http://detectmobilebrowsers.com/ + tablets
(function(a) {
    if(/android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(ad|hone|od)|iris|kindle|lge |maemo|meego.+mobile|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|playbook|silk/i.test(a)
    ||
    /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))
    {
        window.location="yourNewIndex.html"
    }
})(navigator.userAgent||navigator.vendor||window.opera);

How can I configure my makefile for debug and release builds?

Completing the answers from earlier... You need to reference the variables you define info in your commands...

DEBUG ?= 1
ifeq (DEBUG, 1)
    CFLAGS =-g3 -gdwarf2 -DDEBUG
else
    CFLAGS=-DNDEBUG
endif

CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)

all: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

CommandParser.tab.o: CommandParser.y
    bison -d CommandParser.y
    $(CXX) -c CommandParser.tab.c

Command.o: Command.cpp
    $(CXX) -c Command.cpp

clean:
    rm -f CommandParser.tab.* CommandParser.yy.* output *.o

How to add a "open git-bash here..." context menu to the windows explorer?

Step 1. On your desktop right click "New"->"Text Document" with name OpenGitBash.reg

Step 2. Right click the file and choose "Edit"

Step 3. Copy-paste the code below, save and close the file

Step 4. Execute the file by double clicking it

Note: You need administrator permission to write to the registry.

Windows Registry Editor Version 5.00
; Open files
; Default Git-Bash Location C:\Program Files\Git\git-bash.exe

[HKEY_CLASSES_ROOT\*\shell\Open Git Bash]
@="Open Git Bash"
"Icon"="C:\\Program Files\\Git\\git-bash.exe"

[HKEY_CLASSES_ROOT\*\shell\Open Git Bash\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%1\""

; This will make it appear when you right click ON a folder
; The "Icon" line can be removed if you don't want the icon to appear

[HKEY_CLASSES_ROOT\Directory\shell\bash]
@="Open Git Bash"
"Icon"="C:\\Program Files\\Git\\git-bash.exe"


[HKEY_CLASSES_ROOT\Directory\shell\bash\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%1\""

; This will make it appear when you right click INSIDE a folder
; The "Icon" line can be removed if you don't want the icon to appear

[HKEY_CLASSES_ROOT\Directory\Background\shell\bash]
@="Open Git Bash"
"Icon"="C:\\Program Files\\Git\\git-bash.exe"

[HKEY_CLASSES_ROOT\Directory\Background\shell\bash\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%v.\""

And here is your result :

enter image description here

what's the correct way to send a file from REST web service to client?

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

Disable submit button on form submit

How to disable submit button

just call a function on onclick event and... return true to submit and false to disable submit. OR call a function on window.onload like :

window.onload = init();

and in init() do something like this :

var theForm = document.getElementById(‘theForm’);
theForm.onsubmit =  // what ever you want to do 

jQuery count child elements

pure js

selected.children[0].children.length;

_x000D_
_x000D_
let num = selected.children[0].children.length;_x000D_
_x000D_
console.log(num);
_x000D_
<div id="selected">_x000D_
  <ul>_x000D_
    <li>29</li>_x000D_
    <li>16</li>_x000D_
    <li>5</li>_x000D_
    <li>8</li>_x000D_
    <li>10</li>_x000D_
    <li>7</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

What does MVW stand for?

It stands indeed for whatever, as in whatever works for you

MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.

For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.

Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.

Checking for empty or null JToken in a JObject

As of C# 7 you could also use this:

if (clientsParsed["objects"] is JArray clients) 
{
    foreach (JObject item in clients.Children())
    {
        if (item["thisParameter"] as JToken itemToken) 
        {
            command.Parameters["@MyParameter"].Value = JTokenToSql(itemToken);
        }
    }
}

The is Operator checks the Type and if its corrects the Value is inside the clients variable.

Flutter: Setting the height of the AppBar

At the time of writing this, I was not aware of PreferredSize. Cinn's answer is better to achieve this.

You can create your own custom widget with a custom height:

import "package:flutter/material.dart";

class Page extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Column(children : <Widget>[new CustomAppBar("Custom App Bar"), new Container()],);
  }
}


class CustomAppBar extends StatelessWidget {

  final String title;
  final double barHeight = 50.0; // change this for different heights 

  CustomAppBar(this.title);

  @override
  Widget build(BuildContext context) {
    final double statusbarHeight = MediaQuery
        .of(context)
        .padding
        .top;

    return new Container(
      padding: new EdgeInsets.only(top: statusbarHeight),
      height: statusbarHeight + barHeight,
      child: new Center(
        child: new Text(
          title,
          style: new TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}

Why do we need middleware for async flow in Redux?

To Answer the question:

Why can't the container component call the async API, and then dispatch the actions?

I would say for at least two reasons:

The first reason is the separation of concerns, it's not the job of the action creator to call the api and get data back, you have to have to pass two argument to your action creator function, the action type and a payload.

The second reason is because the redux store is waiting for a plain object with mandatory action type and optionally a payload (but here you have to pass the payload too).

The action creator should be a plain object like below:

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

And the job of Redux-Thunk midleware to dispache the result of your api call to the appropriate action.

How to access site running apache server over lan without internet connection

  1. navigate to C:\wamp\alias.
  2. make file with project name and like phpmyadmin.conf
  3. add the following section and change :

    Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all

change directory to your directory path like c:\wamp\www\projectfolder

  1. make sure you make the same in httpd.conf for all directory like first directory:

    Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all

second directory:

<Directory "c:/wamp/www/">

#
# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.0/mod/core.html#options
# for more information.
#
    Options Indexes FollowSymLinks

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride all

#
# Controls who can get stuff from this server.
#

#   onlineoffline tag - don't remove
    Order Deny,Allow
    Allow from all

</Directory>

<Directory "icons">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

If all the solutions above don't work, try to :

Add $i = 1; after /* Servers configuration */

in place of $i = 0 in your phpmyadmin config.inc.php file

Running XAMPP on local windows server, my mysql data files are not under the usual install path (C:\Xampp), but on another disk.

So now I have the phpmyadmin tables with the double __ like pma__table... and $i = 1;

How to import other Python files?

You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type

from root.parent.folder.file import variable, class, whatever

How to get N rows starting from row M from sorted table in T-SQL

There is a pretty straight-forward method for T-SQL, although I'm not sure if it is prestanda-effective if you're skipping a large number of rows.

SELECT TOP numberYouWantToTake 
    [yourColumns...] 
FROM yourTable 
WHERE yourIDColumn NOT IN (
    SELECT TOP numberYouWantToSkip 
        yourIDColumn 
    FROM yourTable 
    ORDER BY yourOrderColumn
)
ORDER BY yourOrderColumn

If you're using .Net, you can use the following on for example an IEnumerable with your data results:

IEnumerable<yourDataType> yourSelectedData = yourDataInAnIEnumerable.Skip(nubmerYouWantToSkip).Take(numberYouWantToTake);

This has the backside that you're getting all the data from the data storage.

IEnumerable vs List - What to Use? How do they work?

In addition to all the answers posted above, here is my two cents. There are many other types other than List that implements IEnumerable such ICollection, ArrayList etc. So if we have IEnumerable as parameter of any method, we can pass any collection types to the function. Ie we can have method to operate on abstraction not any specific implementation.

Objective-C: Calling selectors with multiple arguments

@Shane Arney

performSelector:withObject:withObject:

You might also want to mention that this method is only for passing maximum 2 arguments, and it cannot be delayed. (such as performSelector:withObject:afterDelay:).

kinda weird that apple only supports 2 objects to be send and didnt make it more generic.

Serialize and Deserialize Json and Json Array in Unity

Unity added JsonUtility to their API after 5.3.3 Update. Forget about all the 3rd party libraries unless you are doing something more complicated. JsonUtility is faster than other Json libraries. Update to Unity 5.3.3 version or above then try the solution below.

JsonUtility is a lightweight API. Only simple types are supported. It does not support collections such as Dictionary. One exception is List. It supports List and List array!

If you need to serialize a Dictionary or do something other than simply serializing and deserializing simple datatypes, use a third-party API. Otherwise, continue reading.

Example class to serialize:

[Serializable]
public class Player
{
    public string playerId;
    public string playerLoc;
    public string playerNick;
}

1. ONE DATA OBJECT (NON-ARRAY JSON)

Serializing Part A:

Serialize to Json with the public static string ToJson(object obj); method.

Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";

//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance);
Debug.Log(playerToJson);

Output:

{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}

Serializing Part B:

Serialize to Json with the public static string ToJson(object obj, bool prettyPrint); method overload. Simply passing true to the JsonUtility.ToJson function will format the data. Compare the output below to the output above.

Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";

//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance, true);
Debug.Log(playerToJson);

Output:

{
    "playerId": "8484239823",
    "playerLoc": "Powai",
    "playerNick": "Random Nick"
}

Deserializing Part A:

Deserialize json with the public static T FromJson(string json); method overload.

string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = JsonUtility.FromJson<Player>(jsonString);
Debug.Log(player.playerLoc);

Deserializing Part B:

Deserialize json with the public static object FromJson(string json, Type type); method overload.

string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = (Player)JsonUtility.FromJson(jsonString, typeof(Player));
Debug.Log(player.playerLoc);

Deserializing Part C:

Deserialize json with the public static void FromJsonOverwrite(string json, object objectToOverwrite); method. When JsonUtility.FromJsonOverwrite is used, no new instance of that Object you are deserializing to will be created. It will simply re-use the instance you pass in and overwrite its values.

This is efficient and should be used if possible.

Player playerInstance;
void Start()
{
    //Must create instance once
    playerInstance = new Player();
    deserialize();
}

void deserialize()
{
    string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";

    //Overwrite the values in the existing class instance "playerInstance". Less memory Allocation
    JsonUtility.FromJsonOverwrite(jsonString, playerInstance);
    Debug.Log(playerInstance.playerLoc);
}

2. MULTIPLE DATA(ARRAY JSON)

Your Json contains multiple data objects. For example playerId appeared more than once. Unity's JsonUtility does not support array as it is still new but you can use a helper class from this person to get array working with JsonUtility.

Create a class called JsonHelper. Copy the JsonHelper directly from below.

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson<T>(T[] array, bool prettyPrint)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
}

Serializing Json Array:

Player[] playerInstance = new Player[2];

playerInstance[0] = new Player();
playerInstance[0].playerId = "8484239823";
playerInstance[0].playerLoc = "Powai";
playerInstance[0].playerNick = "Random Nick";

playerInstance[1] = new Player();
playerInstance[1].playerId = "512343283";
playerInstance[1].playerLoc = "User2";
playerInstance[1].playerNick = "Rand Nick 2";

//Convert to JSON
string playerToJson = JsonHelper.ToJson(playerInstance, true);
Debug.Log(playerToJson);

Output:

{
    "Items": [
        {
            "playerId": "8484239823",
            "playerLoc": "Powai",
            "playerNick": "Random Nick"
        },
        {
            "playerId": "512343283",
            "playerLoc": "User2",
            "playerNick": "Rand Nick 2"
        }
    ]
}

Deserializing Json Array:

string jsonString = "{\r\n    \"Items\": [\r\n        {\r\n            \"playerId\": \"8484239823\",\r\n            \"playerLoc\": \"Powai\",\r\n            \"playerNick\": \"Random Nick\"\r\n        },\r\n        {\r\n            \"playerId\": \"512343283\",\r\n            \"playerLoc\": \"User2\",\r\n            \"playerNick\": \"Rand Nick 2\"\r\n        }\r\n    ]\r\n}";

Player[] player = JsonHelper.FromJson<Player>(jsonString);
Debug.Log(player[0].playerLoc);
Debug.Log(player[1].playerLoc);

Output:

Powai

User2


If this is a Json array from the server and you did not create it by hand:

You may have to Add {"Items": in front of the received string then add } at the end of it.

I made a simple function for this:

string fixJson(string value)
{
    value = "{\"Items\":" + value + "}";
    return value;
}

then you can use it:

string jsonString = fixJson(yourJsonFromServer);
Player[] player = JsonHelper.FromJson<Player>(jsonString);

3.Deserialize json string without class && De-serializing Json with numeric properties

This is a Json that starts with a number or numeric properties.

For example:

{ 
"USD" : {"15m" : 1740.01, "last" : 1740.01, "buy" : 1740.01, "sell" : 1744.74, "symbol" : "$"}, 

"ISK" : {"15m" : 179479.11, "last" : 179479.11, "buy" : 179479.11, "sell" : 179967, "symbol" : "kr"},

"NZD" : {"15m" : 2522.84, "last" : 2522.84, "buy" : 2522.84, "sell" : 2529.69, "symbol" : "$"}
}

Unity's JsonUtility does not support this because the "15m" property starts with a number. A class variable cannot start with an integer.

Download SimpleJSON.cs from Unity's wiki.

To get the "15m" property of USD:

var N = JSON.Parse(yourJsonString);
string price = N["USD"]["15m"].Value;
Debug.Log(price);

To get the "15m" property of ISK:

var N = JSON.Parse(yourJsonString);
string price = N["ISK"]["15m"].Value;
Debug.Log(price);

To get the "15m" property of NZD:

var N = JSON.Parse(yourJsonString);
string price = N["NZD"]["15m"].Value;
Debug.Log(price);

The rest of the Json properties that doesn't start with a numeric digit can be handled by Unity's JsonUtility.


4.TROUBLESHOOTING JsonUtility:

Problems when serializing with JsonUtility.ToJson?

Getting empty string or "{}" with JsonUtility.ToJson?

A. Make sure that the class is not an array. If it is, use the helper class above with JsonHelper.ToJson instead of JsonUtility.ToJson.

B. Add [Serializable] to the top of the class you are serializing.

C. Remove property from the class. For example, in the variable, public string playerId { get; set; } remove { get; set; }. Unity cannot serialize this.

Problems when deserializing with JsonUtility.FromJson?

A. If you get Null, make sure that the Json is not a Json array. If it is, use the helper class above with JsonHelper.FromJson instead of JsonUtility.FromJson.

B. If you get NullReferenceException while deserializing, add [Serializable] to the top of the class.

C.Any other problems, verify that your json is valid. Go to this site here and paste the json. It should show you if the json is valid. It should also generate the proper class with the Json. Just make sure to remove remove { get; set; } from each variable and also add [Serializable] to the top of each class generated.


Newtonsoft.Json:

If for some reason Newtonsoft.Json must be used then check out the forked version for Unity here. Note that you may experience crash if certain feature is used. Be careful.


To answer your question:

Your original data is

 [{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]

Add {"Items": in front of it then add } at the end of it.

Code to do this:

serviceData = "{\"Items\":" + serviceData + "}";

Now you have:

 {"Items":[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]}

To serialize the multiple data from php as arrays, you can now do

public player[] playerInstance;
playerInstance = JsonHelper.FromJson<player>(serviceData);

playerInstance[0] is your first data

playerInstance[1] is your second data

playerInstance[2] is your third data

or data inside the class with playerInstance[0].playerLoc, playerInstance[1].playerLoc, playerInstance[2].playerLoc ......

You can use playerInstance.Length to check the length before accessing it.

NOTE: Remove { get; set; } from the player class. If you have { get; set; }, it won't work. Unity's JsonUtility does NOT work with class members that are defined as properties.

Connection timeout for SQL server

Yes, you could append ;Connection Timeout=30 to your connection string and specify the value you wish.

The timeout value set in the Connection Timeout property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).

Moreover, setting the timeout value to 0, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:

A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.

Convert timestamp to readable date/time PHP

strtotime makes a date string into a timestamp. You want to do the opposite, which is date. The typical mysql date format is date('Y-m-d H:i:s'); Check the manual page for what other letters represent.

If you have a timestamp that you want to use (apparently you do), it is the second argument of date().

How to resolve the C:\fakepath?

seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path

sorting a List of Map<String, String>

try {
        java.util.Collections.sort(data,
                new Comparator<Map<String, String>>() {
                    SimpleDateFormat sdf = new SimpleDateFormat(
                            "MM/dd/yyyy");

                    public int compare(final Map<String, String> map1,
                            final Map<String, String> map2) {
                        Date date1 = null, date2 = null;
                        try {
                            date1 = sdf.parse(map1.get("Date"));
                            date2 = sdf.parse(map2.get("Date"));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (date1.compareTo(date2) > 0) {
                            return +1;
                        } else if (date1.compareTo(date2) == 0) {
                            return 0;
                        } else {
                            return -1;
                        }
                    }
                });

    } catch (Exception e) {

    }

How To Raise Property Changed events on a Dependency Property?

I question the logic of raising a PropertyChanged event on the second property when it's the first property that's changing. If the second properties value changes then the PropertyChanged event could be raised there.

At any rate, the answer to your question is you should implement INotifyPropertyChange. This interface contains the PropertyChanged event. Implementing INotifyPropertyChanged lets other code know that the class has the PropertyChanged event, so that code can hook up a handler. After implementing INotifyPropertyChange, the code that goes in the if statement of your OnPropertyChanged is:

if (PropertyChanged != null)
    PropertyChanged(new PropertyChangedEventArgs("MySecondProperty"));

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

The action or event has been blocked by Disabled Mode

Another issue is that your database may be in a "non-trusted" location. Go to the trust center settings and add your database location to the trusted locations list.

Folder is locked and I can't unlock it

I encountered this problem after these operations:

  1. get lock on folder
  2. modify files
  3. remove files and update folders --> new files downloaded
  4. try to commit or release lock

I finally resolved the problem by forcing the lock again : TortoiseSVN --> Get Lock --> check "steal lock" then commit or release lock.

Is there a way to make mv create the directory to be moved to if it doesn't exist?

Save as a script named mv or mv.sh

#!/bin/bash
# mv.sh
dir="$2"
tmp="$2"; tmp="${tmp: -1}"
[ "$tmp" != "/" ] && dir="$(dirname "$2")"
[ -a "$dir" ] ||
mkdir -p "$dir" &&
mv "$@"

Or put at the end of your ~/.bashrc file as a function that replaces the default mv on every new terminal. Using a function allows bash keep it memory, instead of having to read a script file every time.

function mv ()
{
    dir="$2"
    tmp="$2"; tmp="${tmp: -1}"
    [ "$tmp" != "/" ] && dir="$(dirname "$2")"
    [ -a "$dir" ] ||
    mkdir -p "$dir" &&
    mv "$@"
}

These based on the submission of Chris Lutz.

Using lodash to compare jagged arrays (items existence without order)

By 'the same' I mean that there are is no item in array1 that is not contained in array2.

You could use flatten() and difference() for this, which works well if you don't care if there are items in array2 that aren't in array1. It sounds like you're asking is array1 a subset of array2?

var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];

function isSubset(source, target) {
    return !_.difference(_.flatten(source), _.flatten(target)).length;
}

isSubset(array1, array2); // ? true
array1.push('d');
isSubset(array1, array2); // ? false
isSubset(array2, array1); // ? true

Pandas split column of lists into multiple columns

Based on the previous answers, here is another solution which returns the same result as df2.teams.apply(pd.Series) with a much faster run time:

pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

Timings:

In [1]:
import pandas as pd
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2 = pd.concat([df2]*1000).reset_index(drop=True)

In [2]: %timeit df2['teams'].apply(pd.Series)

8.27 s ± 2.73 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

35.4 ms ± 5.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

How to get started with Windows 7 gadgets

Here's an excellent article by Scott Allen: Developing Gadgets for the Windows Sidebar

This site, Windows 7/Vista Sidebar Gadgets, has links to many gadget resources.

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

I was getting the same error after granting remote access until I made this:

From /etc/mysql/my.cnf

In newer versions of mysql the location of the file is /etc/mysql/mysql.conf.d/mysqld.cnf

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address           = 127.0.0.1

(comment this line: bind-address = 127.0.0.1)

Then run service mysql restart.

how do I make a single legend for many subplots with matplotlib?

This answer is a complement to @Evert's on the legend position.

My first try on @Evert's solution failed due to overlaps of the legend and the subplot's title.

In fact, the overlaps are caused by fig.tight_layout(), which changes the subplots' layout without considering the figure legend. However, fig.tight_layout() is necessary.

In order to avoid the overlaps, we can tell fig.tight_layout() to leave spaces for the figure's legend by fig.tight_layout(rect=(0,0,1,0.9)).

Description of tight_layout() parameters.

Populating a razor dropdownlist from a List<object> in MVC

  @Html.DropDownList("ddl",Model.Select(item => new SelectListItem
{
    Value = item.RecordID.ToString(),
    Text = item.Name.ToString(),
     Selected = "select" == item.RecordID.ToString()
}))

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

You should include jquery.fileupload-process.js and jquery.fileupload-validate.js to make it work.

Then...

$(this).fileupload({
    // ...
    processfail: function (e, data) {
        data.files.forEach(function(file){
            if (file.error) {
                self.$errorMessage.html(file.error);
                return false;
            }
        });
    },
//...
}

processfail callback is launched after a validation fail.

Python - Create list with numbers between 2 values?

The most elegant way to do this is by using the range function however if you want to re-create this logic you can do something like this :

def custom_range(*args):
    s = slice(*args)
    start, stop, step = s.start, s.stop, s.step
    if 0 == step:
        raise ValueError("range() arg 3 must not be zero")
    i = start
    while i < stop if step > 0 else i > stop:
        yield i
        i += step

>>> [x for x in custom_range(10, 3, -1)]

This produces the output:

[10, 9, 8, 7, 6, 5, 4]

As expressed before by @Jared, the best way is to use the range or numpy.arrange however I find the code interesting to be shared.

Write Base64-encoded image to file

No need to use BufferedImage, as you already have the image file in a byte array

    byte dearr[] = Base64.decodeBase64(crntImage);
    FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp")); 
    fos.write(dearr); 
    fos.close();

How to pass a form input value into a JavaScript function

It might be cleaner to take out your inline click handler and do it like this:

$(document).ready(function() {
    $('#button-id').click(function() {
      foo($('#formValueId').val());
    });
});

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

One line if/else condition in linux shell scripting

To summarize the other answers, for general use:

Multi-line if...then statement

if [ foo ]; then
    a; b
elif [ bar ]; then
    c; d
else
    e; f
fi

Single-line version

if [ foo ]; then a && b; elif [ bar ]; c && d; else e && f; fi

Using the OR operator

( foo && a && b ) || ( bar && c && d ) || e && f;

Notes

Remember that the AND and OR operators evaluate whether or not the result code of the previous operation was equal to true/success (0). So if a custom function returns something else (or nothing at all), you may run into problems with the AND/OR shorthand. In such cases, you may want to replace something like ( a && b ) with ( [ a == 'EXPECTEDRESULT' ] && b ), etc.

Also note that ( and [ are technically commands, so whitespace is required around them.

Instead of a group of && statements like then a && b; else, you could also run statements in a subshell like then $( a; b ); else, though this is less efficient. The same is true for doing something like result1=$( foo; a; b ); result2=$( bar; c; d ); [ "$result1" -o "$result2" ] instead of ( foo && a && b ) || ( bar && c && d ). Though at that point you'd be getting more into less-compact, multi-line stuff anyway.

How do I add slashes to a string in Javascript?

A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.

str = JSON.stringify(String(str));
str = str.substring(1, str.length-1);

Using this approach, also special chars as the null byte, unicode characters and line breaks \r and \n are escaped properly in a relatively compact statement.

How do I pass a datetime value as a URI parameter in asp.net mvc?

Typical format of a URI for ASP .NET MVC is Controller/Action/Id where Id is an integer

I would suggest sending the date value as a parameter rather than as part of the route:

 mysite/Controller/Action?date=21-9-2009 10:20

If it's still giving you problems the date may contain characters that are not allowed in a URI and need to be encoded. Check out:

 encodeURIComponent(yourstring)

It is a method within Javascript.

On the Server Side:

public ActionResult ActionName(string date)
{
     DateTime mydate;
     DateTime.Tryparse(date, out mydate);
}

FYI, any url parameter can be mapped to an action method parameter as long as the names are the same.

Can I have two JavaScript onclick events in one element?

You could try something like this as well

<a href="#" onclick="one(); two();" >click</a>

<script type="text/javascript">
    function one(){
        alert('test');
    }

    function two(){
        alert('test2');
    }
</script>

JQuery / JavaScript - trigger button click from another button click event

jQuery("input.first").click(function(){
   jQuery("input.second").trigger("click");
   return false;
});

How to run binary file in Linux

full path for binary file. For example: /home/vitaliy2034/binary_file_name. Or use directive "./+binary_file_name". './' in unix system it return full path to directory, in which you open terminal(shell). I hope it helps. Sorry, for my english language)

How do I programmatically change file permissions?

There is an example class on Oracle Docs which works very much similar to the UNIX chmod. It works with java se 7+ though.

Python Pandas replicate rows in dataframe

Other way is using concat() function:

import pandas as pd

In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

In [604]: df
Out[604]: 
  col1  col2
0    a     0
1    b     1
2    c     2

In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]: 
  col1  col2
0    a     0
1    b     1
2    c     2
3    a     0
4    b     1
5    c     2
6    a     0
7    b     1
8    c     2

In [606]: pd.concat([df]*3)
Out[606]: 
  col1  col2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2

How to use SortedMap interface in Java?

TreeMap sorts by the key natural ordering. The keys should implement Comparable or be compatible with a Comparator (if you passed one instance to constructor). In you case, Float already implements Comparable so you don't have to do anything special.

You can call keySet to retrieve all the keys in ascending order.

How to Delete node_modules - Deep Nested Folder in Windows

What worked for me was:

  1. closed the node manager console
  2. closed the Atom (visual studio code ) dev environment you are in.
  3. then delete the node_modules

    npm install rimraf -g 
    rimraf node_modules
    

How to exclude a directory from ant fileset, based on directories contents

Answer provided by user mgaert works for me. I think it should be marked as the right answer.

It works also with complex selectors like in this example:

<!-- 
    selects only direct subdirectories of ${targetdir} if they have a
    sub-subdirectory named either sub1 or sub2
-->
<dirset dir="${targetdir}" >
    <and>
        <depth max="0"/>
        <or>
            <present targetdir="${targetdir}">
                <globmapper from="*" to="*/sub1" />
            </present>
            <present targetdir="${targetdir}">
                <globmapper from="*" to="*/sub2" />
            </present>
        </or>
    </and>
</dirset>

Thus, having a directory structure like this:

targetdir
+-- bar
¦   +-- sub3
+-- baz
¦   +-- sub1
+-- foo
¦   +-- sub2
+-- phoo
¦   +-- sub1
¦   +-- sub2
+-- qux
    +-- xyzzy
        +-- sub1

the above dirset would contain only

baz foo phoo
(bar doesn't match because of sub3 while xyzzy doesn't match because it's not a direct subdirectory of targetdir)

How do I install cygwin components from the command line?

Old question, but still relevant. Here is what worked for me today (6/26/16).

From the bash shell:

lynx -source rawgit.com/transcode-open/apt-cyg/master/apt-cyg > apt-cyg
install apt-cyg /bin

How to convert a Collection to List?

Collections.sort( new ArrayList( coll ) );

Convert between UIImage and Base64 string

See my class -  AppExtension.swift


// MARK: - UIImage (Base64 Encoding)

public enum ImageFormat {
    case PNG
    case JPEG(CGFloat)
}

extension UIImage {

    public func base64(format: ImageFormat) -> String {
        var imageData: NSData
        switch format {
        case .PNG: imageData = UIImagePNGRepresentation(self)
        case .JPEG(let compression): imageData = UIImageJPEGRepresentation(self, compression)
        }
        return imageData.base64EncodedStringWithOptions(.allZeros)
    }
}

Converting dd/mm/yyyy formatted string to Datetime

You can use "dd/MM/yyyy" format for using it in DateTime.ParseExact.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Here is a DEMO.

For more informations, check out Custom Date and Time Format Strings

How to create text file and insert data to that file on Android

First create a Project With PdfCreation in Android Studio

Then Follow below steps:

1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/PDF");
        System.out.print(myDir.toString());
        myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
        try {
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } // Open Document for Writting into document
        document.open(); // User Define Method
        addMetaData(document);
        try {
            addTitlePage(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        } // Close Document after writting all content
        document.close();

5.   public void addMetaData(Document document)
    {
        document.addTitle("RESUME");
        document.addSubject("Person Info");
        document.addKeywords("Personal, Education, Skills");
                document.addAuthor("TAG");
        document.addCreator("TAG");
    }
    public void addTitlePage(Document document) throws DocumentException
    { // Font Style for Document
        Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
        Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
                | Font.UNDERLINE, BaseColor.GRAY);
        Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
        Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
        Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
        prHead.setFont(titleFont); // Add item into Paragraph
        prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
        PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
        myTable.setWidthPercentage(100.0f); // Create New Cell into Table
        PdfPCell myCell = new PdfPCell(new Paragraph(""));
        myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
        myTable.addCell(myCell);
        prHead.setFont(catFont);
        prHead.add("\nName1 Name2\n");
        prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
        document.add(prHead);
        document.add(myTable);
        document.add(myTable); // Now Start another New Paragraph
        Paragraph prPersinalInfo = new Paragraph();
        prPersinalInfo.setFont(smallBold);
        prPersinalInfo.add("Address 1\n");
        prPersinalInfo.add("Address 2\n");
        prPersinalInfo.add("City: SanFran. State: CA\n");
        prPersinalInfo.add("Country: USA Zip Code: 000001\n");
        prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: [email protected] \n");
        prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
        document.add(prPersinalInfo);
        document.add(myTable);
        document.add(myTable);
        Paragraph prProfile = new Paragraph();
        prProfile.setFont(smallBold);
        prProfile.add("\n \n Profile : \n ");
        prProfile.setFont(normal);
        prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
        prProfile.setFont(smallBold);
        document.add(prProfile); // Create new Page in PDF
        document.newPage();
    }

Ascending and Descending Number Order in java

Sort the array just as before, but print the elements out in reverse order, using a loop that counts down rather than counting up.

Also, move the sort out of the loop - you are currently sorting the array over and over again when you only need to sort it once.

                Arrays.sort(arr);
                for(int i = 0; i < arr.length; i++){
                    //Arrays.sort(arr); // not here
                    System.out.print( " " +arr[i]);
                }
                for(int i = arr.length-1; i >= 0; i--){
                    //Arrays.sort(arr); // not here
                    System.out.print( " " +arr[i]);
                }

How to Apply global font to whole HTML document

Try this:

body
{
    font-family:your font;
    font-size:your value;
    font-weight:your value;
}

What's the difference between interface and @interface in java?

The @ symbol denotes an annotation type definition.

That means it is not really an interface, but rather a new annotation type -- to be used as a function modifier, such as @override.

See this javadocs entry on the subject.

How to find if a file contains a given string using Windows command line

I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

Hope it helps!

How does facebook, gmail send the real time notification?

The way Facebook does this is pretty interesting.

A common method of doing such notifications is to poll a script on the server (using AJAX) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened.

The way Facebook does it is using the comet approach, rather than polling on an interval, as soon as one poll completes, it issues another one. However, each request to the script on the server has an extremely long timeout, and the server only responds to the request once something has happened. You can see this happening if you bring up Firebug's Console tab while on Facebook, with requests to a script possibly taking minutes. It is quite ingenious really, since this method cuts down immediately on both the number of requests, and how often you have to send them. You effectively now have an event framework that allows the server to 'fire' events.

Behind this, in terms of the actual content returned from those polls, it's a JSON response, with what appears to be a list of events, and info about them. It's minified though, so is a bit hard to read.

In terms of the actual technology, AJAX is the way to go here, because you can control request timeouts, and many other things. I'd recommend (Stack overflow cliche here) using jQuery to do the AJAX, it'll take a lot of the cross-compability problems away. In terms of PHP, you could simply poll an event log database table in your PHP script, and only return to the client when something happens? There are, I expect, many ways of implementing this.

Implementing:

Server Side:

There appear to be a few implementations of comet libraries in PHP, but to be honest, it really is very simple, something perhaps like the following pseudocode:

while(!has_event_happened()) {
   sleep(5);
}

echo json_encode(get_events());
  • The has_event_happened function would just check if anything had happened in an events table or something, and then the get_events function would return a list of the new rows in the table? Depends on the context of the problem really.

  • Don't forget to change your PHP max execution time, otherwise it will timeout early!

Client Side:

Take a look at the jQuery plugin for doing Comet interaction:

That said, the plugin seems to add a fair bit of complexity, it really is very simple on the client, perhaps (with jQuery) something like:

function doPoll() {
   $.get("events.php", {}, function(result) {
      $.each(result.events, function(event) { //iterate over the events
          //do something with your event
      });
      doPoll(); 
      //this effectively causes the poll to run again as
      //soon as the response comes back
   }, 'json'); 
}

$(document).ready(function() {
    $.ajaxSetup({
       timeout: 1000*60//set a global AJAX timeout of a minute
    });
    doPoll(); // do the first poll
});

The whole thing depends a lot on how your existing architecture is put together.

How do I check if an object has a key in JavaScript?

You should use hasOwnProperty. For example:

myObj.hasOwnProperty('myKey');

Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:

Object.prototype.hasOwnProperty.call(myObj, 'myKey');

PSEXEC, access denied errors

For anybody who may stumble upon this. There is a recent (Dec 2013) Security Update from Microsoft Windows on Windows 7 that is preventing remote execution. See http://support.microsoft.com/kb/2893294/en-us

I uninstalled the Security Update by going to Control Panel\Programs\Programs and Features\Installed Updates

It worked right after that.

Search in all files in a project in Sublime Text 3

You can search a directory using Find ? Find in files. This also includes all opened tabs.

The keyboard shortcut is Ctrl?+F on non-Mac (regular) keyboards, and ??+F on a Mac.

You'll be presented with three boxes: Find, Where and Replace. It's a regular Find/Find-replace search where Where specifies a file or directory to search. I for example often use a file name or . for searching the current directory. There are also a few special constructs that can be used within the Where field:

<project>,<current file>,<open files>,<open folders>,-*.doc,*.txt

Note that these are not placeholders, you type these verbatim. Most of them are self-explanatory (e.g. -*.doc excludes files with a .doc extension).

Pressing the ... to the right will present you with all available options.

After searching you'll be presented with a Find results page with all of your matching results. To jump to specific lines and files from it you simply double-click on a line.

Can I use Twitter Bootstrap and jQuery UI at the same time?

If don't store it locally and use the link that they provide you might have an improved performance.The client might have the scripts already cached in some cases. As for the case of jQueryUI i would recommend not loading it until necessary. They are both minimized, but you can fire up the console and look at the network tab and see how long it takes for it to load, once it is initially downloaded it will be cached so you shouldn't worry afterwards.My conclusion would be yes use them both but use a CDN

Spring Boot Multiple Datasource

Update 2018-01-07 with Spring Boot 1.5.8.RELEASE

If you want to know how to config it, how to use it, and how to control transaction. I may have answers for you.

You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/

I copied some code here.

First you have to set application.properties like this

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

Then define them as providers (@Bean) like this:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}

Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example

@Qualifier("datasource1")
@Autowired
private DataSource dataSource;

If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:

@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

Then you can use it like

@Transactional //this will use the first datasource because it is @primary

or

@Transactional("tm2")

This should be enough. See example and detail in the link above.

Docker CE on RHEL - Requires: container-selinux >= 2.9

[SOLVED] Simple one command to fix this issue.

yum install http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-3.el7.noarch.rpm

How to set default value to the input[type="date"]

1 - @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    <input type="date" "myDate">
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

    var today = new Date();
    $('#myDate').val(today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2));

2 - @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   <input type="datatime-local" id="myLocalDataTime" step="1">
    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

var today = new Date();
$('#myLocalDataTime').val(today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2)+'T'+today.getHours()+':'+today.getMinutes());

Convert string to float?

Using Float.parseFloat()?

class Test {
    public static void main(String[] args) {
        String s = "3.14";
        float f = Float.parseFloat(s);
        System.out.println(f);
    }
}

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

Create web service proxy in Visual Studio from a WSDL file

Since the true Binding URL for the web service is located in the file, you could do these simple steps from your local machine:

1) Save the file to your local computer for example:

C:\Documents and Settings\[user]\Desktop\Webservice1.asmx

2) In Visual Studio Right Click on your project > Choose Add Web Reference, A dialog will open.

3) In the URL Box Copy the local file location above C:\Documents and Settings[user]\Desktop\Webservice1.asmx, Click Next

4) Now you will see the functions appear, choose your name for the reference, Click add reference

5) You are done! you can start using it as a namespace in your application don't worry that you used a local file, because anyway the true URL for the service is located in the file at the Binding section

How to disable spring security for particular url

This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
                .anyRequest().permitAll()
                .and()
                .formLogin().loginPage("/web/login").permitAll()
                .and()
                .csrf().ignoringAntMatchers("/contact-email")
                .and()
                .logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles(ADMIN.toString())
                .and()
                .withUser("guest").password("guest").roles(GUEST.toString());
    }

}

I have included full configuration but the key line is:

.csrf().ignoringAntMatchers("/contact-email")

Convert array to JSON string in swift

As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.

As long as the array contains only JSON encodable values (string, number, dictionary, array, nil) you can just use NSJSONSerialization to do it.

Instead just do the array->data->string parts:

Swift 3/4

let array = [ "one", "two" ]

func json(from object:Any) -> String? {
    guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
        return nil
    }
    return String(data: data, encoding: String.Encoding.utf8)
}

print("\(json(from:array as Any))")

Original Answer

let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)

although you should probably not use forced unwrapping, it gives you the right starting point.

How to create a new schema/new user in Oracle Database 11g?

It's a working example:

CREATE USER auto_exchange IDENTIFIED BY 123456;
GRANT RESOURCE TO auto_exchange;
GRANT CONNECT TO auto_exchange;
GRANT CREATE VIEW TO auto_exchange;
GRANT CREATE SESSION TO auto_exchange;
GRANT UNLIMITED TABLESPACE TO auto_exchange;

How to change the text color of first select option

I really wanted this (placeholders should look the same for text boxes as select boxes!) and straight CSS wasn't working in Chrome. Here is what I did:

First make sure your select tag has a .has-prompt class.

Then initialize this class somewhere in document.ready.

# Adds a class to select boxes that have prompt currently selected.
# Allows for placeholder-like styling.
# Looks for has-prompt class on select tag.
Mess.Views.SelectPromptStyler = Backbone.View.extend
  el: 'body'

  initialize: ->
    @$('select.has-prompt').trigger('change')

  events:
    'change select.has-prompt': 'changed'

  changed: (e) ->
    select = @$(e.currentTarget)
    if select.find('option').first().is(':selected')
      select.addClass('prompt-selected')
    else
      select.removeClass('prompt-selected')

Then in CSS:

select.prompt-selected {
  color: $placeholder-color;
}

ImportError: No module named PIL

In shell, run:

pip install Pillow

Attention: PIL is deprecated, and pillow is the successor.

break/exit script

You can use the pskill function in the R "tools" package to interrupt the current process and return to the console. Concretely, I have the following function defined in a startup file that I source at the beginning of each script. You can also copy it directly at the start of your code, however. Then insert halt() at any point in your code to stop script execution on the fly. This function works well on GNU/Linux and judging from the R documentation, it should also work on Windows (but I didn't check).

# halt: interrupts the current R process; a short iddle time prevents R from
# outputting further results before the SIGINT (= Ctrl-C) signal is received 
halt <- function(hint = "Process stopped.\n") {
    writeLines(hint)
    require(tools, quietly = TRUE)
    processId <- Sys.getpid() 
    pskill(processId, SIGINT)
    iddleTime <- 1.00
    Sys.sleep(iddleTime)
}

decompiling DEX into Java sourcecode

Since no one mentioned this, there's one more tool: DED homepage

Install how-to and some explanations: Installation.

It was used in a quite interesting study of the security of top market apps(not really related, just if you're curious): A Survey of Android Application Security

Making href (anchor tag) request POST instead of GET?

To do POST you'll need to have a form.

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

Some tricks: Make a link use POST instead of GET and How do you post data with a link

Edit: to load response on a frame you can target your form to your frame:

<form action="employee.action" method="post" target="myFrame">

Check if a number is int or float

def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  if absolute - rounded == 0:
    print str(x) + " is an integer"
  else:
    print str(x) +" is not an integer"


is_int(7.0) # will print 7.0 is an integer

How to expire a cookie in 30 minutes using jQuery?

30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.

 var date = new Date();
 var minutes = 30;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });

How to assign colors to categorical variables in ggplot2 that have stable mapping?

This is an old post, but I was looking for answer to this same question,

Why not try something like:

scale_color_manual(values = c("foo" = "#999999", "bar" = "#E69F00"))

If you have categorical values, I don't see a reason why this should not work.

What is the default text size on Android?

http://petrnohejl.github.io/Android-Cheatsheet-For-Graphic-Designers/

Text size

Type    Dimension
Micro   12 sp
Small   14 sp
Medium  18 sp
Large   22 sp

self.tableView.reloadData() not working in Swift

I was also facing the same issue, what I did wrong was that I'd forgot to add

tableView.delegate = self    
tableView.dataSource = self

in the viewDidLoad() {} method. This could be one reason of self.tableView.reloadData() not working.

How do I trigger a macro to run after a new mail is received in Outlook?

This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.

Private WithEvents Items As Outlook.Items 
Private Sub Application_Startup() 
  Dim olApp As Outlook.Application 
  Dim objNS As Outlook.NameSpace 
  Set olApp = Outlook.Application 
  Set objNS = olApp.GetNamespace("MAPI") 
  ' default local Inbox
  Set Items = objNS.GetDefaultFolder(olFolderInbox).Items 
End Sub
Private Sub Items_ItemAdd(ByVal item As Object) 

  On Error Goto ErrorHandler 
  Dim Msg As Outlook.MailItem 
  If TypeName(item) = "MailItem" Then
    Set Msg = item 
    ' ******************
    ' do something here
    ' ******************
  End If
ProgramExit: 
  Exit Sub
ErrorHandler: 
  MsgBox Err.Number & " - " & Err.Description 
  Resume ProgramExit 
End Sub

After pasting the code in ThisOutlookSession module, you must restart Outlook.

Hive Alter table change Column Name

Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.

EXAMPLE:

hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;

  MismatchedTokenException(49!=90)
        at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
        at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
        at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
        ...

hive> use databasename;

hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;

OK

Only allow specific characters in textbox

You can probably use the KeyDown event, KeyPress event or KeyUp event. I would first try the KeyDown event I think.

You can set the Handled property of the event args to stop handling the event.

What is the email subject length limit?

RFC2322 states that the subject header "has no length restriction"

but to produce long headers but you need to split it across multiple lines, a process called "folding".

subject is defined as "unstructured" in RFC 5322

here's some quotes ([...] indicate stuff i omitted)

3.6.5. Informational Fields
  The informational fields are all optional.  The "Subject:" and
  "Comments:" fields are unstructured fields as defined in section
  2.2.1, [...]

2.2.1. Unstructured Header Field Bodies
  Some field bodies in this specification are defined simply as
  "unstructured" (which is specified in section 3.2.5 as any printable
  US-ASCII characters plus white space characters) with no further
  restrictions.  These are referred to as unstructured field bodies.
  Semantically, unstructured field bodies are simply to be treated as a
  single line of characters with no further processing (except for
  "folding" and "unfolding" as described in section 2.2.3).

2.2.3  [...]  An unfolded header field has no length restriction and
  therefore may be indeterminately long.

How do I use the JAVA_OPTS environment variable?

JAVA_OPTS is not restricted to Tomcat’s Java process, but passed to all JVM processes running on the same machine.

Use CATALINA_OPTS if you specifically want to pass JVM arguments to Tomcat's servlet engine.

unix sort descending order

The presence of the n option attached to the -k5 causes the global -r option to be ignored for that field. You have to specify both n and r at the same level (globally or locally).

sort -t $'\t' -k5,5rn

or

sort -rn -t $'\t' -k5,5

how to get vlc logs?

Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...

How to deep copy a list?

If you are not allowed to directly import modules you can define your own deepcopy function as -

def copyList(L):
if type(L[0]) != list:
    return [i for i in L]
else:
    return [copyList(L[i]) for i in range(len(L))]

It's working can be seen easily as -

>>> x = [[1,2,3],[3,4]]
>>> z = copyList(x)
>>> x
[[1, 2, 3], [3, 4]]
>>> z
[[1, 2, 3], [3, 4]]
>>> id(x)
2095053718720
>>> id(z)
2095053718528
>>> id(x[0])
2095058990144
>>> id(z[0])
2095058992192
>>>

Read/write files within a Linux kernel module

Since version 4.14 of Linux kernel, vfs_read and vfs_write functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:

# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);

# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
            loff_t *pos);

Also, filp_open no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs).

JavaScript "cannot read property "bar" of undefined

You can safeguard yourself either of these two ways:

function myFunc(thing) {
    if (thing && thing.foo && thing.foo.bar) {
        // safe to use thing.foo.bar here
    }
}

function myFunc(thing) {
    try {
        var x = thing.foo.bar;
        // do something with x
    } catch(e) {
        // do whatever you want when thing.foo.bar didn't work
    }
}

In the first example, you explicitly check all the possible elements of the variable you're referencing to make sure it's safe before using it so you don't get any unplanned reference exceptions.

In the second example, you just put an exception handler around it. You just access thing.foo.bar assuming it exists. If it does exist, then the code runs normally. If it doesn't exist, then it will throw an exception which you will catch and ignore. The end result is the same. If thing.foo.bar exists, your code using it executes. If it doesn't exist that code does not execute. In all cases, the function runs normally.

The if statement is faster to execute. The exception can be simpler to code and use in complex cases where there may be many possible things to protect against and your code is structured so that throwing an exception and handling it is a clean way to skip execution when some piece of data does not exist. Exceptions are a bit slower when the exception is thrown.

Make error: missing separator

I had the missing separator file in Makefiles generated by qmake. I was porting Qt code to a different platform. I didn't have QMAKESPEC nor MAKE set. Here's the link I found the answer:

https://forum.qt.io/topic/3783/missing-separator-error-in-makefile/5

Android scale animation on view

Here is a code snip to do exactly that.

public void scaleView(View v, float startScale, float endScale) {
    Animation anim = new ScaleAnimation(
            1f, 1f, // Start and end values for the X axis scaling
            startScale, endScale, // Start and end values for the Y axis scaling
            Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
            Animation.RELATIVE_TO_SELF, 1f); // Pivot point of Y scaling
    anim.setFillAfter(true); // Needed to keep the result of the animation
    anim.setDuration(1000);
    v.startAnimation(anim);
}

The ScaleAnimation constructor used here takes 8 args, 4 related to handling the X-scale which we don't care about (1f, 1f, ... Animation.RELATIVE_TO_SELF, 0f, ...).

The other 4 args are for the Y-scaling we do care about.

startScale, endScale - In your case, you'd use 0f, 0.6f.

Animation.RELATIVE_TO_SELF, 1f - This specifies where the shrinking of the view collapses to (referred to as the pivot in the documentation). Here, we set the float value to 1f because we want the animation to start growing the bar from the bottom. If we wanted it to grow downward from the top, we'd use 0f.

Finally, and equally important, is the call to anim.setFillAfter(true). If you want the result of the animation to stick around after the animation completes, you must run this on the animator before executing the animation.

So in your case, you can do something like this:

View v = findViewById(R.id.viewContainer);
scaleView(v, 0f, .6f);

Practical uses for the "internal" keyword in C#

I have a project which uses LINQ-to-SQL for the data back-end. I have two main namespaces: Biz and Data. The LINQ data model lives in Data and is marked "internal"; the Biz namespace has public classes which wrap around the LINQ data classes.

So there's Data.Client, and Biz.Client; the latter exposes all relevant properties of the data object, e.g.:

private Data.Client _client;
public int Id { get { return _client.Id; } set { _client.Id = value; } }

The Biz objects have a private constructor (to force the use of factory methods), and an internal constructor which looks like this:

internal Client(Data.Client client) {
    this._client = client;
}

That can be used by any of the business classes in the library, but the front-end (UI) has no way of directly accessing the data model, ensuring that the business layer always acts as an intermediary.

This is the first time I've really used internal much, and it's proving quite useful.

Multi-line string with extra space (preserved indentation)

Just to mention a simple one-line concatenation as it can be useful sometimes.

# for bash

v=" guga "$'\n'"   puga "

# Just for an example.
v2="bar "$'\n'"   foo "$'\n'"$v"

# Let's simplify the previous version of $v2.
n=$'\n'
v3="bar ${n}   foo ${n}$v"

echo "$v3" 

You'll get something like this

bar 
   foo 
 guga 
   puga 

All leading and ending white spaces will be preserved right for

echo "$v3" > filename