Programs & Examples On #Forms authentication

Forms Authentication is a built-in and extensible system for authenticating users in an ASP.Net application that also maintains that authenticated session via a ticket (often stored as a cookie or query string parameter).

ASP.NET MVC - Set custom IIdentity or IPrincipal

Based on LukeP's answer, and add some methods to setup timeout and requireSSL cooperated with Web.config.

The references links

Modified Codes of LukeP

1, Set timeout based on Web.Config. The FormsAuthentication.Timeout will get the timeout value, which is defined in web.config. I wrapped the followings to be a function, which return a ticket back.

int version = 1;
DateTime now = DateTime.Now;

// respect to the `timeout` in Web.config.
TimeSpan timeout = FormsAuthentication.Timeout;
DateTime expire = now.Add(timeout);
bool isPersist = false;

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
     version,          
     name,
     now,
     expire,
     isPersist,
     userData);

2, Configure the cookie to be secure or not, based on the RequireSSL configuration.

HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
// respect to `RequreSSL` in `Web.Config`
bool bSSL = FormsAuthentication.RequireSSL;
faCookie.Secure = bSSL;

How to check user is "logged in"?

The simplest way:

if (Request.IsAuthenticated) ...

How to get the current user in ASP.NET MVC

In order to reference a user ID created using simple authentication built into ASP.NET MVC 4 in a controller for filtering purposes (which is helpful if you are using database first and Entity Framework 5 to generate code-first bindings and your tables are structured so that a foreign key to the userID is used), you can use

WebSecurity.CurrentUserId

once you add a using statement

using System.Web.Security;

FormsAuthentication.SignOut() does not log the user out

Users can still browse your website because cookies are not cleared when you call FormsAuthentication.SignOut() and they are authenticated on every new request. In MS documentation is says that cookie will be cleared but they don't, bug? Its exactly the same with Session.Abandon(), cookie is still there.

You should change your code to this:

FormsAuthentication.SignOut();
Session.Abandon();

// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);

// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
SessionStateSection sessionStateSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
HttpCookie cookie2 = new HttpCookie(sessionStateSection.CookieName, "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);

FormsAuthentication.RedirectToLoginPage();

HttpCookie is in the System.Web namespace. MSDN Reference.

How to get the cookie value in asp.net website

HttpCookie cook = new HttpCookie("testcook");
cook = Request.Cookies["CookName"];
if (cook != null)
{
    lbl_cookie_value.Text = cook.Value;
}
else
{
    lbl_cookie_value.Text = "Empty value";
}

Reference Click here

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

How do I hide an element when printing a web page?

Here is a simple solution put this CSS

@media print{
   .noprint{
       display:none;
   }
}

and here is the HTML

<div class="noprint">
    element that need to be hidden when printing
</div>

Most popular screen sizes/resolutions on Android phones

The vast majority of current android 2.1+ phone screens are 480x800 (or in the case of motodroid oddities, 480x854)

However, this doesn't mean this should be your only concern. You need to make it looking good on tablets, and smaller or 4:3 ratio smaller screens.

RelativeLayout is your friend!

How to control the line spacing in UILabel

Swift 4 label extension. Creating NSMutableAttributedString before passing into function in case there are extra attributes required for the attributed text.

extension UILabel {

    func setLineHeightMultiple(to height: CGFloat, withAttributedText attributedText: NSMutableAttributedString) {

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 1.0
        paragraphStyle.lineHeightMultiple = height
        paragraphStyle.alignment = textAlignment

        attributedText.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedText.length - 1))

        self.attributedText = attributedText
    }
}

Is there a NumPy function to return the first index of something in an array?

Yes, given an array, array, and a value, item to search for, you can use np.where as:

itemindex = numpy.where(array==item)

The result is a tuple with first all the row indices, then all the column indices.

For example, if an array is two dimensions and it contained your item at two locations then

array[itemindex[0][0]][itemindex[1][0]]

would be equal to your item and so would be:

array[itemindex[0][1]][itemindex[1][1]]

How to round a numpy array?

If you want the output to be

array([1.6e-01, 9.9e-01, 3.6e-04])

the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:

def my_round(value, N):
    exponent = np.ceil(np.log10(value))
    return 10**exponent*np.round(value*10**(-exponent), N)

For a general solution handling 0 and negative values as well, you can do something like this:

def my_round(value, N):
    value = np.asarray(value).copy()
    zero_mask = (value == 0)
    value[zero_mask] = 1.0
    sign_mask = (value < 0)
    value[sign_mask] *= -1
    exponent = np.ceil(np.log10(value))
    result = 10**exponent*np.round(value*10**(-exponent), N)
    result[sign_mask] *= -1
    result[zero_mask] = 0.0
    return result

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

I face the same issue. I am using docker version:17.09.0-ce.

I follow below steps:

  1. Create Dockerfile and added commands for creating docker image
  2. Go to directory where we have created Dockfile
  3. execute below command $ sudo docker build -t ubuntu-test:latest .

It resolved issue and image created successsfully.

Note: build command depend on docker version as well as which build option we are using. :)

GridView Hide Column by code

This helped for me

this.myGridview.Columns[0].Visible = false;

Here 0 is the column index i want to hide.

Why is Visual Studio 2013 very slow?

I added "devenv.exe" as an exclusion to Windows Defender. This solved my problem completely. People can try this as their first try.

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

I didn't think it would be that simple! go to this link: https://www.codeproject.com/Articles/18399/Localizing-System-MessageBox

Download the source. Take the MessageBoxManager.cs file, add it to your project. Now just register it once in your code (for example in the Main() method inside your Program.cs file) and it will work every time you call MessageBox.Show():

    MessageBoxManager.OK = "Alright";
    MessageBoxManager.Yes = "Yep!";
    MessageBoxManager.No = "Nope";
    MessageBoxManager.Register();

See this answer for the source code here for MessageBoxManager.cs.

Compare integer in bash, unary operator expected

Judging from the error message the value of i was the empty string when you executed it, not 0.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

I had this issue. Tracked it down after trying most the other answers on this question. It was caused by the owner and permissions of the /var/lib/nginx and more specifically the /var/lib/nginx/tmp directory being incorrect.

The tmp directory is used by fast-cgi to cache responses as they are generated, but only if they are above a certain size. So the issue is intermittent and only occurs when the generated response is large.

Check the nginx <host_name>.error_log to see if you are having permission issues.

To fix, ensure the owner and group of /var/lib/nginx and all sub-dirs is nginx.

I have also seen this intermittently occur when space on the storage device is too low to create the temporary file. The solution in this case is to free up some space on the device.

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

You can do this things on this way:

using System.Reflection;

Assembly MyDALL = Assembly.Load("DALL"); //DALL name of your assembly
Type MyLoadClass = MyDALL.GetType("DALL.LoadClass"); // name of your class
 object  obj = Activator.CreateInstance(MyLoadClass);

document.getElementByID is not a function

There are several things wrong with this as you can see in the other posts, but the reason you're getting that error is because you name your form getElementById. So document.getElementById now points to your form instead of the default method that javascript provides. See my fiddle for a working demo https://jsfiddle.net/jemartin80/nhjehwqk/.

function checkValues()
{
   var isFormValid, form_fname;

   isFormValid = true;
   form_fname = document.getElementById("fname");
   if (form_fname.value === "")
   {
       isFormValid = false;
   }
   isFormValid || alert("I am indicating that there is something wrong with your input.")

   return isFormValid;
}

Reverting single file in SVN to a particular revision

For a single file, you could do:

svn export -r <REV> svn://host/path/to/file/on/repos file.ext

You could do svn revert <file> but that will only restore the last working copy.

jQuery autohide element after 5 seconds

You use setTimeout on you runEffect function :

function runEffect() {
    setTimeout(function(){
        var selectedEffect = 'blind';
        var options = {};
        $("#successMessage").hide(selectedEffect, options, 500)
     }, 5000);
}

Calling Non-Static Method In Static Method In Java

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method.

class A
{
    void method()
    {
    }
}
class Demo
{
    static void method2()
    {
        A a=new A();

        a.method();
    }
    /*
    void method3()
    {
        A a=new A();
        a.method();
    }
    */

    public static void main(String args[])
    {
        A a=new A();
        /*an instance of the class is created to access non-static method from a static method */
        a.method();

        method2();

        /*method3();it will show error non-static method can not be  accessed from a static method*/
    }
}

Eclipse fonts and background color

I just came across this: Eclipse Colour Themes

Install the plugin and choose from a selection of pre-defined themes, or write your own. Just what I needed!

How can I install packages using pip according to the requirements.txt file from a local directory?

This works for me:

$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages

--no-index - Ignore package index (only looking at --find-links URLs instead).

-f, --find-links <URL> - If a URL or path to an HTML file, then parse for links to archives.

If a local path or file:// URL that's a directory, then look for archives in the directory listing.

Skip certain tables with mysqldump

You can use the --ignore-table option. So you could do

mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql

There is no whitespace after -p (this is not a typo).

To ignore multiple tables, use this option multiple times, this is documented to work since at least version 5.0.

If you want an alternative way to ignore multiple tables you can use a script like this:

#!/bin/bash
PASSWORD=XXXXXX
HOST=XXXXXX
USER=XXXXXX
DATABASE=databasename
DB_FILE=dump.sql
EXCLUDED_TABLES=(
table1
table2
table3
table4
tableN   
)
 
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE} > ${DB_FILE}

echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}

Android - How to achieve setOnClickListener in Kotlin?

Use this code to add onClickListener in Kotlin

val button : Button = getView()?.findViewById<Button>(R.id.testButton) as Button
button.setOnClickListener {view ->
         Toast.makeText(context, "Write your message here", Toast.LENGTH_LONG).show()
    }
}

Generating a unique machine id

Can you pull some kind of manufacturer serial number or service tag?

Our shop is a Dell shop, so we use the service tag which is unique to each machine to identify them. I know it can be queried from the BIOS, at least in Linux, but I don't know offhand how to do it in Windows.

How do I get the domain originating the request in express.js?

Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host') is deprecated, that's why giving Undefined. Use,

    req.header('Origin');
    req.header('Host');
    // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.

Get epoch for a specific date using Javascript

Take a look at http://www.w3schools.com/jsref/jsref_obj_date.asp

There is a function UTC() that returns the milliseconds from the unix epoch.

Center image using text-align center?

To center an image with CSS.

img{
    display: block;
    margin-left: auto;
    margin-right: auto;
}

You can learn more here

$http get parameters does not work

From $http.get docs, the second parameter is a configuration object:

get(url, [config]);

Shortcut method to perform GET request.

You may change your code to:

$http.get('accept.php', {
    params: {
        source: link, 
        category_id: category
    }
});

Or:

$http({
    url: 'accept.php', 
    method: 'GET',
    params: { 
        source: link, 
        category_id: category
    }
});

As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:

$http.get('/url', config).then(successCallback, errorCallback);

Undefined reference to 'vtable for xxx'

If a class defines virtual methods outside that class, then g++ generates the vtable only in the object file that contains the outside-of-class definition of the virtual method that was declared first:

//test.h
struct str
{
   virtual void f();
   virtual void g();
};

//test1.cpp
#include "test.h"
void str::f(){}

