Programs & Examples On #Pos for .net

pos-for-.net refers to Point of Service (POS) class libraries by Microsoft that allows applications developed in the .NET Framework to integrate with point of sale peripheral devices.

Error with multiple definitions of function

The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

You don't want to include cpp files. You want to include header files.

The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.

fun.hpp:

#include <iostream>

class classA {
    friend void funct();
public:
    classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
    int propa;
    int propb;
    void outfun(){
        std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
    }
};

fun.cpp:

#include "fun.hpp"

using namespace std;

void funct(){
    cout<<"enter funct"<<endl;
    classA tmp(1,2);
    tmp.outfun();
    cout<<"exit funct"<<endl;
}

mainfile.cpp:

#include <iostream>
#include "fun.hpp"
using namespace std;

int main(int nargin,char* varargin[]) {
    cout<<"call funct"<<endl;
    funct();
    cout<<"exit main"<<endl;
    return 0;
}

Note that it is generally recommended to avoid using namespace std in header files.

The transaction log for the database is full

The answer to the question is not deleting the rows from a table but it is the the tempDB space that is being taken up due to an active transaction. this happens mostly when there is a merge (upsert) is being run where we try to insert update and delete the transactions. The only option is is to make sure the DB is set to simple recovery model and also increase the file to the maximum space (Add an other file group). Although this has its own advantages and disadvantages these are the only options.

The other option that you have is to split the merge(upsert) into two operations. one that does the insert and the other that does the update and delete.

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

Ajax LARAVEL 419 POST error

I received this error when I had a config file with <?php on the second line instead of the first.

Login failed for user 'DOMAIN\MACHINENAME$'

A colleague had the same error and it was due to a little configuration error in IIS.
The wrong Application Pool was assigned for the web application.

Indeed we use a custom Application Pool with a specific Identity to meet our needs.

In his local IIS Manager -> Sites -> Default Web Site -> Our Web App Name -> Basic Settings... The Application Pool was "DefaultAppPool" instead of our custom Application Pool.

Setting the correct application pool solved the problem.

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...

...create an NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                       forKeys:keys];

...iterate over it

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

...make it mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Note: historic version before 2010: [[dictionary mutableCopy] autorelease]

...and alter it

[mutableDict setObject:@"value3" forKey:@"key3"];

...then store it to a file

[mutableDict writeToFile:@"path/to/file" atomically:YES];

...and read it back again

NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];

...read a value

NSString *x = [anotherDict objectForKey:@"key1"];

...check if a key exists

if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");

...use scary futuristic syntax

From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]

Regex Last occurrence?

What about this regex: \\[^\\]+$

Validate that text field is numeric usiung jQuery

Regex isn't needed, nor is plugins

if (isNaN($('#Field').val() / 1) == false) {
    your code here
}

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

Calling a particular PHP function on form submit

Assuming that your script is named x.php, try this

<?php 
   function display($s) {
      echo $s;
   }
?>
<html>
    <body>
        <form method="post" action="x.php">
            <input type="text" name="studentname">
            <input type="submit" value="click">
        </form>
        <?php
           if($_SERVER['REQUEST_METHOD']=='POST')
           {
               display();
           } 
        ?>
    </body>
</html>

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

What you have is a parse error. Those are thrown before any code is executed. A PHP file needs to be parsed in its entirety before any code in it can be executed. If there's a parse error in the file where you're setting your error levels, they won't have taken effect by the time the error is thrown.

Either break your files up into smaller parts, like setting the error levels in one file and then includeing another file which contains the actual code (and errors), or set the error levels outside PHP using php.ini or .htaccess directives.

open link in iframe

Because the target of the link matches the name of the iframe, the link will open in the iframe. Try this:

<iframe src="http://stackoverflow.com/" name="iframe_a">
<p>Your browser does not support iframes.</p>
</iframe>

<a href="http://www.cnn.com" target="iframe_a">www.cnn.com</a>

JQuery - Storing ajax response into global variable

Here is a function that does the job quite well. I could not get the Best Answer above to work.

jQuery.extend({
    getValues: function(url) {
        var result = null;
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'xml',
            async: false,
            success: function(data) {
                result = data;
            }
        });
       return result;
    }
});

Then to access it, create the variable like so:

var results = $.getValues("url string");

GROUP_CONCAT ORDER BY

Try

SELECT li.clientid, group_concat(li.views ORDER BY li.views) AS views,
       group_concat(li.percentage ORDER BY li.percentage) 
FROM table_views li 
GROUP BY client_id

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function%5Fgroup-concat

How do I convert between ISO-8859-1 and UTF-8 in Java?

Here is a function to convert UNICODE (ISO_8859_1) to UTF-8

public static String String_ISO_8859_1To_UTF_8(String strISO_8859_1) {
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strISO_8859_1.length(); i++) {
  final char ch = strISO_8859_1.charAt(i);
  if (ch <= 127) 
  {
      stringBuilder.append(ch);
  }
  else 
  {
      stringBuilder.append(String.format("%02x", (int)ch));
  }
}
String s = stringBuilder.toString();
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
    data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                         + Character.digit(s.charAt(i+1), 16));
}
String strUTF_8 =new String(data, StandardCharsets.UTF_8);
return strUTF_8;
}

TEST

String strA_ISO_8859_1_i = new String("??????".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

System.out.println("ISO_8859_1 strA est = "+ strA_ISO_8859_1_i + "\n String_ISO_8859_1To_UTF_8 = " + String_ISO_8859_1To_UTF_8(strA_ISO_8859_1_i));

RESULT

ISO_8859_1 strA est = اÙغÙا٠String_ISO_8859_1To_UTF_8 = ??????

How to list branches that contain a given commit?

The answer for git branch -r --contains <commit> works well for normal remote branches, but if the commit is only in the hidden head namespace that GitHub creates for PRs, you'll need a few more steps.

Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r doesn't know about PR #42 because refs like refs/pull/42/head aren't listed as a remote branch by default.

In .git/config for the [remote "origin"] section add a new line:

fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

(This gist has more context.)

Then when you git fetch you'll get all the PR branches, and when you run git branch -r --contains <commit> you'll see origin/pr/42 contains the commit.

How should I store GUID in MySQL tables?

I would suggest using the functions below since the ones mentioned by @bigh_29 transforms my guids into new ones (for reasons I don't understand). Also, these are a little bit faster in the tests I did on my tables. https://gist.github.com/damienb/159151

DELIMITER |

CREATE FUNCTION uuid_from_bin(b BINARY(16))
RETURNS CHAR(36) DETERMINISTIC
BEGIN
  DECLARE hex CHAR(32);
  SET hex = HEX(b);
  RETURN LOWER(CONCAT(LEFT(hex, 8), '-', MID(hex, 9,4), '-', MID(hex, 13,4), '-', MID(hex, 17,4), '-', RIGHT(hex, 12)));
END
|

CREATE FUNCTION uuid_to_bin(s CHAR(36))
RETURNS BINARY(16) DETERMINISTIC
RETURN UNHEX(CONCAT(LEFT(s, 8), MID(s, 10, 4), MID(s, 15, 4), MID(s, 20, 4), RIGHT(s, 12)))
|

DELIMITER ;

How do I use IValidatableObject?

The problem with the accepted answer is that it now depends on the caller for the object to be properly validated. I would either remove the RangeAttribute and do the range validation inside the Validate method or I would create a custom attribute subclassing RangeAttribute that takes the name of the required property as an argument on the constructor.

For example:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class RangeIfTrueAttribute : RangeAttribute
{
    private readonly string _NameOfBoolProp;

    public RangeIfTrueAttribute(string nameOfBoolProp, int min, int max) : base(min, max)
    {
        _NameOfBoolProp = nameOfBoolProp;
    }

    public RangeIfTrueAttribute(string nameOfBoolProp, double min, double max) : base(min, max)
    {
        _NameOfBoolProp = nameOfBoolProp;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_NameOfBoolProp);
        if (property == null)
            return new ValidationResult($"{_NameOfBoolProp} not found");

        var boolVal = property.GetValue(validationContext.ObjectInstance, null);

        if (boolVal == null || boolVal.GetType() != typeof(bool))
            return new ValidationResult($"{_NameOfBoolProp} not boolean");

        if ((bool)boolVal)
        {
            return base.IsValid(value, validationContext);
        }
        return null;
    }
}

Install sbt on ubuntu

My guess is that the directory ~/bin/sbt/bin is not in your PATH.

To execute programs or scripts that are in the current directory you need to prefix the command with ./, as in:

./sbt

This is a security feature in linux, so to prevent overriding of system commands (and other programs) by a malicious party dropping a file in your home directory (for example). Imagine a script called 'ls' that emails your /etc/passwd file to 3rd party before executing the ls command... Or one that executes 'rm -rf .'...

That said, unless you need something specific from the latest source code, you're best off doing what paradigmatic said in his post, and install it from the Typesafe repository.

Changing the cursor in WPF sometimes works, sometimes doesn't

One way we do this in our application is using IDisposable and then with using(){} blocks to ensure the cursor is reset when done.

public class OverrideCursor : IDisposable
{

  public OverrideCursor(Cursor changeToCursor)
  {
    Mouse.OverrideCursor = changeToCursor;
  }

  #region IDisposable Members

  public void Dispose()
  {
    Mouse.OverrideCursor = null;
  }

  #endregion
}

and then in your code:

using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait))
{
  // Do work...
}

The override will end when either: the end of the using statement is reached or; if an exception is thrown and control leaves the statement block before the end of the statement.

Update

To prevent the cursor flickering you can do:

public class OverrideCursor : IDisposable
{
  static Stack<Cursor> s_Stack = new Stack<Cursor>();

  public OverrideCursor(Cursor changeToCursor)
  {
    s_Stack.Push(changeToCursor);

    if (Mouse.OverrideCursor != changeToCursor)
      Mouse.OverrideCursor = changeToCursor;
  }

  public void Dispose()
  {
    s_Stack.Pop();

    Cursor cursor = s_Stack.Count > 0 ? s_Stack.Peek() : null;

    if (cursor != Mouse.OverrideCursor)
      Mouse.OverrideCursor = cursor;
  }

}

PHP isset() with multiple parameters

You just need:

if (!empty($_POST['search_term']) && !empty($_POST['postcode']))

isset && !empty is redundant.

How can I create my own comparator for a map?

std::map takes up to four template type arguments, the third one being a comparator. E.g.:

struct cmpByStringLength {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.length() < b.length();
    }
};

// ...
std::map<std::string, std::string, cmpByStringLength> myMap;

Alternatively you could also pass a comparator to maps constructor.

Note however that when comparing by length you can only have one string of each length in the map as a key.

Python: convert string from UTF-8 to Latin-1

If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.

In my case, I was using json.load on data incorrectly read from file by not using the encoding="utf-8". Trying to de-/encode the resulting string to latin-1 just does not help...

What's the difference between @Component, @Repository & @Service annotations in Spring?

Explanation of stereotypes :

  • @Service - Annotate all your service classes with @Service. This layer knows the unit of work. All your business logic will be in Service classes. Generally methods of service layer are covered under transaction. You can make multiple DAO calls from service method, if one transaction fails all transactions should rollback.
  • @Repository - Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
  • @Component - Annotate your other components (for example REST resource classes) with component stereotype.
  • @Autowired - Let Spring auto-wire other beans into your classes using @Autowired annotation.

@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

Originally answered here.

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

How to call on a function found on another file?

Small addition to @user995502's answer on how to run the program.

g++ player.cpp main.cpp -o main.out && ./main.out

Parse JSON from HttpURLConnection object

This function will be used get the data from url in form of HttpResponse object.

public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}

Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.

String jsonString     =     
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/    blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new    CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
                    jsonElementForJavaObject, JsonJavaModel.class);

This is a simple java model class for incomming json. public class JsonJavaModel{ String content; String title; } This is a custom deserialiser:

public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel>         {

@Override
public JsonJavaModel deserialize(JsonElement json, Type type,
                                 JsonDeserializationContext arg2) throws    JsonParseException {
    final JsonJavaModel jsonJavaModel= new JsonJavaModel();
    JsonObject object = json.getAsJsonObject();

    try {
     jsonJavaModel.content = object.get("Content").getAsString()
     jsonJavaModel.title = object.get("Title").getAsString()

    } catch (Exception e) {

        e.printStackTrace();
    }
    return jsonJavaModel;
}

Include Gson library and org.apache.http.util.EntityUtils;

Lowercase and Uppercase with jQuery

Try this:

var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();

Possible duplicate with: How do I use jQuery to ignore case when selecting

How to find if a native DLL file is compiled as x64 or x86?

The Magic field of the IMAGE_OPTIONAL_HEADER (though there is nothing optional about the header in Windows executable images (DLL/EXE files)) will tell you the architecture of the PE.

Here's an example of grabbing the architecture from a file.

public static ushort GetImageArchitecture(string filepath) {
    using (var stream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
    using (var reader = new System.IO.BinaryReader(stream)) {
        //check the MZ signature to ensure it's a valid Portable Executable image
        if (reader.ReadUInt16() != 23117) 
            throw new BadImageFormatException("Not a valid Portable Executable image", filepath);

        // seek to, and read, e_lfanew then advance the stream to there (start of NT header)
        stream.Seek(0x3A, System.IO.SeekOrigin.Current); 
        stream.Seek(reader.ReadUInt32(), System.IO.SeekOrigin.Begin);

        // Ensure the NT header is valid by checking the "PE\0\0" signature
        if (reader.ReadUInt32() != 17744)
            throw new BadImageFormatException("Not a valid Portable Executable image", filepath);

        // seek past the file header, then read the magic number from the optional header
        stream.Seek(20, System.IO.SeekOrigin.Current); 
        return reader.ReadUInt16();
    }
}

The only two architecture constants at the moment are:

0x10b - PE32
0x20b - PE32+

Cheers

UPDATE It's been a while since I posted this answer, yet I still see that it gets a few upvotes now and again so I figured it was worth updating. I wrote a way to get the architecture of a Portable Executable image, which also checks to see if it was compiled as AnyCPU. Unfortunately the answer is in C++, but it shouldn't be too hard to port to C# if you have a few minutes to look up the structures in WinNT.h. If people are interested I'll write a port in C#, but unless people actually want it I wont spend much time stressing about it.

#include <Windows.h>

#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))

typedef enum _pe_architecture {
    PE_ARCHITECTURE_UNKNOWN = 0x0000,
    PE_ARCHITECTURE_ANYCPU  = 0x0001,
    PE_ARCHITECTURE_X86     = 0x010B,
    PE_ARCHITECTURE_x64     = 0x020B
} PE_ARCHITECTURE;

LPVOID GetOffsetFromRva(IMAGE_DOS_HEADER *pDos, IMAGE_NT_HEADERS *pNt, DWORD rva) {
    IMAGE_SECTION_HEADER *pSecHd = IMAGE_FIRST_SECTION(pNt);
    for(unsigned long i = 0; i < pNt->FileHeader.NumberOfSections; ++i, ++pSecHd) {
        // Lookup which section contains this RVA so we can translate the VA to a file offset
        if (rva >= pSecHd->VirtualAddress && rva < (pSecHd->VirtualAddress + pSecHd->Misc.VirtualSize)) {
            DWORD delta = pSecHd->VirtualAddress - pSecHd->PointerToRawData;
            return (LPVOID)MKPTR(pDos, rva - delta);
        }
    }
    return NULL;
}

PE_ARCHITECTURE GetImageArchitecture(void *pImageBase) {
    // Parse and validate the DOS header
    IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)pImageBase;
    if (IsBadReadPtr(pDosHd, sizeof(pDosHd->e_magic)) || pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
        return PE_ARCHITECTURE_UNKNOWN;

    // Parse and validate the NT header
    IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
    if (IsBadReadPtr(pNtHd, sizeof(pNtHd->Signature)) || pNtHd->Signature != IMAGE_NT_SIGNATURE)
        return PE_ARCHITECTURE_UNKNOWN;

    // First, naive, check based on the 'Magic' number in the Optional Header.
    PE_ARCHITECTURE architecture = (PE_ARCHITECTURE)pNtHd->OptionalHeader.Magic;

    // If the architecture is x86, there is still a possibility that the image is 'AnyCPU'
    if (architecture == PE_ARCHITECTURE_X86) {
        IMAGE_DATA_DIRECTORY comDirectory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
        if (comDirectory.Size) {
            IMAGE_COR20_HEADER *pClrHd = (IMAGE_COR20_HEADER*)GetOffsetFromRva(pDosHd, pNtHd, comDirectory.VirtualAddress);
            // Check to see if the CLR header contains the 32BITONLY flag, if not then the image is actually AnyCpu
            if ((pClrHd->Flags & COMIMAGE_FLAGS_32BITREQUIRED) == 0)
                architecture = PE_ARCHITECTURE_ANYCPU;
        }
    }

    return architecture;
}

The function accepts a pointer to an in-memory PE image (so you can choose your poison on how to get it their; memory-mapping or reading the whole thing into memory...whatever).

Is it possible to send an array with the Postman Chrome extension?

I tried all solution here and in other posts, but nothing helped.

The only answer helped me:
Adding [FromBody] attribute before decleration of parameter in function signature:

[Route("MyFunc")]        
public string MyFunc([FromBody] string[] obj)

Git error: "Please make sure you have the correct access rights and the repository exists"

An alternative problem may be your internet connection. Obvious maybe, but took me a few minutes to figure out my wifi was down :)

Angularjs $http.get().then and binding to a list

Actually you get promise on $http.get.

Try to use followed flow:

<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
    <span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
    <span>{{document.Name}}</span>
</li>

Where documents is your array.

$scope.documents = [];

$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
    result.data.forEach(function(val, i) { 
        $scope.documents.push(/* put data here*/);
    });
}, function(error) {
    alert(error.message);
});                       

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Start with the triangle...

    *
   **
  ***
 ****

representing 1+2+3+4 so far. Cut the triangle in half along one dimension...

     *
    **
  * **
 ** **

Rotate the smaller part 180 degrees, and stick it on top of the bigger part...

    **
    * 

     *
    **
    **
    **

Close the gap to get a rectangle.

At first sight this only works if the base of the rectangle has an even length - but if it has an odd length, you just cut the middle column in half - it still works with a half-unit-wide twice-as-tall (still integer area) strip on one side of your rectangle.

Whatever the base of the triangle, the width of your rectangle is (base / 2) and the height is (base + 1), giving ((base + 1) * base) / 2.

However, my base is your n-1, since the bubble sort compares a pair of items at a time, and therefore iterates over only (n-1) positions for the first loop.

How to set Navigation Drawer to be opened from right to left

Here is the documentation on the drawer and it appears that you can configure it to pull out from the left or right.

Drawer positioning and layout is controlled using the android:layout_gravity attribute on child views corresponding to which side of the view you want the drawer to emerge from: left or right. (Or start/end on platform versions that support layout direction.)

http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

The offending lines are the following:

MaxConnections=90
InitialConnections=80

You can increase the values to allow more connections.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

My first post... UDF I managed quickly to compile. Usage: Select 3D range as normal and enclose is into quotation marks like below...

=CountIf3D("'StartSheet:EndSheet'!G16:G878";"Criteria")

Advisably sheets to be adjacent to avoid unanticipated results.

Public Function CountIf3D(SheetstoCount As String, CriteriaToUse As Variant)

     Dim sStarSheet As String, sEndSheet As String, sAddress As String
     Dim lColonPos As Long, lExclaPos As Long, cnt As Long

    lColonPos = InStr(SheetstoCount, ":") 'Finding ':' separating sheets
    lExclaPos = InStr(SheetstoCount, "!") 'Finding '!' separating address from the sheets

    sStarSheet = Mid(SheetstoCount, 2, lColonPos - 2) 'Getting first sheet's name
    sEndSheet = Mid(SheetstoCount, lColonPos + 1, lExclaPos - lColonPos - 2) 'Getting last sheet's name

    sAddress = Mid(SheetstoCount, lExclaPos + 1, Len(SheetstoCount) - lExclaPos) 'Getting address

        cnt = 0
   For i = Sheets(sStarSheet).Index To Sheets(sEndSheet).Index
        cnt = cnt + Application.CountIf(Sheets(i).Range(sAddress), CriteriaToUse)
   Next

   CountIf3D = cnt

End Function

Logging request/response messages when using HttpClient

Network tracing also available for next objects (see article on msdn)

  • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
  • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
  • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
  • System.Net.Cache Some private and internal methods in System.Net.Cache.
  • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
  • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

Put next lines of code to the configuration file

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

what's data-reactid attribute in html?

data attributes are commonly used for a variety of interactions. Typically via javascript. They do not affect anything regarding site behavior and stand as a convenient method to pass data for whatever purpose needed. Here is an article that may clear things up:

http://ejohn.org/blog/html-5-data-attributes/

You can create a data attribute by prefixing data- to any standard attribute safe string (alphanumeric with no spaces or special characters). For example, data-id or in this case data-reactid

Git Clone from GitHub over https with two-factor authentication

1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:

$ git push
Username for 'https://github.com':            # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token

Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

How do you set the document title in React?

import React from 'react'
import ReactDOM from 'react-dom'


class Doc extends React.Component{
  componentDidMount(){
    document.title = "dfsdfsdfsd"
  }

  render(){
    return(
      <b> test </b>
    )
  }
}

ReactDOM.render(
  <Doc />,
  document.getElementById('container')
);

This works for me.

Edit: If you're using webpack-dev-server set inline to true

Codeigniter's `where` and `or_where`

You can change your code to this:

$where_au = "(library.available_until >= '{date('Y-m-d H:i:s)}' OR library.available_until = '00-00-00 00:00:00')";
$this->db
    ->select('*')
    ->from('library')
    ->where('library.rating >=', $form['slider'])
    ->where('library.votes >=', '1000')
    ->where('library.language !=', 'German')
    ->where($where_au)
    ->where('library.release_year >=', $year_start)
    ->where('library.release_year <=', $year_end)
    ->join('rating_repo', 'library.id = rating_repo.id');

Tip: to watch the generated query you can use

echo $this->db->last_query(); die();

Python: how can I check whether an object is of type datetime.date?

import datetime
d = datetime.date(2012, 9, 1)
print type(d) is datetime.date

> True

How do I obtain a Query Execution Plan in SQL Server?

Assuming you're using Microsoft SQL Server Management Studio

  • For Estimated Query Plan you can press Ctrl + L or the following button.

enter image description here

  • For Actual Query Plan, you can press Ctrl + M or the following button before executing query.

enter image description here

  • For Live Query Plan, (only in SSMS 2016) use the following button before executing query.

enter image description here

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

URL Encoding the data works as well for me

For example

var data = '<b>Hello</b>'

In Browser call encodeURIComponent(data) before posting

On Server call HttpUtility.UrlDecode(received_data) to decode

That way you can control exactly which fields area allowed to have html

Bootstrap 3 dropdown select

;(function ($) {
    $.fn.bootselect = function (options) {
        this.each(function () {
            var os = jQuery(this).find('option');
            var parent = this.parentElement;
            var css = jQuery(this).attr('class').split('input').join('btn').split('form-control').join('');
            var vHtml = jQuery(this).find('option[value="' + jQuery(this).val() + '"]').html();
            var html = '<div class="btn-group" role="group">' + '<button type="button" data-toggle="dropdown" value="1" class="btn btn-default ' + css + ' dropdown-toggle">' +
                vHtml + '<span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu">';
            var i = 0;
            while (i < os.length) {
                html += '<li><a href="#" data-value="' + jQuery(os[i]).val() + '" html-attr="' + jQuery(os[i]).html() + '">' + jQuery(os[i]).html() + '</a></li>';
                i++;
            }
            html += '</ul>' + '</div>';
            var that = this;
            jQuery(parent).append(html);
            jQuery(parent).find('ul.dropdown-menu > li > a').on('click', function () {
                jQuery(parent).find('button.btn').html(jQuery(this).html() + '<span class="caret"></span>');
                jQuery(that).find('option[value="' + jQuery(this).attr('data-value') + '"]')[0].selected = true;
                jQuery(that).trigger('change');
            });
            jQuery(this).hide();
        });
    };
}(jQuery));


jQuery('.bootstrap-select').bootselect();

Python, how to check if a result set is empty?

Notice: This is for MySQLdb module in Python.

For a SELECT statement, there shouldn't be an exception for an empty recordset. Just an empty list ([]) for cursor.fetchall() and None for cursor.fetchone().