//test2.cpp
#include "test.h"
void str::g(){}

The vtable will be in test1.o, but not in test2.o

This is an optimisation g++ implements to avoid having to compile in-class-defined virtual methods that would get pulled in by the vtable.

The link error you describe suggests that the definition of a virtual method (str::f in the example above) is missing in your project.

Query to search all packages for table and/or column

By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.

(\s|\(|\.|,|^)bqr(\s|,|\)|$)

Facebook Graph API : get larger pictures in one request

In pictures URL found in the Graph responses (the "http://photos-c.ak.fbcdn.net/" ones), just replace the default "_s.jpg" by "_n.jpg" (? normal size) or "_b.jpg" (? big size) or "_t.jpg" (thumbnail).

Hacakable URLs/REST API make the Web better.

Entity Framework Queryable async

The problem seems to be that you have misunderstood how async/await work with Entity Framework.

About Entity Framework

So, let's look at this code:

public IQueryable<URL> GetAllUrls()
{
    return context.Urls.AsQueryable();
}

and example of it usage:

repo.GetAllUrls().Where(u => <condition>).Take(10).ToList()

What happens there?

  1. We are getting IQueryable object (not accessing database yet) using repo.GetAllUrls()
  2. We create a new IQueryable object with specified condition using .Where(u => <condition>
  3. We create a new IQueryable object with specified paging limit using .Take(10)
  4. We retrieve results from database using .ToList(). Our IQueryable object is compiled to sql (like select top 10 * from Urls where <condition>). And database can use indexes, sql server send you only 10 objects from your database (not all billion urls stored in database)

Okay, let's look at first code:

public async Task<IQueryable<URL>> GetAllUrlsAsync()
{
    var urls = await context.Urls.ToListAsync();
    return urls.AsQueryable();
}

With the same example of usage we got:

  1. We are loading in memory all billion urls stored in your database using await context.Urls.ToListAsync();.
  2. We got memory overflow. Right way to kill your server

About async/await

Why async/await is preferred to use? Let's look at this code:

var stuff1 = repo.GetStuff1ForUser(userId);
var stuff2 = repo.GetStuff2ForUser(userId);
return View(new Model(stuff1, stuff2));

What happens here?

  1. Starting on line 1 var stuff1 = ...
  2. We send request to sql server that we want to get some stuff1 for userId
  3. We wait (current thread is blocked)
  4. We wait (current thread is blocked)
  5. .....
  6. Sql server send to us response
  7. We move to line 2 var stuff2 = ...
  8. We send request to sql server that we want to get some stuff2 for userId
  9. We wait (current thread is blocked)
  10. And again
  11. .....
  12. Sql server send to us response
  13. We render view

So let's look to an async version of it:

var stuff1Task = repo.GetStuff1ForUserAsync(userId);
var stuff2Task = repo.GetStuff2ForUserAsync(userId);
await Task.WhenAll(stuff1Task, stuff2Task);
return View(new Model(stuff1Task.Result, stuff2Task.Result));

What happens here?

  1. We send request to sql server to get stuff1 (line 1)
  2. We send request to sql server to get stuff2 (line 2)
  3. We wait for responses from sql server, but current thread isn't blocked, he can handle queries from another users
  4. We render view

Right way to do it

So good code here:

using System.Data.Entity;

public IQueryable<URL> GetAllUrls()
{
   return context.Urls.AsQueryable();
}

public async Task<List<URL>> GetAllUrlsByUser(int userId) {
   return await GetAllUrls().Where(u => u.User.Id == userId).ToListAsync();
}

Note, than you must add using System.Data.Entity in order to use method ToListAsync() for IQueryable.

Note, that if you don't need filtering and paging and stuff, you don't need to work with IQueryable. You can just use await context.Urls.ToListAsync() and work with materialized List<Url>.

android get all contacts

Try this too,

private void getContactList() {
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

    if ((cur != null ? cur.getCount() : 0) > 0) {
        while (cur != null && cur.moveToNext()) {
            String id = cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(
                    ContactsContract.Contacts.DISPLAY_NAME));

            if (cur.getInt(cur.getColumnIndex(
                    ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phoneNo = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.i(TAG, "Name: " + name);
                    Log.i(TAG, "Phone Number: " + phoneNo);
                }
                pCur.close();
            }
        }
    }
    if(cur!=null){
        cur.close();
    }
}

If you need more reference means refer this link Read ContactList

How do I set specific environment variables when debugging in Visual Studio?

Set up a batch file which you can invoke. Pass the path the batch file, and have the batch file set the environment variable and then invoke NUnit.

Align two divs horizontally side by side center to the page using bootstrap css

<div class="container">
    <div class="row">
       <div class="col-xs-6 col-sm-6 col-md-6">
          First Div
       </div>
       <div class="col-xs-6 col-sm-6 col-md-6">
          Second Div
       </div>
   </div>

This does the trick.

How to validate a form with multiple checkboxes to have atleast one checked

if (
  document.forms["form"]["mon"].checked==false &&
  document.forms["form"]["tues"].checked==false &&
  document.forms["form"]["wed"].checked==false &&
  document.forms["form"]["thrs"].checked==false &&
  document.forms["form"]["fri"].checked==false
) {
  alert("Select at least One Day into Five Days");
  return false; 
}

How to find the length of a string in R

Use stringi package and stri_length function

> stri_length(c("ala ma kota","ABC",NA))
[1] 11  3 NA

Why? Because it is the FASTEST among presented solutions :)

require(microbenchmark)
require(stringi)
require(stringr)
x <- c(letters,NA,paste(sample(letters,2000,TRUE),collapse=" "))
microbenchmark(nchar(x),str_length(x),stri_length(x))
Unit: microseconds
           expr    min     lq  median      uq     max neval
       nchar(x) 11.868 12.776 13.1590 13.6475  41.815   100
  str_length(x) 30.715 33.159 33.6825 34.1360 173.400   100
 stri_length(x)  2.653  3.281  4.0495  4.5380  19.966   100

and also works fine with NA's

nchar(NA)
## [1] 2
stri_length(NA)
## [1] NA

NameError: name 'self' is not defined

If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.

def foo():
    print(self.bar)

>NameError: name 'self' is not defined

def foo(self):
    print(self.bar)

How to get size of mysql database?

It can be determined by using following MySQL command

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.TABLES GROUP BY table_schema

Result

Database    Size (MB)
db1         11.75678253
db2         9.53125000
test        50.78547382

Get result in GB

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 / 1024 AS "Size (GB)" FROM information_schema.TABLES GROUP BY table_schema

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

I haven't read a lot into the other examples, but I have just created this method for consolidating multiple consecutive space characters.

It does not use any libraries, and whilst it is relatively long in terms of script length, it is not a complex implementation:

def spaceMatcher(command):
    """
    Function defined to consolidate multiple whitespace characters in
    strings to a single space
    """
    # Initiate index to flag if more than one consecutive character
    iteration
    space_match = 0
    space_char = ""
    for char in command:
      if char == " ":
          space_match += 1
          space_char += " "
      elif (char != " ") & (space_match > 1):
          new_command = command.replace(space_char, " ")
          space_match = 0
          space_char = ""
      elif char != " ":
          space_match = 0
          space_char = ""
   return new_command

command = None
command = str(input("Please enter a command ->"))
print(spaceMatcher(command))
print(list(spaceMatcher(command)))

Assign command output to variable in batch file

A method has already been devised, however this way you don't need a temp file.

for /f "delims=" %%i in ('command') do set output=%%i

However, I'm sure this has its own exceptions and limitations.

Visual Studio: Relative Assembly References Paths

Probably, the easiest way to achieve this is to simply add the reference to the assembly and then (manually) patch the textual representation of the reference in the corresponding Visual Studio project file (extension .csproj) such that it becomes relative.

I've done this plenty of times in VS 2005 without any problems.

Convert NVARCHAR to DATETIME in SQL Server 2008

As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)

|                     YOUR_DT |             SQL2008 |
|-----------------------------|---------------------|
|         2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
|    2013-08-29 13:55:48 blah |              (null) |
| 2013-08-29 13:55:48 rubbish |              (null) |

SELECT
  [Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
                        THEN convert(datetime,[Your_Dt])
                        ELSE NULL
                     END
            ) AS ca1 (dt_converted)
;

Notes:

You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'

For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison

declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'

select
  FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008

|             SQL2012 |             SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 | 

A warning - comparison between signed and unsigned integer expressions

The primary issue is that underlying hardware, the CPU, only has instructions to compare two signed values or compare two unsigned values. If you pass the unsigned comparison instruction a signed, negative value, it will treat it as a large positive number. So, -1, the bit pattern with all bits on (twos complement), becomes the maximum unsigned value for the same number of bits.

8-bits: -1 signed is the same bits as 255 unsigned 16-bits: -1 signed is the same bits as 65535 unsigned etc.

So, if you have the following code:

int fd;
fd = open( .... );

int cnt;
SomeType buf;

cnt = read( fd, &buf, sizeof(buf) );

if( cnt < sizeof(buf) ) {
    perror("read error");
}

you will find that if the read(2) call fails due to the file descriptor becoming invalid (or some other error), that cnt will be set to -1. When comparing to sizeof(buf), an unsigned value, the if() statement will be false because 0xffffffff is not less than sizeof() some (reasonable, not concocted to be max size) data structure.

Thus, you have to write the above if, to remove the signed/unsigned warning as:

if( cnt < 0 || (size_t)cnt < sizeof(buf) ) {
    perror("read error");
}

This just speaks loudly to the problems.

1.  Introduction of size_t and other datatypes was crafted to mostly work, 
    not engineered, with language changes, to be explicitly robust and 
    fool proof.
2.  Overall, C/C++ data types should just be signed, as Java correctly
    implemented.

If you have values so large that you can't find a signed value type that works, you are using too small of a processor or too large of a magnitude of values in your language of choice. If, like with money, every digit counts, there are systems to use in most languages which provide you infinite digits of precision. C/C++ just doesn't do this well, and you have to be very explicit about everything around types as mentioned in many of the other answers here.

Test if remote TCP port is open from a shell script

With netcat you can check whether a port is open like this:

nc my.example.com 80 < /dev/null

The return value of nc will be success if the TCP port was opened, and failure (typically the return code 1) if it could not make the TCP connection.

Some versions of nc will hang when you try this, because they do not close the sending half of their socket even after receiving the end-of-file from /dev/null. On my own Ubuntu laptop (18.04), the netcat-openbsd version of netcat that I have installed offers a workaround: the -N option is necessary to get an immediate result:

nc -N my.example.com 80 < /dev/null

Using Gradle to build a jar with dependencies

This works fine for me.

My Main class:

package com.curso.online.gradle;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class Main {

    public static void main(String[] args) {
        Logger logger = Logger.getLogger(Main.class);
        logger.debug("Starting demo");

        String s = "Some Value";

        if (!StringUtils.isEmpty(s)) {
            System.out.println("Welcome ");
        }

        logger.debug("End of demo");
    }

}

And it is the content of my file build.gradle:

apply plugin: 'java'

apply plugin: 'eclipse'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
    compile  'org.apache.commons:commons-lang3:3.0'
    compile  'log4j:log4j:1.2.16'
}