For any other statement, e.g. INSERT or UPDATE, that doesn't return a recordset, you can neither call fetchall() nor fetchone() on the cursor. Otherwise, an exception will be raised.

There's one way to distinguish between the above two types of cursors:

def yield_data(cursor):
    while True:
        if cursor.description is None:
            # No recordset for INSERT, UPDATE, CREATE, etc
            pass
        else:
            # Recordset for SELECT, yield data
            yield cursor.fetchall()
            # Or yield column names with
            # yield [col[0] for col in cursor.description]

        # Go to the next recordset
        if not cursor.nextset():
            # End of recordsets
            return

How the int.TryParse actually works

Regex is compiled so for speed create it once and reuse it.
The new takes longer than the IsMatch.
This only checks for all digits.
It does not check for range.
If you need to test range then TryParse is the way to go.

private static Regex regexInt = new Regex("^\\d+$");
static bool CheckReg(string value)
{
    return regexInt.IsMatch(value);
}

Center image in div horizontally

I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example: http://jsfiddle.net/Tv9mG/

Django CSRF Cookie Not Set

Make sure your django session backend is configured properly in settings.py. Then try this,

class CustomMiddleware(object):
  def process_request(self,request:HttpRequest):
      get_token(request)

Add this middleware in settings.py under MIDDLEWARE_CLASSES or MIDDLEWARE depending on the django version

get_token - Returns the CSRF token required for a POST form. The token is an alphanumeric value. A new token is created if one is not already set.

Select2() is not a function

For newbies like me, who end up on this question: This error also happens if you attempt to call .select2() on an element retrieved using pure javascript and not using jQuery.

This fails with the "select2 is not a function" error:

document.getElementById('e9').select2();

This works:

$("#e9").select2();

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

Android Paint: .measureText() vs .getTextBounds()

Sorry for answering again on that question... I needed to embed the image.

I think the results @mice found are missleading. The observations might be correct for the font size of 60 but they turn much more different when the text is smaller. Eg. 10px. In that case the text is actually drawn BEYOND the bounds.

enter image description here

Sourcecode of the screenshot:

  @Override
  protected void onDraw( Canvas canvas ) {
    for( int i = 0; i < 20; i++ ) {
      int startSize = 10;
      int curSize = i + startSize;
      paint.setTextSize( curSize );
      String text = i + startSize + " - " + TEXT_SNIPPET;
      Rect bounds = new Rect();
      paint.getTextBounds( text, 0, text.length(), bounds );
      float top = STEP_DISTANCE * i + curSize;
      bounds.top += top;
      bounds.bottom += top;
      canvas.drawRect( bounds, bgPaint );
      canvas.drawText( text, 0, STEP_DISTANCE * i + curSize, paint );
    }
  }

Is there a method for String conversion to Title Case?

I had this problem and i searched for it then i made my own method using some java keywords just need to pass String variable as parameter and get output as proper titled String.

public class Main
{
  public static void main (String[]args)
  {
    String st = "pARVeEN sISHOsIYA";
    String mainn = getTitleCase (st);
      System.out.println (mainn);
  }


  public static String getTitleCase(String input)
  {
    StringBuilder titleCase = new StringBuilder (input.length());
    boolean hadSpace = false;
    for (char c:input.toCharArray ()){
        if(Character.isSpaceChar(c)){
            hadSpace = true;
            titleCase.append (c);
            continue;
        }
        if(hadSpace){
            hadSpace = false;
            c = Character.toUpperCase(c);
            titleCase.append (c);
        }else{
            c = Character.toLowerCase(c);
            titleCase.append (c);
        }
    }
    String temp=titleCase.toString ();
    StringBuilder titleCase1 = new StringBuilder (temp.length ());
    int num=1;
    for (char c:temp.toCharArray ())
        {   if(num==1)
            c = Character.toUpperCase(c);
            titleCase1.append (c);
            num=0;
        }
        return titleCase1.toString ();
    }
}

LINQ extension methods - Any() vs. Where() vs. Exists()

Just so you can find it next time, here is how you search for the enumerable Linq extensions. The methods are static methods of Enumerable, thus Enumerable.Any, Enumerable.Where and Enumerable.Exists.

As the third returns no usable result, I found that you meant List.Exists, thus:

I also recommend hookedonlinq.com as this is has very comprehensive and clear guides, as well clear explanations of the behavior of Linq methods in relation to deferness and lazyness.

What is a good pattern for using a Global Mutex in C#?

I want to make sure this is out there, because it's so hard to get right:

using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly
using System.Threading;                 //Mutex
using System.Security.AccessControl;    //MutexAccessRule
using System.Security.Principal;        //SecurityIdentifier

static void Main(string[] args)
{
    // get application GUID as defined in AssemblyInfo.cs
    string appGuid =
        ((GuidAttribute)Assembly.GetExecutingAssembly().
            GetCustomAttributes(typeof(GuidAttribute), false).
                GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

    // Need a place to store a return value in Mutex() constructor call
    bool createdNew;

    // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
    // edited by 'Marc' to work also on localized systems (don't use just "Everyone") 
    var allowEveryoneRule =
        new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
                                                   , null)
                           , MutexRights.FullControl
                           , AccessControlType.Allow
                           );
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

   // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
    using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
    {
        // edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                // edited by acidzombie24
                // mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access");
            }
            catch (AbandonedMutexException)
            {
                // Log the fact that the mutex was abandoned in another process,
                // it will still get acquired
                hasHandle = true;
            }

            // Perform your work here.
        }
        finally
        {
            // edited by acidzombie24, added if statement
            if(hasHandle)
                mutex.ReleaseMutex();
        }
    }
}

javascript popup alert on link click

Single line works just fine:

<a href="http://example.com/"
 onclick="return confirm('Please click on OK to continue.');">click me</a>

Adding another line with a different link on the same page works fine too:

<a href="http://stackoverflow.com/"
 onclick="return confirm('Click on another OK to continue.');">another link</a>

Examples for string find in Python

Try

myString = 'abcabc'
myString.find('a')

This will give you the index!!!

MySQL: Insert datetime into other datetime field

According to MySQL documentation, you should be able to just enclose that datetime string in single quotes, ('YYYY-MM-DD HH:MM:SS') and it should work. Look here: Date and Time Literals

So, in your case, the command should be as follows:

UPDATE products SET former_date='2011-12-18 13:17:17' WHERE id=1

How do I create my own URL protocol? (e.g. so://...)

This is different for each browser, in IE and windows you need to create what they call a pluggable protocol handler.

The basic steps are as follows:

  1. Implement the IInternetProtocol interface.
  2. Implement the IInternetProtocolRoot interface.
  3. Implement the IClassFactory interface.
  4. Optional. Implement the IInternetProtocolInfo interface. Support for the HTTP protocol is provided by the transaction handler.
  5. If IInternetProtocolInfo is implemented, provide support for PARSE_SECURITY_URL and PARSE_SECURITY_DOMAIN so the URL security zone manager can handle the security properly. Write the code for your protocol handler.
  6. Provide support for BINDF_NO_UI and BINDF_SILENTOPERATION.
  7. Add a subkey for your protocol handler in the registry under HKEY_CLASSES_ROOT\PROTOCOLS\Handler.
  8. Create a string value, CLSID, under the subkey and set the string to the CLSID of your protocol handler.

See About Asynchronous Pluggable Protocols on MSDN for more details on the windows side. There is also a sample in the windows SDK.

A quick google also showed this article on codeproject: http://www.codeproject.com/KB/IP/DataProtocol.aspx.

Finally, as a security guy I have to point out that this code needs to be battle hardened. It's at a high risk because to do it reliably you can't do it in managed code and have to do it in C++ (I suppose you could use VB6). You should consider whether you really need to do this and if you do, design it carefully and code it securely. An attacker can easily control the content that gets passed to you by simply including a link on a page. For example if you have a simple buffer overflow then nobody better do this: <a href="custom:foooo{insert long string for buffer overflow here}"> Click me for free porn</a>

Strongly consider using strsafe and the new secure CRT methods included in the VC8 and above compilers. See http://blogs.msdn.com/michael_howard/archive/2006/02/27/540123.aspx if you have no idea what I'm talking about.

Can I set a breakpoint on 'memory access' in GDB?

watch only breaks on write, rwatch let you break on read, and awatch let you break on read/write.

You can set read watchpoints on memory locations:

gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface

but one limitation applies to the rwatch and awatch commands; you can't use gdb variables in expressions:

gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.

So you have to expand them yourself:

gdb$ print $ebx 
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f

Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()

Edit: Oh, and by the way. You need either hardware or software support. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the can-use-hw-watchpoints environment setting.

gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Form onSubmit determine which submit button was pressed

<form onsubmit="alert(this.submitted); return false;">
    <input onclick="this.form.submitted=this.value;" type="submit" value="Yes" />
    <input onclick="this.form.submitted=this.value;" type="submit" value="No" />
</form>

jsfiddle for the same

How to draw border around a UILabel?

Here are some things you can do with UILabel and its borders.

enter image description here

Here is the code for those labels:

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!
    @IBOutlet weak var label5: UILabel!
    @IBOutlet weak var label6: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // label 1
        label1.layer.borderWidth = 1.0

        // label 2
        label2.layer.borderWidth = 5.0
        label2.layer.borderColor = UIColor.blue.cgColor

        // label 3
        label3.layer.borderWidth = 2.0
        label3.layer.cornerRadius = 8

        // label 4
        label4.backgroundColor = UIColor.cyan

        // label 5
        label5.backgroundColor = UIColor.red
        label5.layer.cornerRadius = 8
        label5.layer.masksToBounds = true

        // label 6
        label6.layer.borderWidth = 2.0
        label6.layer.cornerRadius = 8
        label6.backgroundColor = UIColor.yellow
        label6.layer.masksToBounds = true
    }
}

Note that in Swift there is no need to import QuartzCore.

See also

Change location of log4j.properties

Yes, define log4j.configuration property

java -Dlog4j.configuration=file:/path/to/log4j.properties myApp

Note, that property value must be a URL.

For more read section 'Default Initialization Procedure' in Log4j manual.

How do I redirect in expressjs while passing some context?

There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You'll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.

app.get('/category', function(req, res) {
  var string = encodeURIComponent('something that would break');
  res.redirect('/?valid=' + string);
});

You can snag that in your other route by getting the parameters sent by using req.query.

app.get('/', function(req, res) {
  var passedVariable = req.query.valid;
  // Do something with variable
});

For more dynamic way you can use the url core module to generate the query string for you:

const url = require('url');    
app.get('/category', function(req, res) {
    res.redirect(url.format({
       pathname:"/",
       query: {
          "a": 1,
          "b": 2,
          "valid":"your string here"
        }
     }));
 });

So if you want to redirect all req query string variables you can simply do

res.redirect(url.format({
       pathname:"/",
       query:req.query,
     });
 });

And if you are using Node >= 7.x you can also use the querystring core module

const querystring = require('querystring');    
app.get('/category', function(req, res) {
      const query = querystring.stringify({
          "a": 1,
          "b": 2,
          "valid":"your string here"
      });
      res.redirect('/?' + query);
 });

Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:

app.get('/category', function(req, res) {
  req.session.valid = true;
  res.redirect('/');
});

And later on after the redirect...

app.get('/', function(req, res) {
  var passedVariable = req.session.valid;
  req.session.valid = null; // resets session variable
  // Do something
});

There is also the option of using an old feature of Express, req.flash. Doing so in newer versions of Express will require you to use another library. Essentially it allows you to set up variables that will show up and reset the next time you go to a page. It's handy for showing errors to users, but again it's been removed by default. EDIT: Found a library that adds this functionality.

Hopefully that will give you a general idea how to pass information around in an Express application.

How to create string with multiple spaces in JavaScript

You can use the <pre> tag with innerHTML. The HTML <pre> element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written. If you don't want a different font, simply add pre as a selector in your CSS file and style it as desired.

Ex:

var a = '<pre>something        something</pre>';
document.body.innerHTML = a;

How do I download a package from apt-get without installing it?

Try

apt-get -d install <packages>

It is documented in man apt-get.

Just for clarification; the downloaded packages are located in the apt package cache at

/var/cache/apt/archives

How to run binary file in Linux

The volume it's on is mounted noexec.

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

How to remove "disabled" attribute using jQuery?

I think you are trying to toggle the disabled state, in witch case you should use this (from this question):

$(".inputDisabled").prop('disabled', function (_, val) { return ! val; });