task fatJar(type: Jar) {
    manifest {
        attributes 'Main-Class': 'com.curso.online.gradle.Main'
    }
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

And I write the following in my console:

java -jar ProyectoEclipseTest-all.jar

And the output is great:

log4j:WARN No appenders could be found for logger (com.curso.online.gradle.Main)
.
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more in
fo.
Welcome

How to parse a JSON Input stream

Kotlin version with Gson

to read the response JSON:

val response = BufferedReader(
                   InputStreamReader(conn.inputStream, "UTF-8")
               ).use { it.readText() }

to parse response we can use Gson:

val model = Gson().fromJson(response, YourModelClass::class.java)

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

Serializing list to JSON

Yes, but then what do you do about the django objects? simple json tends to choke on them.

If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

seralized_dict = simplejson.dumps(my_dict, 
                     default=lambda a: "[%s,%s]" % (str(type(a)), a.pk)
                     )

to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.

Table overflowing outside of div

There's a width="400" on the table, remove it and it will work...

How to specify "does not contain" in dplyr filter

Note that %in% returns a logical vector of TRUE and FALSE. To negate it, you can use ! in front of the logical statement:

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
 !where_case_travelled_1 %in% 
   c('Outside Canada','Outside province/territory of residence but within Canada'))

Regarding your original approach with -c(...), - is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -.

How to write files to assets folder or raw folder in android?

You cannot write data's to asset/Raw folder, since it is packed(.apk) and not expandable in size.

If your application need to download dependency files from server, you can go for APK Expansion Files provided by android (http://developer.android.com/guide/market/expansion-files.html).

How to clear cache in Yarn?

Ok I found out the answer myself. Much like npm cache clean, Yarn also has its own

yarn cache clean

using setTimeout on promise chain

The shorter ES6 version of the answer:

const delay = t => new Promise(resolve => setTimeout(resolve, t));

And then you can do:

delay(3000).then(() => console.log('Hello'));

How to check the function's return value if true or false

Wrong syntax. You can't compare a Boolean to a string like "false" or "true". In your case, just test it's inverse:

if(!ValidateForm()) { ...

You could test against the constant false, but it's rather ugly and generally frowned upon:

if(ValidateForm() == false) { ...

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

Inserting a Python datetime.datetime object into MySQL

You are most likely getting the TypeError because you need quotes around the datecolumn value.

Try:

now = datetime.datetime(2009, 5, 5)

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
               ("name", 4, now))

With regards to the format, I had success with the above command (which includes the milliseconds) and with:

now.strftime('%Y-%m-%d %H:%M:%S')

Hope this helps.

How to return an array from an AJAX call?

well, I know that I'm a bit too late, but I tried all of your solutions and with no success! So here is how I managed to do it. First of all, I'm working on an Asp.Net MVC project. The Only thing I changed was in my c# method getInvitation:

public ActionResult getInvitation (Guid s_ID)
{
    using (var db = new cRM_Verband_BWEntities())
    {
        var listSidsMit = (from data in db.TERMINEINLADUNGEN where data.RECID_KOMMUNIKATIONEN == s_ID select data.RECID_MITARBEITER.ToString()).ToArray();
        return Json(listSidsMit);
    }
}

SuccessFunction in JS :

function successFunction(result) {
    console.log(result);
}

I changed the Method Type from string[] to ActionResult and of course at the end I wrapped my array listSidsMit with the Json method.

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

Setting up a cron job in Windows

  1. Make sure you logged on as an administrator or you have the same access as an administrator.
  2. Start->Control Panel->System and Security->Administrative Tools->Task Scheduler
  3. Action->Create Basic Task->Type a name and Click Next
  4. Follow through the wizard.

onchange event for input type="number"

$("input[type='number']").bind("focus", function() {
    var value = $(this).val();
    $(this).bind("blur", function() {
        if(value != $(this).val()) {
            alert("Value changed");
        }
        $(this).unbind("blur");
    });
});

OR

$("input[type='number']").bind("input", function() {
    alert("Value changed");
});

Locating child nodes of WebElements in selenium

For Finding All the ChildNodes you can use the below Snippet

List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));

        for (WebElement e  : childs)
        {
            System.out.println(e.getTagName());
        }

Note that this will give all the Child Nodes at same level -> Like if you have structure like this :

<Html> 
<body> 
 <div> ---suppose this is current WebElement 
   <a>
   <a>
      <img>
          <a>
      <img>
   <a>

It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with MyCurrentWebElement.findElements(By.xpath(".//*"));

Hope That Helps !!

Read Session Id using Javascript

Here's a short and sweet JavaScript function to fetch the session ID:

function session_id() {
    return /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
}

Or if you prefer a variable, here's a simple one-liner:

var session_id = /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;

Should match the session ID cookie for PHP, JSP, .NET, and I suppose various other server-side processors as well.

Center a position:fixed element

The only foolproof solution is to use table align=center as in:

<table align=center><tr><td>
<div>
...
</div>
</td></tr></table>

I cannot believe people all over the world wasting these copious amount to silly time to solve such a fundamental problem as centering a div. css solution does not work for all browsers, jquery solution is a software computational solution and is not an option for other reasons.

I have wasted too much time repeatedly to avoid using table, but experience tell me to stop fighting it. Use table for centering div. Works all the time in all browsers! Never worry any more.

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

If you just need to get a few items from the JSON object, I would use Json.NET's LINQ to JSON JObject class. For example:

JToken token = JObject.Parse(stringFullOfJson);

int page = (int)token.SelectToken("page");
int totalPages = (int)token.SelectToken("total_pages");

I like this approach because you don't need to fully deserialize the JSON object. This comes in handy with APIs that can sometimes surprise you with missing object properties, like Twitter.

Documentation: Serializing and Deserializing JSON with Json.NET and LINQ to JSON with Json.NET

Debug JavaScript in Eclipse

Use the debugging tools supported by the browser. As mentioned above Firebug for Firefox Chrome Developer Tools from Chrome IE Developer for IE.

That way you can detect cross-browser issues. To help reduce the cross-browser issues, use a javascript framework ie jQuery, YUI, moo tools, etc.

Below is a screenshot (javascript-debug.png) of what it looks lime in Firebug.
1) hit 'F12'
2) click the 'Script' tab and 'enable it' (if you are already on your page - hit 'F5' to re-load)
3) next to the 'All' drop down, there will be another dropdown to the right. Select your javascript file from that dropdown.
In the screenshot, I've set a break-point at line 42 by 'left-mouse-click'. This will enable you to break, inspect, watch, etc.

enter image description here

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

In my case, upgraded from spring-securiy-web 3.1.3 to 4.2.12, the defaultHttpFirewall was changed from DefaultHttpFirewall to StrictHttpFirewall by default. So just define it in XML configuration like below:

<bean id="defaultHttpFirewall" class="org.springframework.security.web.firewall.DefaultHttpFirewall"/>
<sec:http-firewall ref="defaultHttpFirewall"/>

set HTTPFirewall as DefaultHttpFirewall

How can I set the color of a selected row in DataGrid

I spent the better part of a day fiddling with this problem. Turned out the RowBackground Property on the DataGrid - which I had set - was overriding all attempts to change it in . As soon as I deleted it, everything worked. (Same goes for Foreground set in DataGridTextColumn, by the way).

How can I get a list of users from active directory?

PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.

Filters and syntax here: https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx

Attributes here: https://docs.microsoft.com/en-us/windows/win32/adschema/attributes-all

using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
    using (var searcher = new DirectorySearcher(root))
    {
        // looking for a specific user
        searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
        // I only care about what groups the user is a memberOf
        searcher.PropertiesToLoad.Add("memberOf");

        // FYI, non-null results means the user was found
        var results = searcher.FindOne();

        var properties = results?.Properties;
        if (properties?.Contains("memberOf") == true)
        {
            // ... iterate over all the groups the user is a member of
        }
    }
}

Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.

For authenticating the user:

using (var context = new PrincipalContext(ContextType.Domain))
{
    return context.ValidateCredentials(username, password);
}

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

How to capture Enter key press?

Try this....

HTML inline

onKeydown="Javascript: if (event.keyCode==13) fnsearch();"
or
onkeypress="Javascript: if (event.keyCode==13) fnsearch();"

JavaScript

<script>
function fnsearch()
{
   alert('you press enter');
}
</script>

Multiple left-hand assignment with JavaScript

coffee-script can accomplish this with aplomb..

for x in [ 'a', 'b', 'c' ] then "#{x}" : true

[ { a: true }, { b: true }, { c: true } ]

How do I find the maximum of 2 numbers?

You can use max(value, run)

The function max takes any number of arguments, or (alternatively) an iterable, and returns the maximum value.

Hide a EditText & make it visible by clicking a menu

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.waist2height); {
        final EditText edit = (EditText)findViewById(R.id.editText);          
        final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
        final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);                       
        if(rb1.isChecked()){    
            edit.setVisibility(View.VISIBLE);              
        }
        else if(rb2.isChecked()){               
            edit.setVisibility(View.INVISIBLE);
        }
}

AngularJS ng-style with a conditional expression

@jfredsilva obviously has the simplest answer for the question:

ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

However, you might really want to consider my answer for something more complex.

Ternary-like example:

<p ng-style="{width: {true:'100%',false:'0%'}[myObject.value == 'ok']}"></p>

Something more complex:

<p ng-style="{
   color:       {blueish: 'blue', greenish: 'green'}[ color ], 
  'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]
}">Test</p>

If $scope.color == 'blueish', the color will be 'blue'.

If $scope.zoom == 2, the font-size will be 26px.

_x000D_
_x000D_
angular.module('app',[]);_x000D_
function MyCtrl($scope) {_x000D_
  $scope.color = 'blueish';_x000D_
  $scope.zoom = 2;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="MyCtrl" ng-style="{_x000D_
   color:       {blueish: 'blue', greenish: 'green'}[ color ], _x000D_
  'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]_x000D_
}">_x000D_
  color = {{color}}<br>_x000D_
  zoom = {{zoom}}_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get checkbox list values with jQuery

Not tested but should work:

$("#MyDiv td input:checked").each(function()
{
    alert($(this).attr("id"));
});

How to get current class name including package name in Java?

Use this.getClass().getCanonicalName() to get the full class name.

Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.

Reversing a linked list in Java, recursively

public static ListNode recRev(ListNode curr){

    if(curr.next == null){
        return curr;
    }
    ListNode head = recRev(curr.next);
    curr.next.next = curr;
    curr.next = null;

    // propogate the head value
    return head;

}

Make the image go behind the text and keep it in center using CSS

Well, put your image in the background of your website/container and put whatever you want on top of that.

Your container defined in HTML:

<div id="container">
   <input name="box" type="textbox" />
   <input name="box" type="textbox" />
   <input name="submit" type="submit" />
</div>

Your CSS would look like this:

#container {
    background-image:url(yourimage.jpg);
    background-position:center;
    width:700px;
    height:400px;
}

For this to work though, you must have height and width specified to certain values (i.e. no percentages). I could help you more specifically if you wanted, but I'd need more info.

What are the main performance differences between varchar and nvarchar SQL Server data types?