Here is a working fiddle.

How to use 'find' to search for files created on a specific date?

It's two steps but I like to do it this way:

First create a file with a particular date/time. In this case, the file is 2008-10-01 at midnight

touch -t 0810010000 /tmp/t

Now we can find all files that are newer or older than the above file (going by file modified date. You can also use -anewer for accessed and -cnewer file status changed).

find / -newer /tmp/t
find / -not -newer /tmp/t

You could also look at files between certain dates by creating two files with touch

touch -t 0810010000 /tmp/t1
touch -t 0810011000 /tmp/t2

This will find files between the two dates & times

find / -newer /tmp/t1 -and -not -newer /tmp/t2

iterating through json object javascript

Here is my recursive approach:

function visit(object) {
    if (isIterable(object)) {
        forEachIn(object, function (accessor, child) {
            visit(child);
        });
    }
    else {
        var value = object;
        console.log(value);
    }
}

function forEachIn(iterable, functionRef) {
    for (var accessor in iterable) {
        functionRef(accessor, iterable[accessor]);
    }
}

function isIterable(element) {
    return isArray(element) || isObject(element);
}

function isArray(element) {
    return element.constructor == Array;
}

function isObject(element) {
    return element.constructor == Object;
}

How to display alt text for an image in chrome

Use title attribute instead of alt

<img
  height="90"
  width="90"
  src="http://www.google.com/intl/en_ALL/images/logos/images_logo_lg12.gif"
  title="Image Not Found"
/>

Listing files in a specific "folder" of a AWS S3 bucket

As other have already said, everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.

If you don't need objects which end with a '/' you can safely delete them e.g. via REST api or AWS Java SDK (I assume you have write access). You will not lose "nested files" (there no files, so you will not lose objects whose names are prefixed with the key you delete)

AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(new ProfileCredentialsProvider()).withRegion("region").build();
amazonS3.deleteObject(new DeleteObjectRequest("my-bucket", "users/<user-id>/contacts/<contact-id>/"));

Please note that I'm using ProfileCredentialsProvider so that my requests are not anonymous. Otherwise, you will not be able to delete an object. I have my AWS keep key stored in ~/.aws/credentials file.

What is the mouse down selector in CSS?

I figured out that this behaves like a mousedown event:

button:active:hover {}

How does cookie based authentication work?

I realize this is years late, but I thought I could expand on Conor's answer and add a little bit more to the discussion.

Can someone give me a step by step description of how cookie based authentication works? I've never done anything involving either authentication or cookies. What does the browser need to do? What does the server need to do? In what order? How do we keep things secure?

Step 1: Client > Signing up

Before anything else, the user has to sign up. The client posts a HTTP request to the server containing his/her username and password.

Step 2: Server > Handling sign up

The server receives this request and hashes the password before storing the username and password in your database. This way, if someone gains access to your database they won't see your users' actual passwords.

Step 3: Client > User login

Now your user logs in. He/she provides their username/password and again, this is posted as a HTTP request to the server.

Step 4: Server > Validating login

The server looks up the username in the database, hashes the supplied login password, and compares it to the previously hashed password in the database. If it doesn't check out, we may deny them access by sending a 401 status code and ending the request.

Step 5: Server > Generating access token

If everything checks out, we're going to create an access token, which uniquely identifies the user's session. Still in the server, we do two things with the access token:

  1. Store it in the database associated with that user
  2. Attach it to a response cookie to be returned to the client. Be sure to set an expiration date/time to limit the user's session

Henceforth, the cookies will be attached to every request (and response) made between the client and server.

Step 6: Client > Making page requests

Back on the client side, we are now logged in. Every time the client makes a request for a page that requires authorization (i.e. they need to be logged in), the server obtains the access token from the cookie and checks it against the one in the database associated with that user. If it checks out, access is granted.

This should get you started. Be sure to clear the cookies upon logout!

How can I print each command before executing?

set -x is fine.

Another way to print each executed command is to use trap with DEBUG. Put this line at the beginning of your script :

trap 'echo "# $BASH_COMMAND"' DEBUG

You can find a lot of other trap usages here.

Bootstrap NavBar with left, center or right aligned items

This is a dated question but I found an alternate solution to share right from the bootstrap github page. The documentation has not been updated and there are other questions on SO asking for the same solution albeit on slightly different questions. This solution is not specific to your case but as you can see the solution is the <div class="container"> right after <nav class="navbar navbar-default navbar-fixed-top"> but can also be replaced with <div class="container-fluid" as needed.

<!DOCTYPE html>
<html>

<head>
  <title>Navbar right padding broken </title>
  <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>

<body>
  <nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a href="#/" class="navbar-brand">Hello</a>
      </div>
      <div class="collapse navbar-collapse navbar-ex1-collapse">

        <ul class="nav navbar-nav navbar-right">
          <li>
            <div class="btn-group navbar-btn" role="group" aria-label="...">
              <button type="button" class="btn btn-default" data-toggle="modal" data-target="#modalLogin">Se connecter</button>
              <button type="button" class="btn btn-default" data-toggle="modal" data-target="#modalSignin">Créer un compte</button>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </nav>
</body>

</html>

The solution was found on a fiddle on this page: https://github.com/twbs/bootstrap/issues/18362

and is listed as a won't fix in V3.

How to Increase Import Size Limit in phpMyAdmin

Change the file phpmyadmin.conf on c:/wamp64/alias/phpmyadmin.conf

php_admin_value upload_max_filesize 512M
php_admin_value post_max_size 512M
php_admin_value max_execution_time 360
php_admin_value max_input_time 360

It's very important you increase the time to 5000 or higher, Thus, the process will not stop when you are uploading a large file.

That works for me.

How can I convert JSON to CSV?

Surprisingly, I found that none of the answers posted here so far correctly deal with all possible scenarios (e.g., nested dicts, nested lists, None values, etc).

This solution should work across all scenarios:

def flatten_json(json):
    def process_value(keys, value, flattened):
        if isinstance(value, dict):
            for key in value.keys():
                process_value(keys + [key], value[key], flattened)
        elif isinstance(value, list):
            for idx, v in enumerate(value):
                process_value(keys + [str(idx)], v, flattened)
        else:
            flattened['__'.join(keys)] = value

    flattened = {}
    for key in json.keys():
        process_value([key], json[key], flattened)
    return flattened

Python: How to get values of an array at certain index positions?

You can use index arrays, simply pass your ind_pos as an index argument as below:

a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])

print(a[ind_pos])
# [88,85,16]

Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).

Force youtube embed to start in 720p

Youtube doesn't support playback quality anymore

Youtube doesn't support playback quality anymore

How to calculate 1st and 3rd quartiles?

By using pandas:

df.time_diff.quantile([0.25,0.5,0.75])


Out[793]: 
0.25    0.483333
0.50    0.500000
0.75    0.516667
Name: time_diff, dtype: float64

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

What does '<?=' mean in PHP?

I hope it doesn't get deprecated. While writing <? blah code ?> is fairly unnecessary and confusable with XHTML, <?= isn't, for obvious reasons. Unfortunately I don't use it, because short_open_tag seems to be disabled more and more.

Update: I do use <?= again now, because it is enabled by default with PHP 5.4.0. See http://php.net/manual/en/language.basic-syntax.phptags.php

Why do people say that Ruby is slow?

People say that Ruby is slow because they compare Ruby programs to programs written in other languages. Maybe the programs you write don't need to be faster. Maybe for the programs you write Ruby isn't the bottleneck that's slowing things down.

Ruby 2.1 compared to Javascript V8

Ruby 2.1 compared to ordinary Lua

Ruby 2.1 compared to Python 3

How can I make a CSS table fit the screen width?

If the table content is too wide (as in this example), there's nothing you can do other than alter the content to make it possible for the browser to show it in a more narrow format. Contrary to the earlier answers, setting width to 100% will have absolutely no effect if the content is too wide (as that link, and this one, demonstrate). Browsers already try to keep tables within the left and right margins if they can, and only resort to a horizontal scrollbar if they can't.

Some ways you can alter content to make a table more narrow:

  • Reduce the number of columns (perhaps breaking one megalithic table into multiple independent tables).
  • If you're using CSS white-space: nowrap on any of the content (or the old nowrap attribute, &nbsp;, a nobr element, etc.), see if you can live without them so the browser has the option of wrapping that content to keep the width down.
  • If you're using really wide margins, padding, borders, etc., try reducing their size (but I'm sure you thought of that).

If the table is too wide but you don't see a good reason for it (the content isn't that wide, etc.), you'll have to provide more information about how you're styling the table, the surrounding elements, etc. Again, by default the browser will avoid the scrollbar if it can.

How to programmatically disable page scrolling with jQuery

try this

$('#element').on('scroll touchmove mousewheel', function(e){
  e.preventDefault();
  e.stopPropagation();
  return false;
})

In Java, how do I call a base class's method from the overriding method in a derived class?

If u r using these methods for initialization then use constructors of class A and pass super keyword inside the constructor of class B.

Or if you want to call a method of super class from the subclass method then you have to use super keyword inside the subclass method like : super.myMethod();

Modify request parameter with servlet filter

Try request.setAttribute("param",value);. It worked fine for me.

Please find this code sample:

private void sanitizePrice(ServletRequest request){
        if(request.getParameterValues ("price") !=  null){
            String price[] = request.getParameterValues ("price");

            for(int i=0;i<price.length;i++){
                price[i] = price[i].replaceAll("[^\\dA-Za-z0-9- ]", "").trim();
                System.out.println(price[i]);
            }
            request.setAttribute("price", price);
            //request.getParameter("numOfBooks").re
        }
    }

Calculating days between two dates with Java

When I run your program, it doesn't even get me to the point where I can enter the second date.

This is simpler and less error prone.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test001 {

    public static void main(String[] args) throws Exception {

        BufferedReader br = null;

        br = new BufferedReader(new InputStreamReader(System.in));
        SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy");

        System.out.println("Insert first date : ");
        Date dt1 = sdf.parse(br.readLine().trim());

        System.out.println("Insert second date : ");
        Date dt2 = sdf.parse(br.readLine().trim());

        long diff = dt2.getTime() - dt1.getTime();

        System.out.println("Days: " + diff / 1000L / 60L / 60L / 24L);

        if (br != null) {
            br.close();
        }
    }
}

How to reject in async/await syntax?

You can create a wrapper function that takes in a promise and returns an array with data if no error and the error if there was an error.

function safePromise(promise) {
  return promise.then(data => [ data ]).catch(error => [ null, error ]);
}

Use it like this in ES7 and in an async function:

async function checkItem() {
  const [ item, error ] = await safePromise(getItem(id));
  if (error) { return null; } // handle error and return
  return item; // no error so safe to use item
}

Remove an entire column from a data.frame in R

To remove one or more columns by name, when the column names are known (as opposed to being determined at run-time), I like the subset() syntax. E.g. for the data-frame

df <- data.frame(a=1:3, d=2:4, c=3:5, b=4:6)

to remove just the a column you could do

Data <- subset( Data, select = -a )

and to remove the b and d columns you could do

Data <- subset( Data, select = -c(d, b ) )

You can remove all columns between d and b with:

Data <- subset( Data, select = -c( d : b )

As I said above, this syntax works only when the column names are known. It won't work when say the column names are determined programmatically (i.e. assigned to a variable). I'll reproduce this Warning from the ?subset documentation:

Warning:

This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like '[', and in particular the non-standard evaluation of argument 'subset' can have unanticipated consequences.

Bootstrap - dropdown menu not working?

you are missing the "btn btn-navbar" section. For example:

        <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </a>

Take a look to navbar documentation in:

Twitter Bootstrap

Show message box in case of exception

If you want just the summary of the exception use:

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

If you want to see the whole stack trace (usually better for debugging) use:

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

Another method I sometime use is:

    private DoSomthing(int arg1, int arg2, out string errorMessage)
    {
         int result ;
        errorMessage = String.Empty;
        try 
        {           
            //do stuff
            int result = 42;
        }
        catch (Exception ex)
        {

            errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
            result = -1;
        }
        return result;
    }

And In your form you will have something like:

    string ErrorMessage;
    int result = DoSomthing(1, 2, out ErrorMessage);
    if (!String.IsNullOrEmpty(ErrorMessage))
    {
        MessageBox.Show(ErrorMessage);
    }

How to validate domain credentials?

I`m using the following code to validate credentials. The method shown below will confirm if the credentials are correct and if not wether the password is expired or needs change.

I`ve been looking for something like this for ages... So i hope this helps someone!

using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;

namespace User
{
    public static class UserValidation
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(string principal, string authority, string password, LogonTypes logonType, LogonProviders logonProvider, out IntPtr token);
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr handle);
        enum LogonProviders : uint
        {
            Default = 0, // default for platform (use this!)
            WinNT35,     // sends smoke signals to authority
            WinNT40,     // uses NTLM
            WinNT50      // negotiates Kerb or NTLM
        }
        enum LogonTypes : uint
        {
            Interactive = 2,
            Network = 3,
            Batch = 4,
            Service = 5,
            Unlock = 7,
            NetworkCleartext = 8,
            NewCredentials = 9
        }
        public  const int ERROR_PASSWORD_MUST_CHANGE = 1907;
        public  const int ERROR_LOGON_FAILURE = 1326;
        public  const int ERROR_ACCOUNT_RESTRICTION = 1327;
        public  const int ERROR_ACCOUNT_DISABLED = 1331;
        public  const int ERROR_INVALID_LOGON_HOURS = 1328;
        public  const int ERROR_NO_LOGON_SERVERS = 1311;
        public  const int ERROR_INVALID_WORKSTATION = 1329;
        public  const int ERROR_ACCOUNT_LOCKED_OUT = 1909;      //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!
        public  const int ERROR_ACCOUNT_EXPIRED = 1793;
        public  const int ERROR_PASSWORD_EXPIRED = 1330;

        public static int CheckUserLogon(string username, string password, string domain_fqdn)
        {
            int errorCode = 0;
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain_fqdn, "ADMIN_USER", "PASSWORD"))
            {
                if (!pc.ValidateCredentials(username, password))
                {
                    IntPtr token = new IntPtr();
                    try
                    {
                        if (!LogonUser(username, domain_fqdn, password, LogonTypes.Network, LogonProviders.Default, out token))
                        {
                            errorCode = Marshal.GetLastWin32Error();
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        CloseHandle(token);
                    }
                }
            }
            return errorCode;
        }
    }

Saving excel worksheet to CSV files with filename+worksheet name using VB

I think this is what you want...

Sub SaveWorksheetsAsCsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

Dim CurrentWorkbook As String
Dim CurrentFormat As Long

CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "H:\test\"

For Each WS In Application.ActiveWorkbook.Worksheets
    WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next

Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
'  about overwriting the original file.

End Sub

How do I declare a 2d array in C++ using new?

If you want an 2d array of integers, which elements are allocated sequentially in memory, you must declare it like

int (*intPtr)[n] = new int[x][n]

where instead of x you can write any dimension, but n must be the same in two places. Example

int (*intPtr)[8] = new int[75][8];
intPtr[5][5] = 6;
cout<<intPtr[0][45]<<endl;

must print 6.

CSS display:inline property with list-style-image: property on <li> tags

You want style image and Nav with float to each other then use like this

ol.widgets ul
{
list-style-image:url('some-img.gif');
}
ol.widgets ul li
{
float:left;
}

ImportError: DLL load failed: The specified module could not be found

To make it short, it means that you lacked some "dependencies" for the libraries you wanted to use. Before trying to use any kind of library, first it is suggested to look up whether it needs another library in python "family". What do I mean?

Downloading "dlls" is something that I avoid. I had the same problem with another library "kivy". The problem occurred when I wanted to use Python 3.4v instead of 3.5 Everything was working correctly in 3.5 but I just wanted to use the stable version for kivy which is 3.4 as they officially "advise". So, I switched to 3.4 but then I had the very same "dll" error saying lots of things are missing. So I checked the website and learned that I needed to install extra "dependencies" from the official website of kivy, then the problem got solved.

How to achieve ripple animation using support library?

sometimes will b usable this line on any layout or components.

 android:background="?attr/selectableItemBackground"

Like as.

 <RelativeLayout
                android:id="@+id/relative_ticket_checkin"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="?attr/selectableItemBackground">

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

Shows the Computer Name, Use a Button to call it

Dim strHostName As String

    strHostName = System.Net.Dns.GetHostName().

    MsgBox(strHostName)

Shows the User Name, Use a Button to call it

If TypeOf My.User.CurrentPrincipal Is Security.Principal.WindowsPrincipal Then

        Dim parts() As String = Split(My.User.Name, "\")

        Dim username As String = parts(1)

        MsgBox(username)

   End If

For IP Address its little complicated, But I try to explain as much as I can. First write the next code, before Form1_Load but after import section

Public Class Form1

Dim mem As String

Private Sub GetIPAddress()

    Dim strHostName As String
    Dim strIPAddress As String
    strHostName = System.Net.Dns.GetHostName()
    strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()

    mem = strIPAddress
    MessageBox.Show("IP Address: " & strIPAddress)

End Sub

Then in Form1_Load Section just call it

GetIPAddress()

Result: On form load it will show a msgbox along with the IP address, for put into Label1.text or some where else play with the code.

How to save and extract session data in codeigniter

initialize the Session class in the constructor of controller using

$this->load->library('session');

for example :

 function __construct()
   {
    parent::__construct();
    $this->load->model('user','',TRUE);
    $this->load->model('user_activity','',TRUE);
    $this->load->library('session');
   }

How to convert answer into two decimal point

Ran into this problem today and I wrote a function for it. In my particular case, I needed to make sure all values were at least 0 (hence the "LT0" name) and were rounded to two decimal places.

        Private Function LT0(ByVal Input As Decimal, Optional ByVal Precision As Int16 = 2) As Decimal

            ' returns 0 for all values less than 0, the decimal rounded to (Precision) decimal places otherwise.
            If Input < 0 Then Input = 0
            if Precision < 0 then Precision = 0 ' just in case someone does something stupid.
            Return Decimal.Round(Input, Precision) ' this is the line everyone's probably looking for.

        End Function

Make Font Awesome icons in a circle?

I like Dave Everitt's answer with the « line-height » but it only works by specifying the « height » and then we have to add « !important » to line-height ...

.cercle {
    font-size: 2em;
    width: 2em;
    height: 2em;
    text-align: center;
    line-height: 2em!important;
    background: #666;
    color: #fff;
    border-radius: 2em;
}

Eclipse copy/paste entire line keyboard shortcut

You have to turn off the graphics hot keys that flip the screen. If you're on Windows, you need to right click on the Windows desktop and select "Graphics Properties..." (or something similar depending on your version of Windows). This will bring up a screen where you can manage graphics and display options, look for a place where you can disable hot keys, sometimes it's hidden under something like "Options and Support". Turn off the CTRL + ALT + ? and CTRL + ALT + ? hotkeys (alternatively you can just disable all graphics hot keys if you're not using them).

Get integer value of the current year in Java

In my case none of the above is worked. So After trying lot of solutions i found below one and it worked for me

import java.util.Scanner;
import java.util.Date;

public class Practice
{   
    public static void main(String[] args)
    {
        Date d=new Date();  
        int year=d.getYear();
        int currentYear=year+1900;    

        System.out.println(currentYear);

    }

}

JavaScript chop/slice/trim off last character in string

The easiest method is to use the slice method of the string, which allows negative positions (corresponding to offsets from the end of the string):

const s = "your string";
const withoutLastFourChars = s.slice(0, -4);

If you needed something more general to remove everything after (and including) the last underscore, you could do the following (so long as s is guaranteed to contain at least one underscore):

_x000D_
_x000D_
const s = "your_string";_x000D_
const withoutLastChunk = s.slice(0, s.lastIndexOf("_"));_x000D_
console.log(withoutLastChunk);
_x000D_
_x000D_
_x000D_

Angular 4 setting selected option in Dropdown

Lets see an example with Select control
binded to: $scope.cboPais,
source: $scope.geoPaises

HTML

<select 
  ng-model="cboPais"  
  ng-options="item.strPais for item in geoPaises"
  ></select>

JavaScript

$http.get(strUrl2).success(function (response) {
  if (response.length > 0) {
    $scope.geoPaises = response; //Data source
    nIndex = indexOfUnsortedArray(response, 'iPais', default_values.iPais); //array index of default value, using a custom function to search
    if (nIndex >= 0) {
      $scope.cboPais = response[nIndex]; //if index of array was found
    } else {
      $scope.cboPais = response[0]; //select the first element of array
    }
    $scope.geo_getDepartamentos();
  }
}

How to revert initial git commit?

I wonder why "amend" is not suggest and have been crossed out by @damkrat, as amend appears to me as just the right way to resolve the most efficiently the underlying problem of fixing the wrong commit since there is no purpose of having no initial commit. As some stressed out you should only modify "public" branch like master if no one has clone your repo...

git add <your different stuff>
git commit --amend --author="author name <[email protected]>"-m "new message"

How can I find the current OS in Python?

https://docs.python.org/library/os.html

To complement Greg's post, if you're on a posix system, which includes MacOS, Linux, Unix, etc. you can use os.uname() to get a better feel for what kind of system it is.

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

How do I create an Android Spinner as a popup?

If you want to show it as a full screen popup, then you don't even need an xml layout. Here's how do do it in Kotlin.

 val inputArray: Array<String> = arrayOf("Item 1","Item 2")
                val alt_bld =  AlertDialog.Builder(context);
                alt_bld.setTitle("Items:")
                alt_bld.setSingleChoiceItems(inputArray, -1) { dialog, which ->
                    if(which == 0){
                        //Item 1 Selected
                    }
                    else if(which == 1){
                        //Item 2 Selected
                    }
                    dialog.dismiss();

                }

                val alert11 = alt_bld.create()
                alert11.show()

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Play an audio file using jQuery when a button is clicked

What about:

_x000D_
_x000D_
$('#play').click(function() {_x000D_
  const audio = new Audio("https://freesound.org/data/previews/501/501690_1661766-lq.mp3");_x000D_
  audio.play();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Best way to parse command-line parameters?

I like the clean look of this code... gleaned from a discussion here: http://www.scala-lang.org/old/node/4380

object ArgParser {
  val usage = """
Usage: parser [-v] [-f file] [-s sopt] ...
Where: -v   Run verbosely
       -f F Set input file to F
       -s S Set Show option to S
"""

  var filename: String = ""
  var showme: String = ""
  var debug: Boolean = false
  val unknown = "(^-[^\\s])".r

  val pf: PartialFunction[List[String], List[String]] = {
    case "-v" :: tail => debug = true; tail
    case "-f" :: (arg: String) :: tail => filename = arg; tail
    case "-s" :: (arg: String) :: tail => showme = arg; tail
    case unknown(bad) :: tail => die("unknown argument " + bad + "\n" + usage)
  }

  def main(args: Array[String]) {
    // if there are required args:
    if (args.length == 0) die()
    val arglist = args.toList
    val remainingopts = parseArgs(arglist,pf)

    println("debug=" + debug)
    println("showme=" + showme)
    println("filename=" + filename)
    println("remainingopts=" + remainingopts)
  }

  def parseArgs(args: List[String], pf: PartialFunction[List[String], List[String]]): List[String] = args match {
    case Nil => Nil
    case _ => if (pf isDefinedAt args) parseArgs(pf(args),pf) else args.head :: parseArgs(args.tail,pf)
  }

  def die(msg: String = usage) = {
    println(msg)
    sys.exit(1)
  }

}

Missing maven .m2 folder

If I'm right, it's just because you are missing the cd command. Try c:\Users\Jonathan\cd .m2/.

Password encryption at client side

You need a library that can encrypt your input on client side and transfer it to the server in encrypted form.

You can use following libs:

  • jCryption. Client-Server asymmetric encryption over Javascript

Update after 3 years (2013):

Update after 4 years (2014):

How to access the php.ini file in godaddy shared hosting linux

For some hosting accounts, I'm on Ultimate Classic Linux, the file name you need to use is .user.ini.

INNER JOIN vs INNER JOIN (SELECT . FROM)

There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it

--Version 2 
SELECT p.Name, s.OrderQty 
FROM Product p 
INNER JOIN 
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s 
on p.ProductID = s.ProdctId 

Run a command shell in jenkins

I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.

Error :

Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessImpl.create(Native Method)
    at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
    at hudson.Proc$LocalProc.<init>(Proc.java:250)
    at hudson.Proc$LocalProc.<init>(Proc.java:219)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
    at hudson.Launcher$ProcStarter.start(Launcher.java:455)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
    at hudson.model.Build$BuildExecution.build(Build.java:206)
    at hudson.model.Build$BuildExecution.doRun(Build.java:163)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
    at hudson.model.Run.execute(Run.java:1853)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Solution :

1 - Install Cygwin and note the directory where it gets installed.

It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.

2 - Tell Jenkins where sh.exe is located.

Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.

That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.

limit text length in php and provide 'Read more' link

<?php $string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
if (strlen($string) > 25) {
$trimstring = substr($string, 0, 25). ' <a href="#">readmore...</a>';
} else {
$trimstring = $string;
}
echo $trimstring;
//Output : Lorem Ipsum is simply dum [readmore...][1]
?>

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"

I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.

class ProgressBar extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            id: this.props.id    <--- ID set from <ProgressBar id="Progress1"/>
        }
    }        
}

As mentioned in some of the answers above you absolutely can use document.querySelector inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:

render () {
    const id = this.state.id
    return (<div id={"progress-bar-" + id}></div>)
}

Then you can elsewhere do a normal javascript querySelector call like this:

let element = document.querySelector('#progress-bar-Progress1')

Shell Script: Execute a python program from within a shell script

This works for me:

  1. Create a new shell file job. So let's say: touch job.sh and add command to run python script (you can even add command line arguments to that python, I usually predefine my command line arguments).

    chmod +x job.sh

  2. Inside job.sh add the following py files, let's say:

    python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file.py"

    python_file1.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file1.py"

Output of job.sh should look like this:

Done with python_file.py

Done with python_file1.py

I use this usually when I have to run multiple python files with different arguments, pre defined.

Note: Just a quick heads up on what's going on here:

python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "completed with python_file.py" . 

  • Here shell script will run the file python_file.py and add multiple command-line arguments at run time to the python file.
  • This does not necessarily means, you have to pass command line arguments as well.
  • You can just use it like: python python_file.py, plain and simple. Next up, the >> will print and store the output of this .py file in the testpy-output.txt file.
  • && is a logical operator that will run only after the above is executed successfully and as an optional echo "completed with python_file.py" will be echoed on to your cli/terminal at run time.

Find the number of columns in a table

Its been little late but please take it from me...

In the editor(New Query) by select the database object it can be a table too, if we use the Shortcut Key Alt+F1 we will get all the information of the object and I think will solve your problem as well.

Display HTML form values in same page after submit using Ajax

<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>

<!--Insert more code here-->


<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">

Next time you ask a question here, include more detail and what you have tried.

Perform debounce in React.js

Lots of good info here already, but to be succinct. This works for me...

import React, {Component} from 'react';
import _ from 'lodash';

class MyComponent extends Component{
      constructor(props){
        super(props);
        this.handleChange = _.debounce(this.handleChange.bind(this),700);
      }; 

How to pass command-line arguments to a PowerShell ps1 file

Maybe you can wrap the PowerShell invocation in a .bat file like so:

rem ps.bat
@echo off
powershell.exe -command "%*"

If you then placed this file under a folder in your PATH, you could call PowerShell scripts like this:

ps foo 1 2 3

Quoting can get a little messy, though:

ps write-host """hello from cmd!""" -foregroundcolor green

How to convert integer to string in C?

That's because itoa isn't a standard function. Try snprintf instead.

char str[LEN];
snprintf(str, LEN, "%d", 42);

How to determine if a String has non-alphanumeric characters?

If you can use the Apache Commons library, then Commons-Lang StringUtils has a method called isAlphanumeric() that does what you're looking for.

Submit Button Image

You have to remove the borders and add a background image on the input.

.imgClass { 
    background-image: url(path to image) no-repeat;
    width: 186px;
    height: 53px;
    border: none;
}

It should be good now, normally.

Multiple ping script in Python

Thank you so much for this. I have modified it to work with Windows. I have also put a low timeout so, the IP's that have no return will not sit and wait for 5 seconds each. This is from hochl source code.

import subprocess
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(200, 240):
                ip="10.2.7.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "inactive"
                else:
                        print ip, "active"

Just change the ip= for your scheme and the xrange for the hosts.

How to split strings into text and number?

without using regex, using isdigit() built-in function, only works if starting part is text and latter part is number

def text_num_split(item):
    for index, letter in enumerate(item, 0):
        if letter.isdigit():
            return [item[:index],item[index:]]

print(text_num_split("foobar12345"))

OUTPUT :

['foobar', '12345']

Float a div in top right corner without overlapping sibling header

section {
    position: relative;
    width: 50%;
    border: 1px solid;
}
h1 {
    display: inline;
}
div {
    position: relative;
    float:right;
    top: 0;
    right: 0;

}

Bootstrap navbar Active State not working

Bootstrap 4 requires you to target the li item for active classes. In order to do that you have to find the parent of the a. The 'hitbox' of the a is as big as the li but due to bubbeling of event in JS it will give you back the a event. So you have to manually add it to its parent.

  //set active navigation after click
  $(".nav-link").on("click", (event) => {
    $(".navbar-nav").find(".active").removeClass('active');
    $(event.target).parent().addClass('active');
  });

How to write log file in c#?

public static void WriteLog(string strLog)
    {
        StreamWriter log;
        FileStream fileStream = null;
        DirectoryInfo logDirInfo = null;
        FileInfo logFileInfo;

        string logFilePath = "C:\\Logs\\";
        logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";           
        logFileInfo = new FileInfo(logFilePath);
        logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
        if (!logDirInfo.Exists) logDirInfo.Create();
        if (!logFileInfo.Exists)
        {
            fileStream = logFileInfo.Create();
        }
        else
        {
            fileStream = new FileStream(logFilePath, FileMode.Append);
        }
        log = new StreamWriter(fileStream);
        log.WriteLine(strLog);
        log.Close();
    }   

Refer Link: blogspot.in

Woocommerce get products

<?php
$args     = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args ); 
?>

This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products

How to convert float value to integer in php?

There is always intval() - Not sure if this is what you were looking for...

example: -

$floatValue = 4.5;
echo intval($floatValue);    // Returns 4

It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.

Here is some documentation for this: - http://php.net/manual/en/function.intval.php

Peak signal detection in realtime timeseries data

Here is a (non-idiomatic) Scala version of the smoothed z-score algorithm:

/**
  * Smoothed zero-score alogrithm shamelessly copied from https://stackoverflow.com/a/22640362/6029703
  * Uses a rolling mean and a rolling deviation (separate) to identify peaks in a vector
  *
  * @param y - The input vector to analyze
  * @param lag - The lag of the moving window (i.e. how big the window is)
  * @param threshold - The z-score at which the algorithm signals (i.e. how many standard deviations away from the moving mean a peak (or signal) is)
  * @param influence - The influence (between 0 and 1) of new signals on the mean and standard deviation (how much a peak (or signal) should affect other values near it)
  * @return - The calculated averages (avgFilter) and deviations (stdFilter), and the signals (signals)
  */
private def smoothedZScore(y: Seq[Double], lag: Int, threshold: Double, influence: Double): Seq[Int] = {
  val stats = new SummaryStatistics()

  // the results (peaks, 1 or -1) of our algorithm
  val signals = mutable.ArrayBuffer.fill(y.length)(0)

  // filter out the signals (peaks) from our original list (using influence arg)
  val filteredY = y.to[mutable.ArrayBuffer]

  // the current average of the rolling window
  val avgFilter = mutable.ArrayBuffer.fill(y.length)(0d)

  // the current standard deviation of the rolling window
  val stdFilter = mutable.ArrayBuffer.fill(y.length)(0d)

  // init avgFilter and stdFilter
  y.take(lag).foreach(s => stats.addValue(s))

  avgFilter(lag - 1) = stats.getMean
  stdFilter(lag - 1) = Math.sqrt(stats.getPopulationVariance) // getStandardDeviation() uses sample variance (not what we want)

  // loop input starting at end of rolling window
  y.zipWithIndex.slice(lag, y.length - 1).foreach {
    case (s: Double, i: Int) =>
      // if the distance between the current value and average is enough standard deviations (threshold) away
      if (Math.abs(s - avgFilter(i - 1)) > threshold * stdFilter(i - 1)) {
        // this is a signal (i.e. peak), determine if it is a positive or negative signal
        signals(i) = if (s > avgFilter(i - 1)) 1 else -1
        // filter this signal out using influence
        filteredY(i) = (influence * s) + ((1 - influence) * filteredY(i - 1))
      } else {
        // ensure this signal remains a zero
        signals(i) = 0
        // ensure this value is not filtered
        filteredY(i) = s
      }

      // update rolling average and deviation
      stats.clear()
      filteredY.slice(i - lag, i).foreach(s => stats.addValue(s))
      avgFilter(i) = stats.getMean
      stdFilter(i) = Math.sqrt(stats.getPopulationVariance) // getStandardDeviation() uses sample variance (not what we want)
  }

  println(y.length)
  println(signals.length)
  println(signals)

  signals.zipWithIndex.foreach {
    case(x: Int, idx: Int) =>
      if (x == 1) {
        println(idx + " " + y(idx))
      }
  }

  val data =
    y.zipWithIndex.map { case (s: Double, i: Int) => Map("x" -> i, "y" -> s, "name" -> "y", "row" -> "data") } ++
    avgFilter.zipWithIndex.map { case (s: Double, i: Int) => Map("x" -> i, "y" -> s, "name" -> "avgFilter", "row" -> "data") } ++
    avgFilter.zipWithIndex.map { case (s: Double, i: Int) => Map("x" -> i, "y" -> (s - threshold * stdFilter(i)), "name" -> "lower", "row" -> "data") } ++
    avgFilter.zipWithIndex.map { case (s: Double, i: Int) => Map("x" -> i, "y" -> (s + threshold * stdFilter(i)), "name" -> "upper", "row" -> "data") } ++
    signals.zipWithIndex.map { case (s: Int, i: Int) => Map("x" -> i, "y" -> s, "name" -> "signal", "row" -> "signal") }

  Vegas("Smoothed Z")
    .withData(data)
    .mark(Line)
    .encodeX("x", Quant)
    .encodeY("y", Quant)
    .encodeColor(
      field="name",
      dataType=Nominal
    )
    .encodeRow("row", Ordinal)
    .show

  return signals
}

Here's a test that returns the same results as the Python and Groovy versions:

val y = List(1d, 1d, 1.1d, 1d, 0.9d, 1d, 1d, 1.1d, 1d, 0.9d, 1d, 1.1d, 1d, 1d, 0.9d, 1d, 1d, 1.1d, 1d, 1d,
  1d, 1d, 1.1d, 0.9d, 1d, 1.1d, 1d, 1d, 0.9d, 1d, 1.1d, 1d, 1d, 1.1d, 1d, 0.8d, 0.9d, 1d, 1.2d, 0.9d, 1d,
  1d, 1.1d, 1.2d, 1d, 1.5d, 1d, 3d, 2d, 5d, 3d, 2d, 1d, 1d, 1d, 0.9d, 1d,
  1d, 3d, 2.6d, 4d, 3d, 3.2d, 2d, 1d, 1d, 0.8d, 4d, 4d, 2d, 2.5d, 1d, 1d, 1d)

val lag = 30
val threshold = 5d
val influence = 0d

smoothedZScore(y, lag, threshold, influence)

vegas chart of result

Gist here

Fill DataTable from SQL Server database

Try with following:

public DataTable fillDataTable(string table)
    {
        string query = "SELECT * FROM dstut.dbo." +table;

        SqlConnection sqlConn = new SqlConnection(conSTR);
        sqlConn.Open();
        SqlCommand cmd = new SqlCommand(query, sqlConn);
        SqlDataAdapter da=new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        sqlConn.Close();
        return dt;
    }

Hope it is helpful.

How to grep (search) committed code in the Git history

I took Jeet's answer and adapted it to Windows (thanks to this answer):

FOR /F %x IN ('"git rev-list --all"') DO @git grep <regex> %x > out.txt

Note that for me, for some reason, the actual commit that deleted this regex did not appear in the output of the command, but rather one commit prior to it.

How to check whether Kafka Server is running?

The good option is to use AdminClient as below before starting to produce or consume the messages

private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;           
 try (AdminClient client = AdminClient.create(properties)) {
            client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
        } catch (ExecutionException ex) {
            LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
            return;
        }

How to check if a character in a string is a digit or letter

This is the way how to check whether a given character is alphabet or not

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    char c = sc.next().charAt(0); 
    if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
         System.out.println(c + " is an alphabet.");
    else
        System.out.println(c + " is not an alphabet.");
}

Character reading from file in Python

There are a few points to consider.

A \u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:

>>> text = u'‘'
>>> print repr(text)
u'\u2018'

Now if you simply want to print the unicode string prettily, just use unicode's encode method:

>>> text = u'I don\u2018t like this'
>>> print text.encode('utf-8')
I don‘t like this

To make sure that every line from any file would be read as unicode, you'd better use the codecs.open function instead of just open, which allows you to specify file's encoding:

>>> import codecs
>>> f1 = codecs.open(file1, "r", "utf-8")
>>> text = f1.read()
>>> print type(text)
<type 'unicode'>
>>> print text.encode('utf-8')
I don‘t like this

Check if Cookie Exists

Sometimes you still need to know if Cookie exists in Response. Then you can check if cookie key exists:

HttpContext.Current.Response.Cookies.AllKeys.Contains("myCookie")

More info can be found here.

In my case I had to modify Response Cookie in Application_EndRequest method in Global.asax. If Cookie doesn't exist I don't touch it:

string name = "myCookie";
HttpContext context = ((HttpApplication)sender).Context;
HttpCookie cookie = null;

if (context.Response.Cookies.AllKeys.Contains(name))
{
    cookie = context.Response.Cookies[name];
}

if (cookie != null)
{
    // update response cookie
}

Command to get time in milliseconds

Perl can be used for this, even on exotic platforms like AIX. Example:

#!/usr/bin/perl -w

use strict;
use Time::HiRes qw(gettimeofday);

my ($t_sec, $usec) = gettimeofday ();
my $msec= int ($usec/1000);

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
    localtime ($t_sec);

printf "%04d-%02d-%02d %02d:%02d:%02d %03d\n",
    1900+$year, 1+$mon, $mday, $hour, $min, $sec, $msec;

The remote server returned an error: (403) Forbidden

In my case I had to add both 'user agent' and 'default credentials = True'. I know this is pretty old, still wanted to share. Hope this helps. Below code is in powershell, but it should help others who are using c#.

[System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest]::Create($uri)
$req.UserAgent = "BlackHole"
$req.UseDefaultCredentials = $true

How to use *ngIf else?

You can Use <ng-container> and <ng-template> for Achieve This

<ng-container *ngIf="isValid; then template1 else template2"></ng-container>

<ng-template #template1>
     <div>Template 1 contains</div>
</ng-template>

<ng-template #template2>
     <div>Template 2 contains </div>
</ng-template>

You can find the Stackblitz Live demo below

live demo

Hope This will helps ... !!!

MAX(DATE) - SQL ORACLE

select * from 
  (SELECT MEMBSHIP_ID
   FROM user_payment WHERE user_id=1
   order by paym_date desc) 
where rownum=1;

How to move table from one tablespace to another in oracle 11g

Use sql from sql:

spool output of this to a file:

select 'alter index '||owner||'.'||index_name||' rebuild tablespace TO_TABLESPACE_NAME;' from all_indexes where owner='OWNERNAME';

spoolfile will have something like this:

alter index OWNER.PK_INDEX rebuild tablespace CORRECT_TS_NAME;

Swift - How to detect orientation changes

To get the correct orientation on app start you have to check it in viewDidLayoutSubviews(). Other methods described here won't work.

Here's an example how to do it:

var mFirstStart = true

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if (mFirstStart) {
        mFirstStart = false
        detectOrientation()
    }
}