Since your application is small, there is essentially no appreciable cost increase to using nvarchar over varchar, and you save yourself potential headaches down the road if you have a need to store unicode data.

SELECT using 'CASE' in SQL

This is just the syntax of the case statement, it looks like this.

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    WHEN FRUIT = 'B' THEN 'BANANA'     
  END AS FRUIT
FROM FRUIT_TABLE;

As a reminder remember; no assignment is performed the value becomes the column contents. (If you wanted to assign that to a variable you would put it before the CASE statement).

Angular/RxJs When should I unsubscribe from `Subscription`

The Subscription class has an interesting feature:

Represents a disposable resource, such as the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes the resource held by the subscription.
Additionally, subscriptions may be grouped together through the add() method, which will attach a child Subscription to the current Subscription. When a Subscription is unsubscribed, all its children (and its grandchildren) will be unsubscribed as well.

You can create an aggregate Subscription object that groups all your subscriptions. You do this by creating an empty Subscription and adding subscriptions to it using its add() method. When your component is destroyed, you only need to unsubscribe the aggregate subscription.

@Component({ ... })
export class SmartComponent implements OnInit, OnDestroy {
  private subscriptions = new Subscription();

  constructor(private heroService: HeroService) {
  }

  ngOnInit() {
    this.subscriptions.add(this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes));
    this.subscriptions.add(/* another subscription */);
    this.subscriptions.add(/* and another subscription */);
    this.subscriptions.add(/* and so on */);
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }
}

How do I put hint in a asp:textbox

asp:TextBox ID="txtName" placeholder="any text here"

align 3 images in same row with equal spaces?

HTML:

<div class="container">
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
</div>

CSS:

.container{ width:50%; margin:0 auto; text-align:center}
.container span{ width:30%; margin:0 1%;  }

I haven't tested this, but hope this will work.

You can add 'display:inline-block' to .container span to make the span to have fixed 30% width

SELECT * WHERE NOT EXISTS

SELECT * FROM employees WHERE name NOT IN (SELECT name FROM eotm_dyn)

OR

SELECT * FROM employees WHERE NOT EXISTS (SELECT * FROM eotm_dyn WHERE eotm_dyn.name = employees.name)

OR

SELECT * FROM employees LEFT OUTER JOIN eotm_dyn ON eotm_dyn.name = employees.name WHERE eotm_dyn IS NULL

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

Json.NET serialize object with root name

You can easily create your own serializer

var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);

string Serialize<T>(T o)
{
    var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;

    var jv = JValue.FromObject(o);

    return new JObject(new JProperty(attr.Title, jv)).ToString();
}

Fastest way to determine if record exists

For MySql you can use LIMIT like below (Example shows in PHP)

  $sql = "SELECT column_name FROM table_name WHERE column_name = 'your_value' LIMIT 1";
  $result = $conn->query($sql);
  if ($result -> num_rows > 0) {
      echo "Value exists" ;
  } else {
      echo "Value not found";
  }

How to find the Vagrant IP?

I find that I do need the IP in order to configure /etc/hosts on the host system to point at services on the fresh VM.

Here's a rough version of what I use to fetch the IP. Let Vagrant do its SSH magic and ask the VM for its address; tweak for your needs.

new_ip=$(vagrant ssh -c "ip address show eth0 | grep 'inet ' | sed -e 's/^.*inet //' -e 's/\/.*$//'")

I just found this in the Vagrant Docs. Looks like they consider it a valid approach:

This will automatically assign an IP address from the reserved address space. The IP address can be determined by using vagrant ssh to SSH into the machine and using the appropriate command line tool to find the IP, such as ifconfig.

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:

this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

Sending E-mail using C#

You can use Mailkit. MailKit is an Open Source cross-platform .NET mail-client library that is based on MimeKit and optimized for mobile devices.

It has more and advance features better than System.Net.Mail

  • A fully-cancellable Pop3Client with support for STLS, UIDL, APOP, PIPELINING, UTF8, and LANG. Client-side sorting and threading of messages (the Ordinal Subject and the Jamie Zawinski threading algorithms are supported).
  • Asynchronous versions of all methods that hit the network.
  • S/MIME, OpenPGP and DKIM signature support via MimeKit.
  • Microsoft TNEF support via MimeKit.

See this example you can send mail

            MimeMessage mailMessage = new MimeMessage();
            mailMessage.From.Add(new MailboxAddress(senderName, [email protected]));
            mailMessage.Sender = new MailboxAddress(senderName, [email protected]);
            mailMessage.To.Add(new MailboxAddress(emailid, emailid));
            mailMessage.Subject = subject;
            mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
            mailMessage.Subject = subject;
            var builder = new BodyBuilder();
            builder.TextBody = "Hello There";            
            try
            {
                using (var smtpClient = new SmtpClient())
                {
                    smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
                    smtpClient.Authenticate("[email protected]", "password");

                    smtpClient.Send(mailMessage);
                    Console.WriteLine("Success");
                }
            }
            catch (SmtpCommandException ex)
            {
                Console.WriteLine(ex.ToString());              
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());                
            }

You can download from here.

How to set shadows in React Native for android?

Also i'd like to add that if one's trying to apply shadow in a TouchableHighlight Component in which child has borderRadius, the parent element (TouchableHighlight) also need the radius set in order to elevation prop work on Android.

Using $_POST to get select option value from HTML

You can do it like this, too:

<?php
if(isset($_POST['select1'])){
    $select1 = $_POST['select1'];
    switch ($select1) {
        case 'value1':
            echo 'this is value1<br/>';
            break;
        case 'value2':
            echo 'value2<br/>';
            break;
        default:
            # code...
            break;
    }
}
?>


<form action="" method="post">
    <select name="select1">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
    <input type="submit" name="submit" value="Go"/>
</form>

How to correctly get image from 'Resources' folder in NetBeans

For me it worked like I had images in icons folder under src and I wrote below code.

new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

Check if an apt-get package is installed and then install it if it's not on Linux

This explicitly prints 0 if installed else 1 using only awk:

dpkg-query -W -f '${Status}\n' 'PKG' 2>&1|awk '/ok installed/{print 0;exit}{print 1}'

or if you prefer the other way around where 1 means installed and 0 otherwise:

dpkg-query -W -f '${Status}\n' 'PKG' 2>&1|awk '/ok installed/{print 1;exit}{print 0}'

** replace PKG with your package name

Convenience function:

installed() {
    return $(dpkg-query -W -f '${Status}\n' "${1}" 2>&1|awk '/ok installed/{print 0;exit}{print 1}')
}


# usage:
installed gcc && echo Yes || echo No

#or

if installed gcc; then
    echo yes
else
    echo no
fi

How to set transparent background for Image Button in code?

This should work - imageButton.setBackgroundColor(android.R.color.transparent);

Using a list as a data source for DataGridView

this Func may help you . it add every list object to grid view

private void show_data()
        {
            BindingSource Source = new BindingSource();

            for (int i = 0; i < CC.Contects.Count; i++)
            {
                Source.Add(CC.Contects.ElementAt(i));
            };


            Data_View.DataSource = Source;

        }

I write this for simple database app

How to find out the server IP address (using JavaScript) that the browser is connected to?

Can do this thru a plug-in like Java applet or Flash, then have the Javascript call a function in the applet or vice versa (OR have the JS call a function in Flash or other plugin ) and return the IP. This might not be the IP used by the browser for getting the page contents. Also if there are images, css, js -> browser could have made multiple connections. I think most browsers only use the first IP they get from the DNS call (that connected successfully, not sure what happens if one node goes down after few resources are got and still to get others - timers/ ajax that add html that refer to other resources).

If java applet would have to be signed, make a connection to the window.location (got from javascript, in case applet is generic and can be used on any page on any server) else just back to home server and use java.net.Address to get IP.

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

I ran into this problem and try using the flag -noverify which really works. It is because of the new bytecode verifier. So the flag should really work. I am using JDK 1.7.

Note: This would not work if you are using JDK 1.8

Counting the number of non-NaN elements in a numpy ndarray in Python

An alternative, but a bit slower alternative is to do it over indexing.

np.isnan(data)[np.isnan(data) == False].size

In [30]: %timeit np.isnan(data)[np.isnan(data) == False].size
1 loops, best of 3: 498 ms per loop 

The double use of np.isnan(data) and the == operator might be a bit overkill and so I posted the answer only for completeness.

How to install a specific version of a ruby gem?

Use the --version parameter (shortcut -v):

$ gem install rails -v 0.14.1

You can also use version comparators like >= or ~>

$ gem install rails -v '~> 0.14.0'

Or with newer versions of gem even:

$ gem install rails:0.14.4 rubyzip:'< 1'
…
Successfully installed rails-0.14.4
Successfully installed rubyzip-0.9.9

How to install pip for Python 3.6 on Ubuntu 16.10?

Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.

If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:

sudo add-apt-repository ppa:jonathonf/python-3.6  # (only for 16.04 LTS)

Then, run the following (this works out-of-the-box on 16.10 and 17.04):

sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3

# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python

When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1 (or a more recent version of Python 3.6):

python --version   # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version

jQuery DataTables Getting selected row values

var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});

console.log(a[0]);

Distinct pair of values SQL

If you want to want to treat 1,2 and 2,1 as the same pair, then this will give you the unique list on MS-SQL:

SELECT DISTINCT 
    CASE WHEN a > b THEN a ELSE b END as a,
    CASE WHEN a > b THEN b ELSE a END as b
FROM pairs

Inspired by @meszias answer above

How do I combine 2 javascript variables into a string

You can use the JavaScript String concat() Method,

var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"

Its syntax is:

string.concat(string1, string2, ..., stringX)

All combinations of a list of lists

from itertools import product 
list_vals = [['Brand Acronym:CBIQ', 'Brand Acronym :KMEFIC'],['Brand Country:DXB','Brand Country:BH']]
list(product(*list_vals))

Output:

[('Brand Acronym:CBIQ', 'Brand Country :DXB'),
('Brand Acronym:CBIQ', 'Brand Country:BH'),
('Brand Acronym :KMEFIC', 'Brand Country :DXB'),
('Brand Acronym :KMEFIC', 'Brand Country:BH')]

Select datatype of the field in postgres

You can get data types from the information_schema (8.4 docs referenced here, but this is not a new feature):

=# select column_name, data_type from information_schema.columns
-# where table_name = 'config';
    column_name     | data_type 
--------------------+-----------
 id                 | integer
 default_printer_id | integer
 master_host_enable | boolean
(3 rows)

Tomcat request timeout

If you are trying to prevent a request from running too long, then setting a timeout in Tomcat will not help you. As Chris says, you can set the global timeout value for Tomcat. But, from The Apache Tomcat Connector - Generic HowTo Timeouts, see the Reply Timeout section:

JK can also use a timeout on request replies. This timeout does not measure the full processing time of the response. Instead it controls, how much time between consecutive response packets is allowed.

In most cases, this is what one actually wants. Consider for example long running downloads. You would not be able to set an effective global reply timeout, because downloads could last for many minutes. Most applications though have limited processing time before starting to return the response. For those applications you could set an explicit reply timeout. Applications that do not harmonise with reply timeouts are batch type applications, data warehouse and reporting applications which are expected to observe long processing times.