func detectOrientation() {
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
        // do your stuff here for landscape
    } else {
        print("Portrait")
        // do your stuff here for portrait
    }
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    detectOrientation()
}

This will work always, on app first start, and if rotating while the app is running.

Deprecation warning in Moment.js - Not in a recognized ISO format

This answer is to give a better understanding of this warning

Deprecation warning is caused when you use moment to create time object, var today = moment();.

If this warning is okay with you then I have a simpler method.

Don't use date object from js use moment instead. For example use moment() to get the current date.

Or convert the js date object to moment date. You can simply do that specifying the format of your js date object.

ie, moment("js date", "js date format");

eg:

moment("2014 04 25", "YYYY MM DD");

(BUT YOU CAN ONLY USE THIS METHOD UNTIL IT'S DEPRECIATED, this may be depreciated from moment in the future)

How to set java.net.preferIPv4Stack=true at runtime?

Another approach, if you're desperate and don't have access to (a) the code or (b) the command line, then you can use environment variables:

http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSG-Desktop/html/plugin.html.

Specifically for java web start set the environment variable:

JAVAWS_VM_ARGS

and for applets:

_JPI_VM_OPTIONS

e.g.

_JPI_VM_OPTIONS=-Djava.net.preferIPv4Stack=true

Additionally, under Windows global options (for general Java applications) can be set in the Java control plan page under the "Java" tab.

How can I "reset" an Arduino board?

I had this issue as well. I tried the above methods and none seemed to work, however something that did work (somehow, not sure if it was just a freak thing or it is actually a way to do it) was:

  1. Unplug USB from the Arduino
  2. Press and hold the reset button
  3. Plug in USB and power up
  4. Continue holding and upload the sketch. Once it's done uploading, release the reset button.

How to access POST form fields

For Express 4.1 and above

As most of the answers are using to Express, bodyParser, connect; where multipart is deprecated. There is a secure way to send post multipart objects easily.

Multer can be used as replacement for connect.multipart().

To install the package

$ npm install multer

Load it in your app:

var multer = require('multer');

And then, add it in the middleware stack along with the other form parsing middleware.

app.use(express.json());
app.use(express.urlencoded());
app.use(multer({ dest: './uploads/' }));

connect.json() handles application/json

connect.urlencoded() handles application/x-www-form-urlencoded

multer() handles multipart/form-data

Using Node.js require vs. ES6 import/export

As of right now ES6 import, export is always compiled to CommonJS, so there is no benefit using one or other. Although usage of ES6 is recommended since it should be advantageous when native support from browsers released. The reason being, you can import partials from one file while with CommonJS you have to require all of the file.

ES6 → import, export default, export

CommonJS → require, module.exports, exports.foo

Below is common usage of those.

ES6 export default

// hello.js
function hello() {
  return 'hello'
}
export default hello

// app.js
import hello from './hello'
hello() // returns hello

ES6 export multiple and import multiple

// hello.js
function hello1() {
  return 'hello1'
}
function hello2() {
  return 'hello2'
}
export { hello1, hello2 }

// app.js
import { hello1, hello2 } from './hello'
hello1()  // returns hello1
hello2()  // returns hello2

CommonJS module.exports

// hello.js
function hello() {
  return 'hello'
}
module.exports = hello

// app.js
const hello = require('./hello')
hello()   // returns hello

CommonJS module.exports multiple

// hello.js
function hello1() {
  return 'hello1'
}
function hello2() {
  return 'hello2'
}
module.exports = {
  hello1,
  hello2
}

// app.js
const hello = require('./hello')
hello.hello1()   // returns hello1
hello.hello2()   // returns hello2

How do I concatenate strings in Swift?

In Swift 5 apple has introduces Raw Strings using # symbols.

Example:

print(#"My name is "XXX" and I'm "28"."#)
let name = "XXX"
print(#"My name is \#(name)."#)

symbol # is necessary after \. A regular \(name) will be interpreted as characters in the string.

Including non-Python files with setup.py

It is 2019, and here is what is working - despite advice here and there, what I found on the internet halfway documented is using setuptools_scm, passed as options to setuptools.setup. This will include any data files that are versioned on your VCS, be it git or any other, to the wheel package, and will make "pip install" from the git repository to bring those files along.

So, I just added these two lines to the setup call on "setup.py". No extra installs or import required:

    setup_requires=['setuptools_scm'],
    include_package_data=True,

No need to manually list package_data, or in a MANIFEST.in file - if it is versioned, it is included in the package. The docs on "setuptools_scm" put emphasis on creating a version number from the commit position, and disregard the really important part of adding the data files. (I can't care less if my intermediate wheel file is named "*0.2.2.dev45+g3495a1f" or will use the hardcoded version number "0.3.0dev0" I've typed in - but leaving crucial files for the program to work behind is somewhat important)

Mocking Logger and LoggerFactory with PowerMock and Mockito

Somewhat late to the party - I was doing something similar and needed some pointers and ended up here. Taking no credit - I took all of the code from Brice but got the "zero interactions" than Cengiz got.

Using guidance from what jheriks amd Joseph Lust had put I think I know why - I had my object under test as a field and newed it up in a @Before unlike Brice. Then the actual logger was not the mock but a real class init'd as jhriks suggested...

I would normally do this for my object under test so as to get a fresh object for each test. When I moved the field to a local and newed it in the test it ran ok. However, if I tried a second test it was not the mock in my test but the mock from the first test and I got the zero interactions again.

When I put the creation of the mock in the @BeforeClass the logger in the object under test is always the mock but see the note below for the problems with this...

Class under test

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClassWithSomeLogging  {

    private static final Logger LOG = LoggerFactory.getLogger(MyClassWithSomeLogging.class);

    public void doStuff(boolean b) {
        if(b) {
            LOG.info("true");
        } else {
            LOG.info("false");
        }

    }
}

Test

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.powermock.api.mockito.PowerMockito.when;


@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyClassWithSomeLoggingTest {

    private static Logger mockLOG;

    @BeforeClass
    public static void setup() {
        mockStatic(LoggerFactory.class);
        mockLOG = mock(Logger.class);
        when(LoggerFactory.getLogger(any(Class.class))).thenReturn(mockLOG);
    }

    @Test
    public void testIt() {
        MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
        myClassWithSomeLogging.doStuff(true);

        verify(mockLOG, times(1)).info("true");
    }

    @Test
    public void testIt2() {
        MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
        myClassWithSomeLogging.doStuff(false);

        verify(mockLOG, times(1)).info("false");
    }

    @AfterClass
    public static void verifyStatic() {
        verify(mockLOG, times(1)).info("true");
        verify(mockLOG, times(1)).info("false");
        verify(mockLOG, times(2)).info(anyString());
    }
}

Note

If you have two tests with the same expectation I had to do the verify in the @AfterClass as the invocations on the static are stacked up - verify(mockLOG, times(2)).info("true"); - rather than times(1) in each test as the second test would fail saying there where 2 invocation of this. This is pretty pants but I couldn't find a way to clear the invocations. I'd like to know if anyone can think of a way round this....

Disable button in jQuery

Try this

function disable(i){
    $("#rbutton_"+i).attr("disabled",true);
}

Set EditText cursor color

After a lot of time spent trying all these technique in a Dialog, I finally had this idea : attach the theme to the Dialog itself and not to the TextInputLayout.

<style name="AppTheme_Dialog" parent="Theme.AppCompat.Dialog">

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorWhite</item>
    <item name="colorAccent">@color/colorPrimary</item>

</style>

inside onCreate :

public class myDialog extends Dialog {

private Activity activity;
private someVars;

public PopupFeedBack(Activity activity){
    super(activity, R.style.AppTheme_Dialog);
    setContentView(R.layout.myView);
    ....}}

cheers :)

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

Both answers given worked for the problem I stated -- Thanks!

In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.

Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.

Should I use Java's String.format() if performance is important?

I wrote a small class to test which has the better performance of the two and + comes ahead of format. by a factor of 5 to 6. Try it your self

import java.io.*;
import java.util.Date;

public class StringTest{

    public static void main( String[] args ){
    int i = 0;
    long prev_time = System.currentTimeMillis();
    long time;

    for( i = 0; i< 100000; i++){
        String s = "Blah" + i + "Blah";
    }
    time = System.currentTimeMillis() - prev_time;

    System.out.println("Time after for loop " + time);

    prev_time = System.currentTimeMillis();
    for( i = 0; i<100000; i++){
        String s = String.format("Blah %d Blah", i);
    }
    time = System.currentTimeMillis() - prev_time;
    System.out.println("Time after for loop " + time);

    }
}

Running the above for different N shows that both behave linearly, but String.format is 5-30 times slower.

The reason is that in the current implementation String.format first parses the input with regular expressions and then fills in the parameters. Concatenation with plus, on the other hand, gets optimized by javac (not by the JIT) and uses StringBuilder.append directly.

Runtime comparison

Angular 2 router.navigate

_x000D_
_x000D_
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
  _x000D_
  private router = ActivatedRoute;_x000D_
_x000D_
    constructor(r: ActivatedRoute) {_x000D_
        this.router =r;_x000D_
    }_x000D_
_x000D_
onSuccess() {_x000D_
     this.router.navigate(['/user_invitation'],_x000D_
         {queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
    this.route_x000D_
        .queryParams_x000D_
        .subscribe(params => {_x000D_
            let code = params['code'];_x000D_
            let userEmail = params['email'];_x000D_
        });_x000D_
}
_x000D_
_x000D_
_x000D_

Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html

Delete branches in Bitbucket

Try this command, it will purge all branches that have been merged to the develop branch.

for i in `git branch -r --merged origin/develop| grep origin | grep -v '>' \
   | grep -v master | grep -v develop | sed -E "s|^ *origin/||g"`; \
do \
   git push origin $i --delete; \
done

JavaScript: SyntaxError: missing ) after argument list

You have an extra closing } in your function.

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        }        // <== remove this brace
    }, false);
};