If JK aborts waiting for a response, because a reply timeout fired, there is no way to stop processing on the backend. Although you free processing resources in your web server, the request will continue to run on the backend - without any way to send back a result once the reply timeout fired.

So Tomcat will detect that the servlet has not responded within the timeout and will send back a response to the user, but will not stop the thread running. I don't think you can achieve what you want to do.

How to find a string inside a entire database?

This will work:

DECLARE @MyValue NVarChar(4000) = 'something';

SELECT S.name SchemaName, T.name TableName
INTO #T
FROM sys.schemas S INNER JOIN
     sys.tables T ON S.schema_id = T.schema_id;

WHILE (EXISTS (SELECT * FROM #T)) BEGIN
  DECLARE @SQL NVarChar(4000) = 'SELECT * FROM $$TableName WHERE (0 = 1) ';
  DECLARE @TableName NVarChar(1000) = (
    SELECT TOP 1 SchemaName + '.' + TableName FROM #T
  );
  SELECT @SQL = REPLACE(@SQL, '$$TableName', @TableName);

  DECLARE @Cols NVarChar(4000) = '';

  SELECT
    @Cols = COALESCE(@Cols + 'OR CONVERT(NVarChar(4000), ', '') + C.name + ') = CONVERT(NVarChar(4000), ''$$MyValue'') '
  FROM sys.columns C
  WHERE C.object_id = OBJECT_ID(@TableName);

  SELECT @Cols = REPLACE(@Cols, '$$MyValue', @MyValue);
  SELECT @SQL = @SQL + @Cols;

  EXECUTE(@SQL);

  DELETE FROM #T
  WHERE SchemaName + '.' + TableName = @TableName;
END;

DROP TABLE #T;

A couple caveats, though. First, this is outrageously slow and non-optimized. All values are being converted to nvarchar simply so that they can be compared without error. You may run into problems with values like datetime not converting as expected and therefore not being matched when they should be (false negatives).

The WHERE (0 = 1) is there to make building the OR clause easier. If there are not matches you won't get any rows back.

CreateProcess error=2, The system cannot find the file specified

Assuming that winrar.exe is in the PATH, then Runtime.exec is capable of finding it, if it is not, you will need to supply the fully qualified path to it, for example, assuming winrar.exe is installed in C:/Program Files/WinRAR you would need to use something like...

p=r.exec("C:/Program Files/WinRAR/winrar x h:\\myjar.jar *.* h:\\new");

Personally, I would recommend that you use ProcessBuilder as it has some additional configuration abilities amongst other things. Where possible, you should also separate your command and parameters into separate String elements, it deals with things like spaces much better then a single String variable, for example...

ProcessBuilder pb = new ProcessBuilder(
    "C:/Program Files/WinRAR/winrar",
    "x",
    "myjar.jar",
    "*.*",
    "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

Don't forget to read the contents of the InputStream from the process, as failing to do so may stall the process

Does bootstrap 4 have a built in horizontal divider?

For dropdowns, yes:

https://v4-alpha.getbootstrap.com/components/dropdowns/

<div class="dropdown-menu">
  <a class="dropdown-item" href="#">Action</a>
  <a class="dropdown-item" href="#">Another action</a>
  <a class="dropdown-item" href="#">Something else here</a>
  <div class="dropdown-divider"></div>
  <a class="dropdown-item" href="#">Separated link</a>
</div>

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

How do I restrict an input to only accept numbers?

you may also want to remove the 0 at the beginning of the input... I simply add an if block to Mordred answer above because I cannot make a comment yet...

  app.directive('numericOnly', function() {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, modelCtrl) {

          modelCtrl.$parsers.push(function (inputValue) {
              var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;

              if (transformedInput!=inputValue) {
                  modelCtrl.$setViewValue(transformedInput);
                  modelCtrl.$render();
              }
              //clear beginning 0
              if(transformedInput == 0){
                modelCtrl.$setViewValue(null);
                modelCtrl.$render();
              }
              return transformedInput;
          });
      }
    };
  })

When should an IllegalArgumentException be thrown?

As specified in oracle official tutorial , it states that:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

If I have an Application interacting with database using JDBC , And I have a method that takes the argument as the int item and double price. The price for corresponding item is read from database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG in your database. So , and IllegalArguementException() should be thrown in this case which would state that the price can't be negative.
I hope that I have expressed my point clearly..

How to add an image to an svg container using D3.js

My team also wanted to add images inside d3-drawn circles, and came up with the following (fiddle):

index.html:

<!doctype html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="timeline.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
  <script src="https://code.jquery.com/jquery-2.2.4.js"
    integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
    crossorigin="anonymous"></script>
  <script src="./timeline.js"></script>
</head>
  <body>
    <div class="timeline"></div>
  </body>
</html>

timeline.css:

.axis path,
.axis line,
.tick line,
.line {
  fill: none;
  stroke: #000000;
  stroke-width: 1px;
}

timeline.js:

// container target
var elem = ".timeline";

var props = {
  width: 1000,
  height: 600,
  class: "timeline-point",

  // margins
  marginTop: 100,
  marginRight: 40,
  marginBottom: 100,
  marginLeft: 60,

  // data inputs
  data: [
    {
      x: 10,
      y: 20,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "a"
    },
    {
      x: 20,
      y: 10,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "b"
    },
    {
      x: 60,
      y: 30,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "c"
    },
    {
      x: 40,
      y: 30,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "d"
    },
    {
      x: 50,
      y: 70,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "e"
    },
    {
      x: 30,
      y: 50,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "f"
    },
    {
      x: 50,
      y: 60,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "g"
    }
  ],

  // y label
  yLabel: "Y label",
  yLabelLength: 50,

  // axis ticks
  xTicks: 10,
  yTicks: 10

}

// component start
var Timeline = {};

/***
*
* Create the svg canvas on which the chart will be rendered
*
***/

Timeline.create = function(elem, props) {

  // build the chart foundation
  var svg = d3.select(elem).append('svg')
      .attr('width', props.width)
      .attr('height', props.height);

  var g = svg.append('g')
      .attr('class', 'point-container')
      .attr("transform",
              "translate(" + props.marginLeft + "," + props.marginTop + ")");

  var g = svg.append('g')
      .attr('class', 'line-container')
      .attr("transform", 
              "translate(" + props.marginLeft + "," + props.marginTop + ")");

  var xAxis = g.append('g')
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (props.height - props.marginTop - props.marginBottom) + ")");

  var yAxis = g.append('g')
    .attr("class", "y axis");

  svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 1)
    .attr("x", 0 - ((props.height - props.yLabelLength)/2) )
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text(props.yLabel);

  // add placeholders for the axes
  this.update(elem, props);
};

/***
*
* Update the svg scales and lines given new data
*
***/

Timeline.update = function(elem, props) {
  var self = this;
  var domain = self.getDomain(props);
  var scales = self.scales(elem, props, domain);

  self.drawPoints(elem, props, scales);
};


/***
*
* Use the range of values in the x,y attributes
* of the incoming data to identify the plot domain
*
***/

Timeline.getDomain = function(props) {
  var domain = {};
  domain.x = props.xDomain || d3.extent(props.data, function(d) { return d.x; });
  domain.y = props.yDomain || d3.extent(props.data, function(d) { return d.y; });
  return domain;
};


/***
*
* Compute the chart scales
*
***/

Timeline.scales = function(elem, props, domain) {

  if (!domain) {
    return null;
  }

  var width = props.width - props.marginRight - props.marginLeft;
  var height = props.height - props.marginTop - props.marginBottom;

  var x = d3.scale.linear()
    .range([0, width])
    .domain(domain.x);

  var y = d3.scale.linear()
    .range([height, 0])
    .domain(domain.y);

  return {x: x, y: y};
};


/***
*
* Create the chart axes
*
***/

Timeline.axes = function(props, scales) {

  var xAxis = d3.svg.axis()
    .scale(scales.x)
    .orient("bottom")
    .ticks(props.xTicks)
    .tickFormat(d3.format("d"));

  var yAxis = d3.svg.axis()
    .scale(scales.y)
    .orient("left")
    .ticks(props.yTicks);

  return {
    xAxis: xAxis,
    yAxis: yAxis
  }
};


/***
*
* Use the general update pattern to draw the points
*
***/

Timeline.drawPoints = function(elem, props, scales, prevScales, dispatcher) {
  var g = d3.select(elem).selectAll('.point-container');
  var color = d3.scale.category10();

  // add images
  var image = g.selectAll('.image')
    .data(props.data)

  image.enter()
    .append("pattern")
    .attr("id", function(d) {return d.id})
    .attr("class", "svg-image")
    .attr("x", "0")
    .attr("y", "0")
    .attr("height", "70px")
    .attr("width", "70px")
    .append("image")
      .attr("x", "0")
      .attr("y", "0")
      .attr("height", "70px")
      .attr("width", "70px")
      .attr("xlink:href", function(d) {return d.image})

  var point = g.selectAll('.point')
    .data(props.data);

  // enter
  point.enter()
    .append("circle")
      .attr("class", "point")
      .on('mouseover', function(d) {
        d3.select(elem).selectAll(".point").classed("active", false);
        d3.select(this).classed("active", true);
        if (props.onMouseover) {
          props.onMouseover(d)
        };
      })
      .on('mouseout', function(d) {
        if (props.onMouseout) {
          props.onMouseout(d)
        };
      })

  // enter and update
  point.transition()
    .duration(1000)
    .attr("cx", function(d) {
      return scales.x(d.x); 
    })
    .attr("cy", function(d) { 
      return scales.y(d.y); 
    })
    .attr("r", 30)
    .style("stroke", function(d) {
      if (props.pointStroke) {
        return d.color = props.pointStroke;
      } else {
        return d.color = color(d.key);
      }
    })
    .style("fill", function(d) {
      if (d.image) {
        return ("url(#" + d.id + ")");
      }

      if (props.pointFill) {
        return d.color = props.pointFill;
      } else {
        return d.color = color(d.key);
      }
    });

  // exit
  point.exit()
    .remove();

  // update the axes
  var axes = this.axes(props, scales);
  d3.select(elem).selectAll('g.x.axis')
    .transition()
    .duration(1000)
    .call(axes.xAxis);

  d3.select(elem).selectAll('g.y.axis')
    .transition()
    .duration(1000)
    .call(axes.yAxis);
};


$(document).ready(function() {
  Timeline.create(elem, props);
})

TypeError: 'list' object is not callable in python

Close the current interpreter using exit() command and reopen typing python to start your work. And do not name a list as list literally. Then you will be fine.

Tab key == 4 spaces and auto-indent after curly braces in Vim

The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a { and hitting Enter indents the following line.

As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.

You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.

How to use the DropDownList's SelectedIndexChanged event

The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..

    <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
        AutoPostBack="True" AppendDataBoundItems="true">
    <asp:DropDownList ID="DropDownList2" runat="server"
        onselectedindexchanged="DropDownList2_SelectedIndexChanged">
    </asp:DropDownList> 


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList2

}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList3
}

How do I get my Maven Integration tests to run

Another way of running integration tests with Maven is to make use of the profile feature:

...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <includes>
                    <include>**/*Test.java</include>
                </includes>
                <excludes>
                    <exclude>**/*IntegrationTest.java</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>integration-tests</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <includes>
                            <include>**/*IntegrationTest.java</include>
                        </includes>
                        <excludes>
                            <exclude>**/*StagingIntegrationTest.java</exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
...

Running 'mvn clean install' will run the default build. As specified above integration tests will be ignored. Running 'mvn clean install -P integration-tests' will include the integration tests (I also ignore my staging integration tests). Furthermore, I have a CI server that runs my integration tests every night and for that I issue the command 'mvn test -P integration-tests'.

jQuery select option elements by value

function select_option(index)
{
    var optwewant;
    for (opts in $('#span_id').children('select'))
    {
        if (opts.value() = index)
        {
            optwewant = opts;
            break;
        }
    }
    alert (optwewant);
}

Quicksort with Python

functional approach:

def qsort(list):
    if len(list) < 2:
        return list

    pivot = list.pop()
    left = filter(lambda x: x <= pivot, list)
    right = filter(lambda x: x > pivot, list)

    return qsort(left) + [pivot] + qsort(right)

Change the icon of the exe file generated from Visual Studio 2010

Check the project properties. It's configurable there if you are using another .net windows application for example

Concat scripts in order with Gulp

I have my scripts organized in different folders for each package I pull in from bower, plus my own script for my app. Since you are going to list the order of these scripts somewhere, why not just list them in your gulp file? For new developers on your project, it's nice that all your script end-points are listed here. You can do this with gulp-add-src:

gulpfile.js

var gulp = require('gulp'),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    addsrc = require('gulp-add-src'),
    sourcemaps = require('gulp-sourcemaps');

// CSS & Less
gulp.task('css', function(){
    gulp.src('less/all.less')
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(minifyCSS())
        .pipe(sourcemaps.write('source-maps'))
        .pipe(gulp.dest('public/css'));
});

// JS
gulp.task('js', function() {
    gulp.src('resources/assets/bower/jquery/dist/jquery.js')
    .pipe(addsrc.append('resources/assets/bower/bootstrap/dist/js/bootstrap.js'))
    .pipe(addsrc.append('resources/assets/bower/blahblah/dist/js/blah.js'))
    .pipe(addsrc.append('resources/assets/js/my-script.js'))
    .pipe(sourcemaps.init())
    .pipe(concat('all.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write('source-maps'))
    .pipe(gulp.dest('public/js'));
});

gulp.task('default',['css','js']);

Note: jQuery and Bootstrap added for demonstration purposes of order. Probably better to use CDNs for those since they are so widely used and browsers could have them cached from other sites already.

Remove decimal values using SQL query

First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.

Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.

There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":

REPLACE(CAST(height as varchar(31)),'.00','')

EDIT:

This script works:

DECLARE @Height decimal(6,2);
SET @Height = 12.00;
SELECT @Height, REPLACE(CAST(@Height AS varchar(31)),'.00','');

Invoking a static method using reflection

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

Set value for particular cell in pandas DataFrame with iloc

One thing I would add here is that the at function on a dataframe is much faster particularly if you are doing a lot of assignments of individual (not slice) values.

df.at[index, 'col_name'] = x

In my experience I have gotten a 20x speedup. Here is a write up that is Spanish but still gives an impression of what's going on.

Read pdf files with php

There is a php library (pdfparser) that does exactly what you want.

project website

http://www.pdfparser.org/

github

https://github.com/smalot/pdfparser

Demo page/api

http://www.pdfparser.org/demo

After including pdfparser in your project you can get all text from mypdf.pdf like so:

<?php
$parser = new \installpath\PdfParser\Parser();
$pdf    = $parser->parseFile('mypdf.pdf');  
$text = $pdf->getText();
echo $text;//all text from mypdf.pdf

?>

Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).

Use basic authentication with jQuery and Ajax

Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.

$.ajaxSetup({
  headers: {
    'Authorization': "Basic XXXXX"
  }
});

How can I find my php.ini on wordpress?

Open .htaccess file in a code editor like sublime text and then add..

php_value upload_max_filesize 1000M
php_value post_max_size 2000M
php_value memory_limit 3000M
php_value max_execution_time 1800
php_value max_input_time 180

hope it helps..............it did for me.

Sending the bearer token with axios

If you want to some data after passing token in header so that try this code

const api = 'your api'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});

How does collections.defaultdict work?

There is a great explanation of defaultdicts here: http://ludovf.net/blog/python-collections-defaultdict/

Basically, the parameters int and list are functions that you pass. Remember that Python accepts function names as arguments. int returns 0 by default and list returns an empty list when called with parentheses.

In normal dictionaries, if in your example I try calling d[a], I will get an error (KeyError), since only keys m, s, i and p exist and key a has not been initialized. But in a defaultdict, it takes a function name as an argument, when you try to use a key that has not been initialized, it simply calls the function you passed in and assigns its return value as the value of the new key.

Simple logical operators in Bash

Here is the code for the short version of if-then-else statement:

( [ $a -eq 1 ] || [ $b -eq 2 ] ) && echo "ok" || echo "nok"

Pay attention to the following:

  1. || and && operands inside if condition (i.e. between round parentheses) are logical operands (or/and)

  2. || and && operands outside if condition mean then/else

Practically the statement says:

if (a=1 or b=2) then "ok" else "nok"

Removing input background colour for Chrome autocomplete?

As mentioned before, inset -webkit-box-shadow for me works best.

/* Code witch overwrites input background-color */
input:-webkit-autofill {
     -webkit-box-shadow: 0 0 0px 1000px #fbfbfb inset;
}

Also code snippet to change text color:

input:-webkit-autofill:first-line {
     color: #797979;
}

How to load my app from Eclipse to my Android phone instead of AVD

I had the same problem, and have not been able to get Eclipse in Windows 7 to recognise the device. The device is correctly configured, Windows 7 recognises it on the USB port, and I edited the Run settings in Eclipse to prompt for a device, and it is just not there.

I ran it with the following steps:

  • Connect the device to the computer with USB.
  • Ensure the device is not locked (ie. timed out in the UI). I have to keep unlocking it while I'm working.
  • Wait for Windows to recognise the USB device, and when the autoplay menu comes up select Open device to view files. It should open up the file system in the device, in Explorer.
  • In Explorer go to the Eclipse workspace and find the apk file from the build (eg. MyFirstApp.apk)
  • Copy the apk file to the Downloads directory on the device
  • On the device, use the My Files app (or similar) to open the Downloads directory.
  • Click the downloaded file (My First App.apk) and Android offers to install it
  • Select install
  • The app is now in the installed Apps. Run it.

A second method is to mail the apk file to the device and then download and install it. (Credits to a post on SO which I can't find now).

A third method is to use DropBox. This requires installation of DropBox on the PC and on the device (from the play store) but once both are set up it runs very smoothly. Just share a DropBox folder between the two devices, and then drop the APK into that folder on the PC, and open it on the device. With this method you don't need a USB connection, and can also install the APK on multiple devices. It also assists the management of multiple development versions (by making a separate sub-folder for each version).

Is there a way to add/remove several classes in one single instruction with classList?

The new spread operator makes it even easier to apply multiple CSS classes as array:

const list = ['first', 'second', 'third'];
element.classList.add(...list);

How do I set cell value to Date and apply default Excel date format?

http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

Read line by line in bash script

Do you mean to do:

cat test | \
while read CMD; do
echo $CMD
done

MySQL ORDER BY multiple column ASC and DESC

group by default order by pk id,so the result
username point avg_time
demo123 100 90 ---> id = 4
demo123456 100 100 ---> id = 7
demo 90 120 ---> id = 1

Remove empty strings from a list of strings

For a list with a combination of spaces and empty values, use simple list comprehension -

>>> s = ['I', 'am', 'a', '', 'great', ' ', '', '  ', 'person', '!!', 'Do', 'you', 'think', 'its', 'a', '', 'a', '', 'joke', '', ' ', '', '?', '', '', '', '?']

So, you can see, this list has a combination of spaces and null elements. Using the snippet -

>>> d = [x for x in s if x.strip()]
>>> d
>>> d = ['I', 'am', 'a', 'great', 'person', '!!', 'Do', 'you', 'think', 'its', 'a', 'a', 'joke', '?', '?']

How to replace a string in an existing file in Perl?

It can be done using a single line:

perl -pi.back -e 's/oldString/newString/g;' inputFileName

Pay attention that oldString is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \, so \[.

Difference between Dictionary and Hashtable

There is one more important difference between a HashTable and Dictionary. If you use indexers to get a value out of a HashTable, the HashTable will successfully return null for a non-existent item, whereas the Dictionary will throw an error if you try accessing a item using a indexer which does not exist in the Dictionary

Twitter Bootstrap vs jQuery UI?

You can use both with relatively few issues. Twitter Bootstrap uses jQuery 1.7.1 (as of this writing), and I can't think of any reasons why you cannot integrate additional Jquery UI components into your HTML templates.

I've been using a combination of HTML5 Boilerplate & Twitter Bootstrap built at Initializr.com. This combines two awesome starter templates into one great starter project. Check out the details at http://html5boilerplate.com/ and http://www.initializr.com/ Or to get started right away, go to http://www.initializr.com/, click the "Bootstrap 2" button, and click "Download It". This will give you all the js and css you need to get started.

And don't be scared off by HTML5 and CSS3. Initializr and HTML5 Boilerplate include polyfills and IE specific code that will allow all features to work in IE 6, 7 8, and 9.

The use of LESS in Twitter Bootstrap is also optional. They use LESS to compile all the CSS that is used by Bootstrap, but if you just want to override or add your own styles, they provide an empty css file for that purpose.

There is also a blank js file (script.js) for you to add custom code. This is where you would add your handlers or selectors for additional jQueryUI components.

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

dt is nullable you need to access its Value

if (datetime.HasValue)
    dt = datetime.Value;

It is important to remember that it can be NULL. That is why the nullablestruct has the HasValue property that tells you if it is NULL or not.

You can also use the null-coalescing operator ?? to assign a default value

dt = datetime ?? DateTime.Now;

This will assign the value on the right if the value on the left is NULL

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

Use Microsoft Visual Studio

Date separator '-'

@{string dateValue = request.Date.ToString("yyyy'-'MM'-'ddTHH:mm:ss");}

< input type="datetime-local" class="form-control" name="date1" value="@dateValue" >

Setting href attribute at runtime

In jQuery 1.6+ it's better to use:

$(selector).prop('href',"http://www...") to set the value, and

$(selector).prop('href') to get the value

In short, .prop gets and sets values on the DOM object, and .attr gets and sets values in the HTML. This makes .prop a little faster and possibly more reliable in some contexts.

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

What's the difference between integer class and numeric class in R

First off, it is perfectly feasible to use R successfully for years and not need to know the answer to this question. R handles the differences between the (usual) numerics and integers for you in the background.

> is.numeric(1)

[1] TRUE

> is.integer(1)

[1] FALSE

> is.numeric(1L)

[1] TRUE

> is.integer(1L)

[1] TRUE

(Putting capital 'L' after an integer forces it to be stored as an integer.)

As you can see "integer" is a subset of "numeric".

> .Machine$integer.max

[1] 2147483647

> .Machine$double.xmax

[1] 1.797693e+308

Integers only go to a little more than 2 billion, while the other numerics can be much bigger. They can be bigger because they are stored as double precision floating point numbers. This means that the number is stored in two pieces: the exponent (like 308 above, except in base 2 rather than base 10), and the "significand" (like 1.797693 above).

Note that 'is.integer' is not a test of whether you have a whole number, but a test of how the data are stored.

One thing to watch out for is that the colon operator, :, will return integers if the start and end points are whole numbers. For example, 1:5 creates an integer vector of numbers from 1 to 5. You don't need to append the letter L.

> class(1:5)
[1] "integer"

Reference: https://www.quora.com/What-is-the-difference-between-numeric-and-integer-in-R

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I solved this issue by running the following command in an elevated command prompt as specified in this post.

net start mssqlserver

Paste text on Android Emulator

Only For API level >= 24

Copy any text from your local machine and then simply run this command

adb shell input keyevent 279

Make sure In Android Emulator Settings the Enable Clipboard Sharing options is enabled

Most efficient way to find smallest of 3 numbers Java?

Simply use this math function

System.out.println(Math.min(a,b,c));

You will get the answer in single line.

How to find which views are using a certain table in SQL Server (2008)?

If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).

enter image description here

enter image description here

It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??

Multiple files upload in Codeigniter

private function upload_files($path, $title, $files)
{
    $config = array(
        'upload_path'   => $path,
        'allowed_types' => 'jpg|gif|png',
        'overwrite'     => 1,
    );

    $this->load->library('upload', $config);

    $images = array();

    foreach ($files['name'] as $key => $image) {
        $_FILES['images[]']['name']= $files['name'][$key];
        $_FILES['images[]']['type']= $files['type'][$key];
        $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
        $_FILES['images[]']['error']= $files['error'][$key];
        $_FILES['images[]']['size']= $files['size'][$key];

        $fileName = $title .'_'. $image;

        $images[] = $fileName;

        $config['file_name'] = $fileName;

        $this->upload->initialize($config);

        if ($this->upload->do_upload('images[]')) {
            $this->upload->data();
        } else {
            return false;
        }
    }
    return true;
}

How do I pass a method as a parameter in Python

Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.

Since you asked about methods, I'm using methods in the following examples, but note that everything below applies identically to functions (except without the self parameter).

To call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name:

def method1(self):
    return 'hello world'

def method2(self, methodToRun):
    result = methodToRun()
    return result

obj.method2(obj.method1)

Note: I believe a __call__() method does exist, i.e. you could technically do methodToRun.__call__(), but you probably should never do so explicitly. __call__() is meant to be implemented, not to be invoked from your own code.

If you wanted method1 to be called with arguments, then things get a little bit more complicated. method2 has to be written with a bit of information about how to pass arguments to method1, and it needs to get values for those arguments from somewhere. For instance, if method1 is supposed to take one argument:

def method1(self, spam):
    return 'hello ' + str(spam)

then you could write method2 to call it with one argument that gets passed in:

def method2(self, methodToRun, spam_value):
    return methodToRun(spam_value)

or with an argument that it computes itself:

def method2(self, methodToRun):
    spam_value = compute_some_value()
    return methodToRun(spam_value)

You can expand this to other combinations of values passed in and values computed, like

def method1(self, spam, ham):
    return 'hello ' + str(spam) + ' and ' + str(ham)

def method2(self, methodToRun, ham_value):
    spam_value = compute_some_value()
    return methodToRun(spam_value, ham_value)

or even with keyword arguments

def method2(self, methodToRun, ham_value):
    spam_value = compute_some_value()
    return methodToRun(spam_value, ham=ham_value)

If you don't know, when writing method2, what arguments methodToRun is going to take, you can also use argument unpacking to call it in a generic way:

def method1(self, spam, ham):
    return 'hello ' + str(spam) + ' and ' + str(ham)

def method2(self, methodToRun, positional_arguments, keyword_arguments):
    return methodToRun(*positional_arguments, **keyword_arguments)

obj.method2(obj.method1, ['spam'], {'ham': 'ham'})

In this case positional_arguments needs to be a list or tuple or similar, and keyword_arguments is a dict or similar. In method2 you can modify positional_arguments and keyword_arguments (e.g. to add or remove certain arguments or change the values) before you call method1.

Why is pydot unable to find GraphViz's executables in Windows 8?

This happened because I had installed graphviz after I had installed pydot. Hence, pydot wasn't able to find it. Reinstalling it in the correct order solved the problem.

Not Able To Debug App In Android Studio

This solved my problem. Uninstall app from device and run it again via Android studio.

How can I add a class to a DOM element in JavaScript?

Here is working source code using a function approach.

<html>
    <head>
        <style>
            .news{padding:10px; margin-top:2px;background-color:red;color:#fff;}
        </style>
    </head>

    <body>
    <div id="dd"></div>
        <script>
            (function(){
                var countup = this;
                var newNode = document.createElement('div');
                newNode.className = 'textNode news content';
                newNode.innerHTML = 'this created div contains a class while created!!!';
                document.getElementById('dd').appendChild(newNode);
            })();
        </script>
    </body>
</html>

Spring JPA and persistence.xml

I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.

Primitive type 'short' - casting in Java

What language are you using?

Many C based languages have a rule that any mathematical expression is performed in size int or larger. Because of this, once you add two shorts the result is of type int. This causes the need for a cast.

Why can't DateTime.Parse parse UTC date

Just replace "UTC" with "GMT" -- simple and doesn't break correctly formatted dates:

DateTime.Parse("Tue, 1 Jan 2008 00:00:00 UTC".Replace("UTC", "GMT"))

Do we need type="text/css" for <link> in HTML5

You don't really need it today, because the current standard makes it optional -- and every useful browser currently assumes that a style sheet is CSS, even in versions of HTML that considered the attribute "required".

With HTML being a "living standard" now, though -- and thus subject to change -- you can only guarantee so much. And there's no new DTD that you can point to and say the page was written for that version of HTML, and no reliable way even to say "HTML as of such-and-such a date". For forward-compatibility reasons, in my opinion, you should specify the type.

Flex-box: Align last row to grid

If you want to align the last item to the grid use the following code:

Grid container

.card-grid {
  box-sizing: border-box;
  max-height: 100%;
  display: flex;
  flex-direction: row;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  justify-content: space-between;
  align-items: stretch;
  align-content: stretch;
  -webkit-box-align: stretch;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-flow: row wrap;
  flex-flow: row wrap;
}

.card-grid:after {
  content: "";
  flex: 1 1 100%;
  max-width: 32%;
}

Item in the grid

.card {
  flex: 1 1 100%;
  box-sizing: border-box;
  -webkit-box-flex: 1;
  max-width: 32%;
  display: block;
  position: relative;

}

The trick is to set the max-width of the item equal to the max-width of the .card-grid:after.

Live demo on Codepen

Dots in URL causes 404 with ASP.NET mvc and IIS

Depending on how important it is for you to keep your URI without querystrings, you can also just pass the value with dots as part of the querystring, not the URI.

E.g. www.example.com/people?name=michael.phelps will work, without having to change any settings or anything.

You lose the elegance of having a clean URI, but this solution does not require changing or adding any settings or handlers.

What is the difference between BIT and TINYINT in MySQL?

All these theoretical discussions are great, but in reality, at least if you're using MySQL and really for SQLServer as well, it's best to stick with non-binary data for your booleans for the simple reason that it's easier to work with when you're outputting the data, querying and so on. It is especially important if you're trying to achieve interoperability between MySQL and SQLServer (i.e. you sync data between the two), because the handling of BIT datatype is different in the two of them. SO in practice you will have a lot less hassles if you stick with a numeric datatype. I would recommend for MySQL to stick with BOOL or BOOLEAN which gets stored as TINYINT(1). Even the way MySQL Workbench and MySQL Administrator display the BIT datatype isn't nice (it's a little symbol for binary data). So be practical and save yourself the hassles (and unfortunately I'm speaking from experience).

Disable building workspace process in Eclipse

You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically from the main menu is unchecked.

C# how to convert File.ReadLines into string array?

Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt"); The rest of your code should work fine.

How to add border around linear layout except at the bottom?

Save this xml and add as a background for the linear layout....

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <stroke android:width="4dp" android:color="#FF00FF00" /> 
    <solid android:color="#ffffff" /> 
    <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
    <corners android:radius="4dp" /> 
</shape>

Hope this helps! :)

How to extract closed caption transcript from YouTube video?

Here's how to get the transcript of a YouTube video (when available):

  • Go to YouTube and open the video of your choice.
  • Click on the "More actions" button (3 horizontal dots) located next to the Share button.
  • Click "Open transcript"

Although the syntax may be a little goofy this is a pretty good solution.

Source: http://ccm.net/faq/40644-youtube-how-to-get-the-transcript-of-a-video

R legend placement in a plot

Edit 2017:

use ggplot and theme(legend.position = ""):

library(ggplot2)
library(reshape2)

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

df = data.frame(number = 1:5,a,b,c)
df_long <- melt(df,id.vars = "number")
ggplot(data=df_long,aes(x = number,y=value, colour=variable)) +geom_line() +
theme(legend.position="bottom")

Original answer 2012: Put the legend on the bottom:

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

dev.off()

layout(rbind(1,2), heights=c(7,1))  # put legend on bottom 1/8th of the chart

plot(a,type='l',ylim=c(min(c(a,b,c)),max(c(a,b,c))))
lines(b,lty=2)
lines(c,lty=3,col='blue')

# setup for no margins on the legend
par(mar=c(0, 0, 0, 0))
# c(bottom, left, top, right)
plot.new()
legend('center','groups',c("A","B","C"), lty = c(1,2,3),
       col=c('black','black','blue'),ncol=3,bty ="n")

enter image description here

How do I make a file:// hyperlink that works in both IE and Firefox?

file Protocol
Opens a file on a local or network drive.

Syntax

Copy
 file:///sDrives[|sFile]
Tokens 

sDrives
Specifies the local or network drive.

sFile
Optional. Specifies the file to open. If sFile is omitted and the account accessing the drive has permission to browse the directory, a list of accessible files and directories is displayed.

Remarks

The file protocol and sDrives parameter can be omitted and substituted with just the command line representation of the drive letter and file location. For example, to browse the My Documents directory, the file protocol can be specified as file:///C|/My Documents/ or as C:\My Documents. In addition, a single '\' is equivalent to specifying the root directory on the primary local drive. On most computers, this is C:.

Available as of Microsoft Internet Explorer 3.0 or later.

Note Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.

Example

The following sample demonstrates four ways to use the File protocol.

Copy

//Specifying a drive and a file name. 

file:///C|/My Documents/ALetter.html

//Specifying only a drive and a path to browse the directory. 

file:///C|/My Documents/

//Specifying a drive and a directory using the command line representation of the directory location. 

C:\My Documents\

//Specifying only the directory on the local primary drive. 

\My Documents\

http://msdn.microsoft.com/en-us/library/aa767731

Create a new file in git bash

This is a very simple to create file in git bash at first write touch then file name with extension

for example

touch filename.extension

How to embed images in html email

Here is a way to get a string variable without having to worry about the coding.

If you have Mozilla Thunderbird, you can use it to fetch the html image code for you.

I wrote a little tutorial here, complete with a screenshot (it's for powershell, but that doesn't matter for this):

powershell email with html picture showing red x

And again:

How to embed images in email

Question mark characters displaying within text, why is this?

Your browser hasn't interpretted the encoding of the page correctly (either because you've forced it to a particular setting, or the page is set incorrectly), and thus cannot display some of the characters.