You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.

Telnet is not recognized as internal or external command

If your Windows 7 machine is a member of an AD, or if you have UAC enabled, or if security policies are in effect, telnet more often than not must be run as an admin. The easiest way to do this is as follows

  1. Create a shortcut that calls cmd.exe

  2. Go to the shortcut's properties

  3. Click on the Advanced button

  4. Check the "Run as an administrator" checkbox

    After these steps you're all set and telnet should work now.

Count number of occurrences of a pattern in a file (even on same line)

Try this:

grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c

Sample:

grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
  6  SMTP connect from unknown [188.190.118.90]
 54  SMTP connect from unknown [62.193.131.114]
  3  SMTP connect from unknown [91.222.51.253]

How to add a 'or' condition in #ifdef

I am really OCD about maintaining strict column limits, and not a fan of "\" line continuation because you can't put a comment after it, so here is my method.

//|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|//
#ifdef  CONDITION_01             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_02             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_03             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef              TEMP_MACRO   //|       |//
//|-  --  --  --  --  --  --  --  --  --  -|//

printf("[IF_CONDITION:(1|2|3)]\n");

//|-  --  --  --  --  --  --  --  --  --  -|//
#endif                           //|       |//
#undef              TEMP_MACRO   //|       |//
//|________________________________________|//

In Bash, how do I add a string after each line in a file?

Sed is a little ugly, you could do it elegantly like so:

hendry@i7 tmp$ cat foo 
bar
candy
car
hendry@i7 tmp$ for i in `cat foo`; do echo ${i}bar; done
barbar
candybar
carbar

Console.log(); How to & Debugging javascript

Breakpoints and especially conditional breakpoints are your friends.

Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)

Send json post using php

use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.

How to use protractor to check if an element is visible?

 element(by.className('your-class-name')).isDisplayed().then(function (isVisible) {
if (isVisible) {
    // element is visible
} else {
    // element is not visible
}
}).catch(function(err){
console.log("Element is not found");
})

How to disable XDebug

I ran into a similar issue. Sometimes, you wont find xdebug.so in php.ini. In which case, execute phpinfo() in a php file and check for Additional .ini files parsed. Here you'll see more ini files. One of these will be xdebug's ini file. Just remove (or rename) this file, restart apache, and this extension will be removed.

Clear an input field with Reactjs?

Let me assume that you have done the 'this' binding of 'sendThru' function.

The below functions clears the input fields when the method is triggered.

sendThru() {
    this.inputTitle.value = "";
    this.inputEntry.value = "";
}

Refs can be written as inline function expression:

ref={el => this.inputTitle = el}

where el refers to the component.

When refs are written like above, React sees a different function object each time so on every update, ref will be called with null immediately before it's called with the component instance.

Read more about it here.

How can I pass data from Flask to JavaScript in a template?

<script>
    const geocodeArr = JSON.parse('{{ geocode | tojson }}');
    console.log(geocodeArr);
</script>

This uses jinja2 to turn the geocode tuple into a json string, and then the javascript JSON.parse turns that into a javascript array.

How to find the index of an element in an array in Java?

Simplest solution:

Convert array to list and you can get position of an element.

List<String> abcd  = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");

Other solution, you can iterator array:

int position = 0;
for (String obj : yourArray) {
    if (obj.equals("abcd") {
    return position;
    }
    position += 1;
} 

//OR
for (int i = 0; i < yourArray.length; i++) {
    if (obj.equals("abcd") {
       return i;
    }
}

Angular-Material DateTime Picker Component?

Unfortunately, the answer to your question of whether there is official Material support for selecting the time is "No", but it's currently an open issue on the official Material2 GitHub repo: https://github.com/angular/material2/issues/5648

Hopefully this changes soon, in the mean time, you'll have to fight with the 3rd-party ones you've already discovered. There are a few people in that GitHub issue that provide their self-made workarounds that you can try.

What is a "callback" in C and how are they implemented?

Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event() and data pointers to a framework function watch_events() (for example). When an event happens, your function is called with your data and some event-specific data.

Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.

What is a NoReverseMatch error, and how do I fix it?

It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Make .gitignore ignore everything except a few files

I have Jquery and Angular from bower. Bower installed them in

/public_html/bower_components/jquery/dist/bunch-of-jquery-files
/public_html/bower_components/jquery/src/bunch-of-jquery-source-files
/public_html/bower_components/angular/angular-files

The minimized jquery is inside the dist directory and angular is inside angular directory. I only needed minimized files to be commited to github. Some tampering with .gitignore and this is what I managed to conjure...

/public_html/bower_components/jquery/*
!public_html/bower_components/jquery/dist
/public_html/bower_components/jquery/dist/*
!public_html/bower_components/jquery/dist/jquery.min.js
/public_html/bower_components/angular/*
!public_html/bower_components/angular/angular.min.js

Hope someone could find this useful.

How to check if a registry value exists using C#?

public bool ValueExists(RegistryKey Key, string Value)
{
   try
   {
       return Key.GetValue(Value) != null;
   }
   catch
   {
       return false;
   }
}

This simple function will return true only if a value is found but it is not null, else will return false if the value exists but it is null or the value doesn't exists in the key.


USAGE for your question:

if (ValueExists(winLogonKey, "Start")
{
    // The values exists
}
else
{
    // The values does not exists
}

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

bundle install returns "Could not locate Gemfile"

I had this problem on Ubuntu 18.04. I updated the gem

sudo gem install rails
sudo gem install jekyll
sudo gem install jekyll bundler
cd ~/desiredFolder
jekyll new <foldername>
cd <foldername> OR 
bundle init
bundle install
bundle add jekyll
bundle exec jekyll serve

All worked and goto your browser just go to http://127.0.0.1:4000/ and it really should be running

MSVCP140.dll missing

Your friend's PC is missing the runtime support DLLs for your program:

Convert datetime to valid JavaScript date

You can use moment.js for that, it will convert DateTime object into valid Javascript formated date:

   moment(DateOfBirth).format('DD-MMM-YYYY'); // put format as you want 

   Output: 28-Apr-1993

Hope it will help you :)

Detect Windows version in .net

First solution

To make sure you get the right version with Environment.OSVersion you should add an app.manifest using Visual Studio and uncomment following supportedOS tags:

  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- A list of the Windows versions that this application has been tested on
           and is designed to work with. Uncomment the appropriate elements
           and Windows will automatically select the most compatible environment. -->

      <!-- Windows Vista -->
      <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />

      <!-- Windows 7 -->
      <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />

      <!-- Windows 8 -->
      <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />

      <!-- Windows 8.1 -->
      <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />

      <!-- Windows 10 -->
      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />

    </application>
  </compatibility>

Then in your code you can use Environment.OSVersion like this:

var version = System.Environment.OSVersion;
Console.WriteLine(version);

Example

For instance in my machine (Windows 10.0 Build 18362.476) result would be like this which is incorrect:

Microsoft Windows NT 6.2.9200.0

By adding app.manifest and uncomment those tags I will get the right version number:

Microsoft Windows NT 10.0.18362.0

Alternative solution

If you don't like adding app.manifest to your project, you can use OSDescription which is available since .NET Framework 4.7.1 and .NET Core 1.0.

string description = RuntimeInformation.OSDescription;

Note: Don't forget to add following using statement at top of your file.

using System.Runtime.InteropServices;

You can read more about it and supported platforms here.

Passing data to a bootstrap modal

Here is a cleaner way to do it if you are using Bootstrap 3.2.0.

Link HTML

<a href="#my_modal" data-toggle="modal" data-book-id="my_id_value">Open Modal</a>

Modal JavaScript

//triggered when modal is about to be shown
$('#my_modal').on('show.bs.modal', function(e) {

    //get data-id attribute of the clicked element
    var bookId = $(e.relatedTarget).data('book-id');

    //populate the textbox
    $(e.currentTarget).find('input[name="bookId"]').val(bookId);
});

http://jsfiddle.net/k7FC2/

SVG rounded corner

You have explicitly set your stroke-linejoin to round but your stroke-width to 0, so of course you're not going to see rounded corners if you have no stroke to round.

Here's a modified example with rounded corners made through strokes:
http://jsfiddle.net/8uxqK/1/

<path d="M64.5 45.5 82.5 45.5 82.5 64.5 64.5 64.5 z"
      stroke-width="5"
      stroke-linejoin="round"
      stroke="#808600"
      fill="#a0a700" />

Otherwise—if you need an actual rounded shape fill and not just a rounded fatty stroke—you must do what @Jlange says and make an actual rounded shape.

How can I selectively merge or pick changes from another branch in Git?

While some of these answers are pretty good, I feel like none actually answered the OP's original constraint: selecting particular files from particular branches. This solution does that, but it may be tedious if there are many files.

Let’s say you have the master, exp1, and exp2 branches. You want to merge one file from each of the experimental branches into master. I would do something like this:

git checkout master
git checkout exp1 path/to/file_a
git checkout exp2 path/to/file_b

# Save these files as a stash
git stash

# Merge stash with master
git merge stash

This will give you in-file diffs for each of the files you want. Nothing more. Nothing less. It's useful you have radically different file changes between versions --in my case, changing an application from Ruby on Rails 2 to Ruby on Rails 3.

This will merge files, but it does a smart merge. I wasn't able to figure out how to use this method to get in-file diff information (maybe it still will for extreme differences. Annoying small things like whitespace get merged back in unless you use the -s recursive -X ignore-all-space option)

Find all controls in WPF Window by type

Here is yet another, compact version, with the generics syntax:

    public static IEnumerable<T> FindLogicalChildren<T>(DependencyObject obj) where T : DependencyObject
    {
        if (obj != null) {
            if (obj is T)
                yield return obj as T;

            foreach (DependencyObject child in LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>()) 
                foreach (T c in FindLogicalChildren<T>(child)) 
                    yield return c;
        }
    }

Python script to do something at the same time every day

APScheduler might be what you are after.

from datetime import date
from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def my_job(text):
    print text

# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])

# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])

https://apscheduler.readthedocs.io/en/latest/

You can just get it to schedule another run by building that into the function you are scheduling.

Sublime Text 2 - Show file navigation in sidebar

Both of the previous answers from Matt York and Cyberbolt are right.

Basic idea is here that you want to get some kind of File explorer in Sublime.

Approach:

1) With File -> New Folder -> Click on Desired folder and Hit Open you will get new popup window in sublime which for me is very annoying

2) I use second option which is drag'n'drop from nautilus (a.k.a. Files) window. Simply drag'n'drop your file you want to explore from nautilus to sublime sidebar. That way you stay in the same window and everything is cool.

Don't forget to enable View -> Sidebar -> Show Sidebar and drag'n'drop there from nautilus and of course run it with root privleges. It works like charm

What is the difference between T(n) and O(n)?

Theta is a shorthand way of referring to a special situtation where the big O and Omega are the same.

Thus, if one claims The Theta is expression q, then they are also necessarily claiming that Big O is expression q and Omega is expression q.


Rough analogy:

If: Theta claims, "That animal has 5 legs." then it follows that: Big O is true ("That animal has less than or equal to 5 legs.") and Omega is true("That animal has more than or equal to 5 legs.")

It's only a rough analogy because the expressions aren't necessarily specific numbers, but instead functions of varying orders of magnitude such as log(n), n, n^2, (etc.).