PHP convert XML to JSON

Best solution which works like a charm

$fileContents= file_get_contents($url);

$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);

$fileContents = trim(str_replace('"', "'", $fileContents));

$simpleXml = simplexml_load_string($fileContents);

//$json = json_encode($simpleXml); // Remove // if you want to store the result in $json variable

echo '<pre>'.json_encode($simpleXml,JSON_PRETTY_PRINT).'</pre>';

Source

Share link on Google+

As of July 25, 2011, the answer is no.

I have looked through their Javascript and it seems they don't want anyone directly accessing their api for +1 at the moment.

The Javascript that does all of the work for the +1 button is here:

https://apis.google.com/js/plusone.js

If you run it through a Javascript cleanup program you can tell that they have obfuscated their code with various functions that only start with letters and constantly refer back to themselves and do cryptic things.

I figure in the next couple of weeks or moths they will release a link based sharing api due to the fact that we will need this for sharing from flash and other web based formats that don't rely on pure html and js.

Debian 8 (Live-CD) what is the standard login and password?

I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:

login : Debian Live User
password : live

I hope this helps

How to write a test which expects an Error to be thrown in Jasmine?

For anyone who still might be facing this issue, for me the posted solution didn't work and it kept on throwing this error: Error: Expected function to throw an exception. I later realised that the function which I was expecting to throw an error was an async function and was expecting promise to be rejected and then throw error and that's what I was doing in my code:

throw new Error('REQUEST ID NOT FOUND');

and thats what I did in my test and it worked:

it('Test should throw error if request not found', willResolve(() => {
         const promise = service.getRequestStatus('request-id');
                return expectToReject(promise).then((err) => {
                    expect(err.message).toEqual('REQUEST NOT FOUND');
                });
            }));

Show Hide div if, if statement is true

A fresh look at this(possibly)
in your php:

else{
      $hidemydiv = "hide";
}

And then later in your html code:

<div class='<?php echo $hidemydiv ?>' > maybe show or hide this</div>

in this way your php remains quite clean

How to write multiple line string using Bash with variables?

I'm using Mac OS and to write multiple lines in a SH Script following code worked for me

#! /bin/bash
FILE_NAME="SomeRandomFile"

touch $FILE_NAME

echo """I wrote all
the  
stuff
here.
And to access a variable we can use
$FILE_NAME  

""" >> $FILE_NAME

cat $FILE_NAME

Please don't forget to assign chmod as required to the script file. I have used

chmod u+x myScriptFile.sh

How to subtract 2 hours from user's local time?

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

Saving an Excel sheet in a current directory with VBA

If the Path is omitted the file will be saved automaticaly in the current directory. Try something like this:

ActiveWorkbook.SaveAs "Filename.xslx"

Fiddler not capturing traffic from browsers

I had exactly the same problem. I finally gave up. Reset Chrome's browser settings to default. Uninstalled then reinstalled Fiddler. After that, everything worked.

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

I have faced the same problem and I solved as give db_owner permission too to the Database user.

How do I get a computer's name and IP address using VB.NET?

Imports System.Net

Module MainLine
    Sub Main()
        Dim hostName As String = Dns.GetHostName
        Console.WriteLine("Host Name : " & hostName & vbNewLine)
        For Each address In Dns.GetHostEntry(hostName).AddressList()
            Select Case Convert.ToInt32(address.AddressFamily)
                Case 2
                    Console.WriteLine("IP Version 4 Address: " & address.ToString)
                Case 23
                    Console.WriteLine("IP Version 6 Address: " & address.ToString)
            End Select
        Next
        Console.ReadKey()
    End Sub
End Module

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

I struggled with this for a long time. I am using Angular 6 and I found that

let headers = new HttpHeaders();
headers = headers.append('key', 'value');

did not work. But what did work was

let headers = new HttpHeaders().append('key', 'value');

did, which makes sense when you realize they are immutable. So having created a header you can't add to it. I haven't tried it, but I suspect

let headers = new HttpHeaders();
let headers1 = headers.append('key', 'value');

would work too.

Android Studio - Failed to notify project evaluation listener error

had similar problem, issue was different versions of included library. to find out what causes problem run build command with stacktrace

./gradlew build --stacktrace

Java Try Catch Finally blocks without Catch

The Java Language Specification(1) describes how try-catch-finally is executed. Having no catch is equivalent to not having a catch able to catch the given Throwable.

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    • If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then …
    • If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
      • If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.
      • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).

(1) Execution of try-catch-finally

SonarQube Exclude a directory

This worked for me:

sonar.exclusions=src/**/wwwroot/**/*.js,src/**/wwwroot/**/*.css

It excludes any .js and .css files under any of the sub directories of a folder "wwwroot" appearing as one of the sub directories of the "src" folder (project root).

Convert object of any type to JObject with Json.NET

JObject implements IDictionary, so you can use it that way. For ex,

var cycleJson  = JObject.Parse(@"{""name"":""john""}");

//add surname
cycleJson["surname"] = "doe";

//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });

So the final json will be

{
  "name": "john",
  "surname": "doe",
  "complexObj": {
    "id": 1,
    "name": "test"
  }
}

You can also use dynamic keyword

dynamic cycleJson  = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });

How do I fix "The expression of type List needs unchecked conversion...'?

If you don't want to put @SuppressWarning("unchecked") on each sf.getEntries() call, you can always make a wrapper that will return List.

See this other question

Android: How to set password property in an edit text?

To set password enabled in EditText, We will have to set an "inputType" attribute in xml file.If we are using only EditText then we will have set input type in EditText as given in below code.

                    <EditText
                    android:id="@+id/password_Edit"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:hint="password"
                    android:imeOptions="actionNext"
                    android:inputType="textPassword"
                    android:maxLength="100"
                    android:nextFocusDown="@+id/next"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

Password enable attribute is

 android:inputType="textPassword"

But if we are implementing Password EditText with Material Design (With Design support library) then we will have write code as given bellow.

<android.support.design.widget.TextInputLayout
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:id="@+id/txtInput_currentPassword"
                android:layout_width="match_parent"
                app:passwordToggleEnabled="false"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/password_Edit"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:hint="@string/hint_currentpassword"
                    android:imeOptions="actionNext"
                    android:inputType="textPassword"
                    android:maxLength="100"
                    android:nextFocusDown="@+id/next"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </android.support.design.widget.TextInputLayout>

@Note: - In Android SDK 24 and above, "passwordToggleEnabled" is by default true. So if we have the customs handling of show/hide feature in the password EditText then we will have to set it false in code as given above in .

app:passwordToggleEnabled="true"

To add above line, we will have to add below line in root layout.

xmlns:app="http://schemas.android.com/apk/res-auto"

how to check which version of nltk, scikit learn installed?

In my machine which is ubuntu 14.04 with python 2.7 installed, if I go here,

/usr/local/lib/python2.7/dist-packages/nltk/

there is a file called

VERSION.

If I do a cat VERSION it prints 3.1, which is the NLTK version installed.

Code for a simple JavaScript countdown timer?

My solution works with MySQL date time formats and provides a callback function. on complition. Disclaimer: works only with minutes and seconds, as this is what I needed.

jQuery.fn.countDownTimer = function(futureDate, callback){
    if(!futureDate){
        throw 'Invalid date!';
    }

    var currentTs = +new Date();
    var futureDateTs = +new Date(futureDate);

    if(futureDateTs <= currentTs){
        throw 'Invalid date!';
    }


    var diff = Math.round((futureDateTs - currentTs) / 1000);
    var that = this;

    (function countdownLoop(){
        // Get hours/minutes from timestamp
        var m = Math.floor(diff % 3600 / 60);
        var s = Math.floor(diff % 3600 % 60);
        var text = zeroPad(m, 2) + ':' + zeroPad(s, 2);

        $(that).text(text);

        if(diff <= 0){
            typeof callback === 'function' ? callback.call(that) : void(0);
            return;
        }

        diff--;
        setTimeout(countdownLoop, 1000);
    })();

    function zeroPad(num, places) {
      var zero = places - num.toString().length + 1;
      return Array(+(zero > 0 && zero)).join("0") + num;
    }
}

// $('.heading').countDownTimer('2018-04-02 16:00:59', function(){ // on complete})

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

I just ran into this issue when diffing my branch with master. Git returned one 'mode' error when I expected my branch to be identical to master. I fixed by deleting the file and then merging master in again.

First I ran the diff:

git checkout my-branch
git diff master

This returned:

diff --git a/bin/script.sh b/bin/script.sh
old mode 100755
new mode 100644

I then ran the following to fix:

rm bin/script.sh
git merge -X theirs master

After this, git diff returned no differences between my-branch and master.

How to represent matrices in python

Python doesn't have matrices. You can use a list of lists or NumPy

Array to Hash Ruby

All answers assume the starting array is unique. OP did not specify how to handle arrays with duplicate entries, which result in duplicate keys.

Let's look at:

a = ["item 1", "item 2", "item 3", "item 4", "item 1", "item 5"]

You will lose the item 1 => item 2 pair as it is overridden bij item 1 => item 5:

Hash[*a]
=> {"item 1"=>"item 5", "item 3"=>"item 4"}

All of the methods, including the reduce(&:merge!) result in the same removal.

It could be that this is exactly what you expect, though. But in other cases, you probably want to get a result with an Array for value instead:

{"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

The naïve way would be to create a helper variable, a hash that has a default value, and then fill that in a loop:

result = Hash.new {|hash, k| hash[k] = [] } # Hash.new with block defines unique defaults.
a.each_slice(2) {|k,v| result[k] << v }
a
=> {"item 1"=>["item 2", "item 5"], "item 3"=>["item 4"]}

It might be possible to use assoc and reduce to do above in one line, but that becomes much harder to reason about and read.

Equivalent of LIMIT for DB2

Using FETCH FIRST [n] ROWS ONLY:

http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.perf/db2z_fetchfirstnrows.htm

SELECT LASTNAME, FIRSTNAME, EMPNO, SALARY
  FROM EMP
  ORDER BY SALARY DESC
  FETCH FIRST 20 ROWS ONLY;

To get ranges, you'd have to use ROW_NUMBER() (since v5r4) and use that within the WHERE clause: (stolen from here: http://www.justskins.com/forums/db2-select-how-to-123209.html)

SELECT code, name, address
FROM ( 
  SELECT row_number() OVER ( ORDER BY code ) AS rid, code, name, address
  FROM contacts
  WHERE name LIKE '%Bob%' 
  ) AS t
WHERE t.rid BETWEEN 20 AND 25;

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Table row and column number in jQuery

$('td').click(function() {
    var myCol = $(this).index();
    var $tr = $(this).closest('tr');
    var myRow = $tr.index();
});

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english