Programs & Examples On #Enum map

`EnumMap` is optimized Map implementation exclusively for Enum keys.

What is the `zero` value for time.Time in Go?

The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC See http://play.golang.org/p/vTidOlmb9P

How to check the version of GitLab?

You can access the version through a URL, the web GUI, and the ReST API.

Via a URL

An HTML page displaying the version can be displayed in a browser at https://your-gitlab-url/help. The version is displayed only if you are signed in.

Via a menu in the web GUI

If you do not care to type this URL, you can also access the same HTML page from a menu in the GitLab web GUI:

In GitLab 11 and later

  1. Log in to GitLab
  2. Click on the ? drop down menu in the upper right. Select Help.
  3. The GitLab version appears at the top of the page

In earlier versions, like GitLab 9

  1. Log in to GitLab
  2. Click on the three lines drop down menu in the upper left. Select Help.
  3. And then the version appears at the top of the page

Via the ReST API

Log in as any user, select the user icon in the upper right of the screen. Select Settings > Access Tokens. Create a personal access token and copy it to your clipboard.

In a Linux shell, use curl to access the GitLab version:

curl --header "PRIVATE-TOKEN: personal-access-token" your-gitlab-url/api/v4/version

Node.js global variables

Use a global namespace like global.MYAPI = {}:

global.MYAPI._ = require('underscore')

All other posters talk about the bad pattern involved. So leaving that discussion aside, the best way to have a variable defined globally (OP's question) is through namespaces.

Tip: Development Using Namespaces

In Flask, What is request.args and how is it used?

It has some interesting behaviour in some cases that is good to be aware of:

from werkzeug.datastructures import MultiDict

d = MultiDict([("ex1", ""), ("ex2", None)])

d.get("ex1", "alternive")
# returns: ''

d.get("ex2", "alternative")
# returns no visible output of any kind
# It is returning literally None, so if you do:
d.get("ex2", "alternative") is None
# it returns: True

d.get("ex3", "alternative")
# returns: 'alternative'

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

Get page title with Selenium WebDriver using Java

In java you can do some thing like:

if(driver.getTitle().contains("some expected text"))
    //Pass
    System.out.println("Page title contains \"some expected text\" ");
else
    //Fail
    System.out.println("Page title doesn't contains \"some expected text\" ");

Get week of year in JavaScript like in PHP

now = new Date();
today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
firstOfYear = new Date(now.getFullYear(), 0, 1);
numOfWeek = Math.ceil((((today - firstOfYear) / 86400000)-1)/7);

Convert timestamp long to normal date format

I tried this and worked for me.

Date = (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds

C# if/then directives for debug vs release

DEBUG/_DEBUG should be defined in VS already.

Remove the #define DEBUG in your code. Set preprocessors in the build configuration for that specific build.

The reason it prints "Mode=Debug" is because of your #define and then skips the elif.

The right way to check is:

#if DEBUG
    Console.WriteLine("Mode=Debug"); 
#else
    Console.WriteLine("Mode=Release"); 
#endif

Don't check for RELEASE.

is there a css hack for safari only NOT chrome?

Step 1: use https://modernizr.com/

Step 2: use the html class .regions to select only Safari

a { color: blue; }
html.regions a { color: green; }

Modernizr will add html classes to the DOM based on what the current browser supports. Safari supports regions http://caniuse.com/#feat=css-regions whereas other browsers do not (yet anyway). This method is also very effective in selecting different versions of IE. May the force be with you.

How to replace list item in best way

Or, building on Rusian L.'s suggestion, if the item you're searching for can be in the list more than once::

[Extension()]
public void ReplaceAll<T>(List<T> input, T search, T replace)
{
    int i = 0;
    do {
        i = input.FindIndex(i, s => EqualityComparer<T>.Default.Equals(s, search));

        if (i > -1) {
            FileSystem.input(i) = replace;
            continue;
        }

        break;  
    } while (true);
}

How to check whether a str(variable) is empty or not?

{
test_str1 = "" 
test_str2 = "  "
  
# checking if string is empty 
print ("The zero length string without spaces is empty ? : ", end = "") 
if(len(test_str1) == 0): 
    print ("Yes") 
else : 
    print ("No") 
  
# prints No  
print ("The zero length string with just spaces is empty ? : ", end = "") 
if(len(test_str2) == 0): 
    print ("Yes") 
else : 
    print ("No") 
}

How to filter by object property in angularJS

The documentation has the complete answer. Anyway this is how it is done:

<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>

will filter only age in data array and true is for exact match.

For deep filtering,

<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>

The $ is a special property for deep filter and the true is for exact match like above.

Difference between /res and /assets directories

I know this is old, but just to make it clear, there is an explanation of each in the official android documentation:

from http://developer.android.com/tools/projects/index.html

assets/

This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.

res/raw/

For arbitrary raw asset files. Saving asset files here instead of in the assets/ directory only differs in the way that you access them. These files are processed by aapt and must be referenced from the application using a resource identifier in the R class. For example, this is a good place for media, such as MP3 or Ogg files.

SQLiteDatabase.query method

db.query(
        TABLE_NAME,
        new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
        TABLE_ROW_ID + "=" + rowID,
        null, null, null, null, null
);

TABLE_ROW_ID + "=" + rowID, here = is the where clause. To select all values you will have to give all column names:

or you can use a raw query like this 
db.rawQuery("SELECT * FROM permissions_table WHERE name = 'Comics' ", null);

and here is a good tutorial for database.

jQuery select child element by class with unknown path

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector) is the fastest and most efficient way to do this.

How do I check if a SQL Server text column is empty?

ISNULL(
case textcolum1
    WHEN '' THEN NULL
    ELSE textcolum1
END 
,textcolum2) textcolum1

Android Studio rendering problems

I have solved the Problem by changing style.xml

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
     <!-- Customize your theme here. -->
</style>

this was an awesom solution.

Get checkbox values using checkbox name using jquery

If you like to get a list of all values of checked checkboxes (e.g. to send them as a list in one AJAX call to the server), you could get that list with:

var list = $("input[name='bla[]']:checked").map(function () {
    return this.value;
}).get();

How do you do a deep copy of an object in .NET?

    public static object CopyObject(object input)
    {
        if (input != null)
        {
            object result = Activator.CreateInstance(input.GetType());
            foreach (FieldInfo field in input.GetType().GetFields(Consts.AppConsts.FullBindingList))
            {
                if (field.FieldType.GetInterface("IList", false) == null)
                {
                    field.SetValue(result, field.GetValue(input));
                }
                else
                {
                    IList listObject = (IList)field.GetValue(result);
                    if (listObject != null)
                    {
                        foreach (object item in ((IList)field.GetValue(input)))
                        {
                            listObject.Add(CopyObject(item));
                        }
                    }
                }
            }
            return result;
        }
        else
        {
            return null;
        }
    }

This way is a few times faster than BinarySerialization AND this does not require the [Serializable] attribute.

Angular 6 Material mat-select change method removed

I have this issue today with mat-option-group. The thing which solved me the problem is using in other provided event of mat-select : valueChange

I put here a little code for understanding :

<mat-form-field >
  <mat-label>Filter By</mat-label>
  <mat-select  panelClass="" #choosedValue (valueChange)="doSomething1(choosedValue.value)"> <!-- (valueChange)="doSomething1(choosedValue.value)" instead of (change) or other event-->

    <mat-option >-- None --</mat-option>
      <mat-optgroup  *ngFor="let group of filterData" [label]="group.viewValue"
                    style = "background-color: #0c5460">
        <mat-option *ngFor="let option of group.options" [value]="option.value">
          {{option.viewValue}}
        </mat-option>
      </mat-optgroup>
  </mat-select>
</mat-form-field>

Mat Version:

"@angular/material": "^6.4.7",

How to read from a file or STDIN in Bash?

Code ${1:-/dev/stdin} will just understand first argument, so, how about this.

ARGS='$*'
if [ -z "$*" ]; then
  ARGS='-'
fi
eval "cat -- $ARGS" | while read line
do
   echo "$line"
done

Android Call an method from another class

In Class1:

Class2 inst = new Class2();
inst.UpdateEmployee();

How to create full compressed tar file using Python?

To build a .tar.gz (aka .tgz) for an entire directory tree:

import tarfile
import os.path

def make_tarfile(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))

This will create a gzipped tar archive containing a single top-level folder with the same name and contents as source_dir.

Locating child nodes of WebElements in selenium

According to JavaDocs, you can do this:

WebElement input = divA.findElement(By.xpath(".//input"));

How can I ask in xpath for "the div-tag that contains a span with the text 'hello world'"?

WebElement elem = driver.findElement(By.xpath("//div[span[text()='hello world']]"));

The XPath spec is a suprisingly good read on this.

How do I load a file into the python console?

If your path environment variable contains Python (eg. C:\Python27\) you can run your py file simply from Windows command line (cmd). Howto here.

Access properties file programmatically with Spring?

Please use the below code in your spring configuration file to load the file from class path of your application

 <context:property-placeholder
    ignore-unresolvable="true" ignore-resource-not-found="false" location="classpath:property-file-name" />

Is there a limit to the length of a GET request?

The specification does not limit the length of an HTTP Get request but the different browsers implement their own limitations. For example Internet Explorer has a limitation implemented at 2083 characters.

jQuery: Scroll down page a set increment (in pixels) on click?

Pure js solution for newcomers or anyone else.

var scrollAmount = 150;
var element = document.getElementById("elem");

element.addEventListener("click", scrollPage);

function scrollPage() {
    var currentPositionOfPage = window.scrollY;
    window.scrollTo(0, currentPositionOfPage + scrollAmount);
}

How to reset Django admin password?

This is very good question.

python manage.py changepassword user_name

Example :-

python manage.py changepassword mickey

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

How do you use variables in a simple PostgreSQL script?

You can use:

\set list '''foobar'''
SELECT * FROM dbo.PubLists WHERE name = :list;

That will do

How can I get the current page name in WordPress?

Show the title before the loop starts:

$page_title = $wp_query->post->post_title;

MySql : Grant read only options?

If there is any single privilege that stands for ALL READ operations on database.

It depends on how you define "all read."

"Reading" from tables and views is the SELECT privilege. If that's what you mean by "all read" then yes:

GRANT SELECT ON *.* TO 'username'@'host_or_wildcard' IDENTIFIED BY 'password';

However, it sounds like you mean an ability to "see" everything, to "look but not touch." So, here are the other kinds of reading that come to mind:

"Reading" the definition of views is the SHOW VIEW privilege.

"Reading" the list of currently-executing queries by other users is the PROCESS privilege.

"Reading" the current replication state is the REPLICATION CLIENT privilege.

Note that any or all of these might expose more information than you intend to expose, depending on the nature of the user in question.

If that's the reading you want to do, you can combine any of those (or any other of the available privileges) in a single GRANT statement.

GRANT SELECT, SHOW VIEW, PROCESS, REPLICATION CLIENT ON *.* TO ...

However, there is no single privilege that grants some subset of other privileges, which is what it sounds like you are asking.

If you are doing things manually and looking for an easier way to go about this without needing to remember the exact grant you typically make for a certain class of user, you can look up the statement to regenerate a comparable user's grants, and change it around to create a new user with similar privileges:

mysql> SHOW GRANTS FOR 'not_leet'@'localhost';
+------------------------------------------------------------------------------------------------------------------------------------+
| Grants for not_leet@localhost                                                                                                      |
+------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, REPLICATION CLIENT ON *.* TO 'not_leet'@'localhost' IDENTIFIED BY PASSWORD '*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' |
+------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Changing 'not_leet' and 'localhost' to match the new user you want to add, along with the password, will result in a reusable GRANT statement to create a new user.

Of, if you want a single operation to set up and grant the limited set of privileges to users, and perhaps remove any unmerited privileges, that can be done by creating a stored procedure that encapsulates everything that you want to do. Within the body of the procedure, you'd build the GRANT statement with dynamic SQL and/or directly manipulate the grant tables themselves.

In this recent question on Database Administrators, the poster wanted the ability for an unprivileged user to modify other users, which of course is not something that can normally be done -- a user that can modify other users is, pretty much by definition, not an unprivileged user -- however -- stored procedures provided a good solution in that case, because they run with the security context of their DEFINER user, allowing anybody with EXECUTE privilege on the procedure to temporarily assume escalated privileges to allow them to do the specific things the procedure accomplishes.

Can I update a JSF component from a JSF backing bean method?

The RequestContext is deprecated from Primefaces 6.2. From this version use the following:

if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
    PrimeFaces.current().ajax().update(componentID);
}

And to execute javascript from the backbean use this way:

PrimeFaces.current().executeScript(jsCommand);

Reference:

Find files in a folder using Java

To elaborate on this response, Apache IO Utils might save you some time. Consider the following example that will recursively search for a file of a given name:

    File file = FileUtils.listFiles(new File("the/desired/root/path"), 
                new NameFileFilter("filename.ext"), 
                FileFilterUtils.trueFileFilter()
            ).iterator().next();

See:

Python float to int conversion

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Floating-point numbers cannot represent all the numbers. In particular, 2.51 cannot be represented by a floating-point number, and is represented by a number very close to it:

>>> print "%.16f" % 2.51
2.5099999999999998
>>> 2.51*100
250.99999999999997
>>> 4.02*100
401.99999999999994

If you use int, which truncates the numbers, you get:

250
401

Have a look at the Decimal type.

MySQL JDBC Driver 5.1.33 - Time Zone Issue

i Got error similar to yours but my The server time zone value is 'Afr. centrale Ouest' so i did these steps :

MyError (on IntelliJ IDEA Community Edition):

    InvalidConnectionAttributeException: The server time zone value 'Afr. centrale Ouest' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to u....

I faced this issue when I upgraded my mysql server to SQL Server 8.0 (MYSQL80).

The simplest solution to this problem is just write the below command in your MYSQL Workbench -

  SET GLOBAL time_zone = '+1:00'

The value after the time-zone will be equal to GMT+/- Difference in your timezone. The above example is for North Africa(GMT+1:00) / or for India(GMT+5:30). It will solve the issue.

Enter the Following code in your Mysql Workbench and execute quesry

[source link for question/problem ]

[source link for answer]

[Solution ScreenShot ]

UPDATE multiple tables in MySQL using LEFT JOIN

                DECLARE @cols VARCHAR(max),@colsUpd VARCHAR(max), @query VARCHAR(max),@queryUpd VARCHAR(max), @subQuery VARCHAR(max)
DECLARE @TableNameTest NVARCHAR(150)
SET @TableNameTest = @TableName+ '_Staging';
SELECT  @colsUpd = STUF  ((SELECT DISTINCT '], T1.[' + name,']=T2.['+name+'' FROM sys.columns
                 WHERE object_id = (
                                    SELECT top 1 object_id 
                                      FROM sys.objects
                                     WHERE name = ''+@TableNameTest+''
                                    )
                and name not in ('Action','Record_ID')
                FOR XML PATH('')
            ), 1, 2, ''
        ) + ']'


  Select @queryUpd ='Update T1
SET '+@colsUpd+'
FROM '+@TableName+' T1
INNER JOIN '+@TableNameTest+' T2
ON T1.Record_ID = T2.Record_Id
WHERE T2.[Action] = ''Modify'''
EXEC (@queryUpd)

MySQL: Enable LOAD DATA LOCAL INFILE

Another way is to use the mysqlimport client program.

You invoke it as follows:

mysqlimport -uTheUsername -pThePassword --local yourDatabaseName tableName.txt

This generates a LOAD DATA statement which loads tableName.txt into the tableName table.

Keep in mind the following:

mysqlimport determines the table name from the file you provide; using all text from the start of the file name up to the first period as the table name. So, if you wish to load several files to the same table you could distinguish them like tableName.1.txt, tableName.2.txt,..., etc, for example.

@synthesize vs @dynamic, what are the differences?

Take a look at this article; under the heading "Methods provided at runtime":

Some accessors are created dynamically at runtime, such as certain ones used in CoreData's NSManagedObject class. If you want to declare and use properties for these cases, but want to avoid warnings about methods missing at compile time, you can use the @dynamic directive instead of @synthesize.

...

Using the @dynamic directive essentially tells the compiler "don't worry about it, a method is on the way."

The @synthesize directive, on the other hand, generates the accessor methods for you at compile time (although as noted in the "Mixing Synthesized and Custom Accessors" section it is flexible and does not generate methods for you if either are implemented).

How do I remove newlines from a text file?

Expanding on a previous answer, this removes all new lines and saves the result to a new file (thanks to @tripleee):

tr -d '\n' < yourfile.txt > yourfile2.txt

Which is better than a "useless cat" (see comments):

cat file.txt | tr -d '\n' > file2.txt

Also useful for getting rid of new lines at the end of the file, e.g. created by using echo blah > file.txt.

Where do I get servlet-api.jar from?

You can find a recent servlet-api.jar in Tomcat 6 or 7 lib directory. If you don't have Tomcat on your machine, download the binary distribution of version 6 or 7 from http://tomcat.apache.org/download-70.cgi

Ball to Ball Collision - Detection and Handling

You should use space partitioning to solve this problem.

Read up on Binary Space Partitioning and Quadtrees

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

Change image source with JavaScript

You've got a few changes (this assumes you indeed still want to change the image with an ID of IMG, if not use Shadow Wizard's solution).

Remove a.src and replace with a:

<script type="text/javascript">
function changeImage(a) {
    document.getElementById("img").src=a;
}
</script>

Change your onclick attributes to include a string of the new image source instead of a literal:

onclick='changeImage( "1772031_29_b.jpg" );'

ActiveRecord OR query

The MetaWhere plugin is completely amazing.

Easily mix OR's and AND's, join conditions on any association, and even specify OUTER JOIN's!

Post.where({sharing_level: Post::Sharing[:everyone]} | ({sharing_level: Post::Sharing[:friends]} & {user: {followers: current_user} }).joins(:user.outer => :followers.outer}

What is tail call optimization?

In a functional language, tail call optimization is as if a function call could return a partially evaluated expression as the result, which would then be evaluated by the caller.

f x = g x

f 6 reduces to g 6. So if the implementation could return g 6 as the result, and then call that expression it would save a stack frame.

Also

f x = if c x then g x else h x.

Reduces to f 6 to either g 6 or h 6. So if the implementation evaluates c 6 and finds it is true then it can reduce,

if true then g x else h x ---> g x

f x ---> h x

A simple non tail call optimization interpreter might look like this,

class simple_expresion
{
    ...
public:
    virtual ximple_value *DoEvaluate() const = 0;
};

class simple_value
{
    ...
};

class simple_function : public simple_expresion
{
    ...
private:
    simple_expresion *m_Function;
    simple_expresion *m_Parameter;

public:
    virtual simple_value *DoEvaluate() const
    {
        vector<simple_expresion *> parameterList;
        parameterList->push_back(m_Parameter);
        return m_Function->Call(parameterList);
    }
};

class simple_if : public simple_function
{
private:
    simple_expresion *m_Condition;
    simple_expresion *m_Positive;
    simple_expresion *m_Negative;

public:
    simple_value *DoEvaluate() const
    {
        if (m_Condition.DoEvaluate()->IsTrue())
        {
            return m_Positive.DoEvaluate();
        }
        else
        {
            return m_Negative.DoEvaluate();
        }
    }
}

A tail call optimization interpreter might look like this,

class tco_expresion
{
    ...
public:
    virtual tco_expresion *DoEvaluate() const = 0;
    virtual bool IsValue()
    {
        return false;
    }
};

class tco_value
{
    ...
public:
    virtual bool IsValue()
    {
        return true;
    }
};

class tco_function : public tco_expresion
{
    ...
private:
    tco_expresion *m_Function;
    tco_expresion *m_Parameter;

public:
    virtual tco_expression *DoEvaluate() const
    {
        vector< tco_expression *> parameterList;
        tco_expression *function = const_cast<SNI_Function *>(this);
        while (!function->IsValue())
        {
            function = function->DoCall(parameterList);
        }
        return function;
    }

    tco_expresion *DoCall(vector<tco_expresion *> &p_ParameterList)
    {
        p_ParameterList.push_back(m_Parameter);
        return m_Function;
    }
};

class tco_if : public tco_function
{
private:
    tco_expresion *m_Condition;
    tco_expresion *m_Positive;
    tco_expresion *m_Negative;

    tco_expresion *DoEvaluate() const
    {
        if (m_Condition.DoEvaluate()->IsTrue())
        {
            return m_Positive;
        }
        else
        {
            return m_Negative;
        }
    }
}

addClass and removeClass in jQuery - not removing class

I would recomend to cache the jQuery objects you use more than once. For Instance:

    $(document).on("click", ".clickable", function () {
        $(this).addClass("grown");
        $(this).removeClass("spot");
    });

would be:

    var doc = $(document);
    doc.on('click', '.clickable', function(){
       var currentClickedObject = $(this);
       currentClickedObject.addClass('grown');
       currentClickedObject.removeClass('spot');
    });

its actually more code, BUT it is muuuuuuch faster because you dont have to "walk" through the whole jQuery library in order to get the $(this) object.

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

Convert nested Python dict to object?

I stumbled upon the case I needed to recursively convert a list of dicts to list of objects, so based on Roberto's snippet here what did the work for me:

def dict2obj(d):
    if isinstance(d, dict):
        n = {}
        for item in d:
            if isinstance(d[item], dict):
                n[item] = dict2obj(d[item])
            elif isinstance(d[item], (list, tuple)):
                n[item] = [dict2obj(elem) for elem in d[item]]
            else:
                n[item] = d[item]
        return type('obj_from_dict', (object,), n)
    elif isinstance(d, (list, tuple,)):
        l = []
        for item in d:
            l.append(dict2obj(item))
        return l
    else:
        return d

Note that any tuple will be converted to its list equivalent, for obvious reasons.

Hope this helps someone as much as all your answers did for me, guys.

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

I faced the same problem whenever i am firing SELECT query with specific columns, though the one of the column is primary in table. I was trying to fetch selective records with selective columns in standard wordpress "posts" table. ID column is already primary and unique..

Just specifying primary/unique column name will not resolve this issue. You have to specify full column name like "posts.id" (tablename.columnname) that tells PMA to select specific column and reveals edit etc..

My PMA is 4.3.8. Let me know if this helps..

Saving to CSV in Excel loses regional date format

Change the date range to "General" format and save the workbook once, and change them back to date format (eg, numberformat = "d/m/yyyy") before save & close the book. savechanges parameter is true.

in a "using" block is a SqlConnection closed on return or exception?

Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.

From MSDN:

A using statement can be exited either when 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.

Change the location of the ~ directory in a Windows install of Git Bash

I'd share what I did, which works not only for Git, but MSYS/MinGW as well.

The HOME environment variable is not normally set for Windows applications, so creating it through Windows did not affect anything else. From the Computer Properties (right-click on Computer - or whatever it is named - in Explorer, and select Properties, or Control Panel -> System and Security -> System), choose Advanced system settings, then Environment Variables... and create a new one, HOME, and assign it wherever you like.

If you can't create new environment variables, the other answer will still work. (I went through the details of how to create environment variables precisely because it's so dificult to find.)

How to normalize a NumPy array to within a certain range?

You can also rescale using sklearn. The advantages are that you can adjust normalize the standard deviation, in addition to mean-centering the data, and that you can do this on either axis, by features, or by records.

from sklearn.preprocessing import scale
X = scale( X, axis=0, with_mean=True, with_std=True, copy=True )

The keyword arguments axis, with_mean, with_std are self explanatory, and are shown in their default state. The argument copy performs the operation in-place if it is set to False. Documentation here.

dispatch_after - GCD in Swift?

1) Add this method as a part of UIViewController Extension.

extension UIViewController{
func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) {
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(time, dispatch_get_main_queue(), block)
    }
}

Call this method on VC:

    self.runAfterDelay(5.0, block: {
     //Add code to this block
        print("run After Delay Success")
    })

2)

performSelector("yourMethod Name", withObject: nil, afterDelay: 1)

3)

override func viewWillAppear(animated: Bool) {

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue(), { () -> () in
    //Code Here
})

//Compact Form

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue()) {
    //Code here
 }
}

Can we pass model as a parameter in RedirectToAction?

[NonAction]
private ActionResult CRUD(someModel entity)
{
        try
        {
            //you business logic here
     return View(entity);
       }                                
         catch (Exception exp)
         {
             ModelState.AddModelError("", exp.InnerException.Message);
             Response.StatusCode = 350;
             return someerrohandilingactionresult(entity, actionType);
         }
         //Retrun appropriate message or redirect to proper action
      return RedirectToAction("Index");   
}

Angular 2 How to redirect to 404 or other path if the path does not exist

make sure ,use this 404 route wrote on the bottom of the code.

syntax will be like

{
    path: 'page-not-found', 
    component: PagenotfoundComponent
},
{
    path: '**', 
    redirectTo: '/page-not-found'
},

Thank you

How to properly stop the Thread in Java?

Using Thread.interrupt() is a perfectly acceptable way of doing this. In fact, it's probably preferrable to a flag as suggested above. The reason being that if you're in an interruptable blocking call (like Thread.sleep or using java.nio Channel operations), you'll actually be able to break out of those right away.

If you use a flag, you have to wait for the blocking operation to finish and then you can check your flag. In some cases you have to do this anyway, such as using standard InputStream/OutputStream which are not interruptable.

In that case, when a thread is interrupted, it will not interrupt the IO, however, you can easily do this routinely in your code (and you should do this at strategic points where you can safely stop and cleanup)

if (Thread.currentThread().isInterrupted()) {
  // cleanup and stop execution
  // for example a break in a loop
}

Like I said, the main advantage to Thread.interrupt() is that you can immediately break out of interruptable calls, which you can't do with the flag approach.

Wildcards in a Windows hosts file

We have this working using wildcard DNS in our local DNS server: add an A record something like *.local -> 127.0.0.1

I think that your network settings will need to have the chosen domain suffix in the domain suffix search list for machines on the network, so you might want to replace .local with your company's internal domain (e.g. .int) and then add a subdomain like .localhost.int to make it clear what it's for.

So *.localhost.int would resolve to 127.0.0.1 for everybody on the network, and config file settings for all developers would "just work" if endpoints hang off that subdomain e.g. site1.localhost.int, site2.localhost.int This is pretty much the scheme we have introduced.

dnsmasq also looks nice, but I have not tried it yet: http://ihaveabackup.net/2012/06/28/using-wildcards-in-the-hosts-file/

Split an integer into digits to compute an ISBN checksum

Just assuming you want to get the i-th least significant digit from an integer number x, you can try:

(abs(x)%(10**i))/(10**(i-1))

I hope it helps.

Indent List in HTML and CSS

_x000D_
_x000D_
li {
  padding-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
  <li>List item</li>
</ul>
_x000D_
_x000D_
_x000D_ The above will add 30px of space between the bullet or number and your text.

_x000D_
_x000D_
li {
  margin-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
  <li>List item</li>
</ul>
_x000D_
_x000D_
_x000D_ The above will add 30px of space between the bullet or number and the left edge of the container.

How to open a URL in a new Tab using JavaScript or jQuery?

I know your question does not specify if you are trying to open all a tags in a new window or only the external links.

But in case you only want external links to open in a new tab you can do this:

$( 'a[href^="http://"]' ).attr( 'target','_blank' )
$( 'a[href^="https://"]' ).attr( 'target','_blank' )

Can I set an opacity only to the background image of a div?

This can be done by using the different div class for the text Hi There...

<div class="myDiv">
    <div class="bg">
   <p> Hi there</p>
</div>
</div>

Now you can apply the styles to the

tag. otherwise for bg class. I am sure it works fine

What is “assert” in JavaScript?

If using a modern browser or nodejs, you can use console.assert(expression, object).

For more information:

Import numpy on pycharm

In general, the cause of the problem could be the following:

You started a new project with the new virtual environment. So probably you install numpy from the terminal, but it is not in your venv. So

  • either install it from PyCahrm Interface: Settings -> Project Interpreter -> Add the package

  • or activate your venv and -> pip install numPy

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

HTML input number type allows "e/E" because "e" stands for exponential which is a numeric symbol.

Example 200000 can also be written as 2e5. I hope this helps thank you for the question.

ValueError: max() arg is an empty sequence

in one line,

v = max(v) if v else None

>>> v = []
>>> max(v)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence
>>> v = max(v) if v else None
>>> v
>>> 

Classes vs. Modules in VB.NET

I think it's a good idea to keep avoiding modules unless you stick them into separate namespaces. Because in Intellisense methods in modules will be visible from everywhere in that namespace.

So instead of ModuleName.MyMethod() you end up with MyMethod() popups in anywhere and this kind of invalidates the encapsulation. (at least in the programming level).

That's why I always try to create Class with shared methods, seems so much better.

How to return a list of keys from a Hash Map?

Use the keySet() method to return a set with all the keys of a Map.

If you want to keep your Map ordered you can use a TreeMap.

How to generate java classes from WSDL file

jdk 6 comes with wsimport that u can use to create Java-classes from a WSDL. It also creates a Service-class.

http://docs.oracle.com/javase/6/docs/technotes/tools/share/wsimport.html

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

Align the table to center.

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td align="center">
            Your Content
        </td>
    </tr>
</table>

Where you have "your content" if it is a table, set it to the desired width and you will have centred content.

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

Capturing a single image from my webcam in Java or Python

On windows it is easy to interact with your webcam with pygame:

from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')

I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux

Fatal error: Call to undefined function pg_connect()

I had the same symptom in win7. I got this script:

<?php
    phpinfo();
    pg_connect("blah");

When I executed the phpinfo.php script via apache (http://localhost/phpinfo.php) then I got the error message: Call to undefined function pg_connect() in...

When I executed the same script from command line (php phpinfo.php) then I got the expected message: PHP Warning: pg_connect(): Unable to connect to PostgreSQL server: missing "=" after "blah"

In both cases the expected php.ini was used:

Loaded Configuration File   C:\Program Files (x86)\php\php.ini 

but the pgsql section was completely missing from the phpinfo in case of the apache-based execution and it was present in the command-line-based execution.

The solution was that I added the following line to the apache httpd.conf:

LoadFile "C:/Program Files (x86)/php/libpq.dll"

It seems that for some reason this file is not loaded automatically when apache runs the php script but it is loaded if I run the php script from the command line.

I hope it helps.

Getting Checkbox Value in ASP.NET MVC 4

@Html.EditorFor(x => x.Remember)

Will generate:

<input id="Remember" type="checkbox" value="true" name="Remember" />
<input type="hidden" value="false" name="Remember" />

How does it work:

  • If checkbox remains unchecked, the form submits only the hidden value (false)
  • If checked, then the form submits two fields (false and true) and MVC sets true for the model's bool property

<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />

This will always send the default value, if checked.

Add space between cells (td) using css

Mine is:

border-spacing: 10px;
border-collapse: separate;

Determine if char is a num or letter

C99 standard on c >= '0' && c <= '9'

c >= '0' && c <= '9' (mentioned in another answer) works because C99 N1256 standard draft 5.2.1 "Character sets" says:

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

ASCII is not guaranteed however.

Java optional parameters

varargs could do that (in a way). Other than that, all variables in the declaration of the method must be supplied. If you want a variable to be optional, you can overload the method using a signature which doesn't require the parameter.

private boolean defaultOptionalFlagValue = true;

public void doSomething(boolean optionalFlag) {
    ...
}

public void doSomething() {
    doSomething(defaultOptionalFlagValue);
}

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

How to convert signed to unsigned integer in python

Python doesn't have builtin unsigned types. You can use mathematical operations to compute a new int representing the value you would get in C, but there is no "unsigned value" of a Python int. The Python int is an abstraction of an integer value, not a direct access to a fixed-byte-size integer.

Working with SQL views in Entity Framework Core

It is possible to scaffold a view. Just use -Tables the way you would to scaffold a table, only use the name of your view. E.g., If the name of your view is ‘vw_inventory’, then run this command in the Package Manager Console (substituting your own information for "My..."):

PM> Scaffold-DbContext "Server=MyServer;Database=MyDatabase;user id=MyUserId;password=MyPassword" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Temp -Tables vw_inventory

This command will create a model file and context file in the Temp directory of your project. You can move the model file into your models directory (remember to change the namespace name). You can copy what you need from the context file and paste it into the appropriate existing context file in your project.

Note: If you want to use your view in an integration test using a local db, you'll need to create the view as part of your db setup. If you’re going to use the view in more than one test, make sure to add a check for existence of the view. In this case, since the SQL ‘Create View’ statement is required to be the only statement in the batch, you’ll need to run the create view as dynamic Sql within the existence check statement. Alternatively you could run separate ‘if exists drop view…’, then ‘create view’ statements, but if multiple tests are running concurrently, you don’t want the view to be dropped if another test is using it. Example:

  void setupDb() {
    ...
    SomeDb.Command(db => db.Database.ExecuteSqlRaw(CreateInventoryView()));
    ...
  }
  public string CreateInventoryView() => @"
  IF OBJECT_ID('[dbo].[vw_inventory]') IS NULL
    BEGIN EXEC('CREATE VIEW [dbo].[vw_inventory] AS
       SELECT ...')
    END";

How to escape braces (curly brackets) in a format string in .NET

Escaping Brackets: String Interpolation $("") :

Now, you can also use c# string interpolation like this (feature available in C# 6.0)

var inVal= "1, 2, 3";
var outVal= $" foo {{{inVal}}}";
//Output will be:  foo {1, 2, 3}

Adding form action in html in laravel

For Laravel 2020. Ok, an example:

<form class="modal-content animate" action="{{ url('login_kun')  }}" method="post">
  @csrf   // !!! attention - this string is a must 
....
 </form>

And then in web.php:

Route::post("/login_kun", "LoginController@login");

And one more in new created LoginController:

 public function login(Request $request){
    dd($request->all());
}

and you are done my friend.

How do I check form validity with angularjs?

You can also use myform.$invalid

E.g.

if($scope.myform.$invalid){return;}

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)

Add items in array angular 4

Push object into your array. Try this:

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

How to reload .bashrc settings without logging out and back in again?

I noticed that pure exec bash command will preserve the environment variables, so you need to use exec -c bash to run bash in an empty environment.

For example, you login a bash, and export A=1, if you exec bash, the A == 1.

If you exec -cl bash, A is empty.

I think this is the best way to do your job.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Fragments onResume from back stack

After a popStackBack() you can use the following callback : onHiddenChanged(boolean hidden) within your fragment

Swift Beta performance: sorting arrays

The main issue that is mentioned by others but not called out enough is that -O3 does nothing at all in Swift (and never has) so when compiled with that it is effectively non-optimised (-Onone).

Option names have changed over time so some other answers have obsolete flags for the build options. Correct current options (Swift 2.2) are:

-Onone // Debug - slow
-O     // Optimised
-O -whole-module-optimization //Optimised across files

Whole module optimisation has a slower compile but can optimise across files within the module i.e. within each framework and within the actual application code but not between them. You should use this for anything performance critical)

You can also disable safety checks for even more speed but with all assertions and preconditions not just disabled but optimised on the basis that they are correct. If you ever hit an assertion this means that you are into undefined behaviour. Use with extreme caution and only if you determine that the speed boost is worthwhile for you (by testing). If you do find it valuable for some code I recommend separating that code into a separate framework and only disabling the safety checks for that module.

StringIO in Python3

In order to make examples from here work with Python 3.5.2, you can rewrite as follows :

import io
data =io.BytesIO(b"1, 2, 3\n4, 5, 6") 
import numpy
numpy.genfromtxt(data, delimiter=",")

The reason for the change may be that the content of a file is in data (bytes) which do not make text until being decoded somehow. genfrombytes may be a better name than genfromtxt.

How can I scroll to a specific location on the page using jquery?

Yep, even in plain JavaScript it's pretty easy. You give an element an id and then you can use that as a "bookmark":

<div id="here">here</div>

If you want it to scroll there when a user clicks a link, you can just use the tried-and-true method:

<a href="#here">scroll to over there</a>

To do it programmatically, use scrollIntoView()

document.getElementById("here").scrollIntoView()

Descending order by date filter in AngularJs

see w3schools samples: https://www.w3schools.com/angular/angular_filters.asp https://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_orderby_click

then add the "reverse" flag:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<p>Click the table headers to change the sorting order:</p>

<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:reverse">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Carl',country:'Sweden'},
        {name:'Margareth',country:'England'},
        {name:'Hege',country:'Norway'},
        {name:'Joe',country:'Denmark'},
        {name:'Gustav',country:'Sweden'},
        {name:'Birgit',country:'Denmark'},
        {name:'Mary',country:'England'},
        {name:'Kai',country:'Norway'}
        ];

    $scope.reverse=false;
    $scope.orderByMe = function(x) {

        if($scope.myOrderBy == x) {
            $scope.reverse=!$scope.reverse;
        }
        $scope.myOrderBy = x;
    }
});
</script>

</body>
</html>

How to remove margin space around body or clear default css styles

I had the same problem and my first <p> element which was at the top of the page and also had a browser webkit default margin. This was pushing my entire div down which had the same effect you were talking about so watch out for any text-based elements that are at the very top of the page.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My Website</title>
  </head>
  <body style="margin:0;">
      <div id="image" style="background: url(pixabay-cleaning-kids-720.jpg) 
no-repeat; width: 100%; background-size: 100%;height:100vh">
<p>Text in Paragraph</p>
      </div>
    </div>
  </body>
</html>

So just remember to check all child elements not only the html and body tags.

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

C# Iterate through Class properties

You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.

For a hint, you could possibly do something like:

Record record = new Record();

PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
    property.SetValue(record, value);
}

Where value is the value you're wanting to write in (so from your resultItems array).

How do I get an animated gif to work in WPF?

Basically the same PictureBox solution above, but this time with the code-behind to use an Embedded Resource in your project:

In XAML:

<WindowsFormsHost x:Name="_loadingHost">
  <Forms:PictureBox x:Name="_loadingPictureBox"/>
</WindowsFormsHost>

In Code-Behind:

public partial class ProgressIcon
{
    public ProgressIcon()
    {
        InitializeComponent();
        var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("My.Namespace.ProgressIcon.gif");
        var image = System.Drawing.Image.FromStream(stream);
        Loaded += (s, e) => _loadingPictureBox.Image = image;
    }
}

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

Impersonate tag in Web.Config

The identity section goes under the system.web section, not under authentication:

<system.web>
  <authentication mode="Windows"/>
  <identity impersonate="true" userName="foo" password="bar"/>
</system.web>

SQL Joins Vs SQL Subqueries (Performance)?

The performance should be the same; it's much more important to have the correct indexes and clustering applied on your tables (there exist some good resources on that topic).

(Edited to reflect the updated question)

Updating GUI (WPF) using a different thread

You have a couple of options here, I think.

One would be to use a BackgroundWorker. This is a common helper for multithreading in applications. It exposes a DoWork event which is handled on a background thread from the Thread Pool and a RunWorkerCompleted event which is invoked back on the main thread when the background thread completes. It also has the benefit of try/catching the code running on the background thread so that an unhandled exception doesn't kill the application.

If you don't want to go that route, you can use the WPF dispatcher object to invoke an action to update the GUI back onto the main thread. Random reference:

http://www.switchonthecode.com/tutorials/working-with-the-wpf-dispatcher

There are many other options around too, but these are the two most common that come to mind.

HTML <sup /> tag affecting line height, how to make it consistent?

I had the same problem and non of the given answers worked. But I found a git commit with a fix that did work for me:

sup {
  font-size: 0.8em;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
  top: -0.5em;
}

QString to char* conversion

EDITED

this way also works

QString str ("Something");

char* ch = str.toStdString().C_str();

Get Application Name/ Label via ADB Shell or Terminal

just enter the following command on command prompt after launching the app:

adb shell dumpsys window windows | find "mCurrentFocus"

if executing the command on linux terminal replace find by grep

Creating a procedure in mySql with parameters

(IN @brugernavn varchar(64)**)**,IN @password varchar(64))

The problem is the )

How to get values and keys from HashMap?

It will work with hash.get("key"); Where key is your key for getting the value from Map

Giving multiple conditions in for loop in Java

If you want to do that why not go with a while, for ease of mind? :P No, but seriously I didn't know that and seems kinda nice so thanks, nice to know!

Make Bootstrap's Carousel both center AND responsive?

This work for me very simple just add attribute align="center". Tested on Bootstrap 4.

<!-- The slideshow -->
            <div class="carousel-inner" align="center">             
                <div class="carousel-item active">
                    <img src="image1.jpg" alt="no image" height="550">
                </div>
                <div class="carousel-item">
                    <img src="image2.jpg" alt="no image" height="550">
                </div>                
                <div class="carousel-item">
                    <img src="image3.png" alt="no image" height="550">
                </div>
             </div>

PostgreSQL how to see which queries have run

While using Django with postgres 10.6, logging was enabled by default, and I was able to simply do:

tail -f /var/log/postgresql/*

Ubuntu 18.04, django 2+, python3+

Is PowerShell ready to replace my Cygwin shell on Windows?

I have only recently started dabbling in PowerShell with any degree of seriousness. Although for the past seven years I've worked in an almost exclusively Windows-based environment, I come from a Unix background and find myself constantly trying to "Unix-fy" my interaction experience on Windows. It's frustrating to say the least.

It's only fair to compare PowerShell to something like Bash, tcsh, or zsh since utilities like grep, sed, awk, find, etc. are not, strictly speaking, part of the shell; they will always, however, be part of any Unix environment. That said, a PowerShell command like Select-String has a very similar function to grep and is bundled as a core module in PowerShell ... so the lines can be a little blurred.

I think the key thing is culture, and the fact that the respective tool-sets will embody their respective cultures:

  • Unix is a file-based, (in general, non Unicode) text-based culture. Configuration files are almost exclusively text files. Windows, on the other hand has always been far more structured in respect of configuration formats--configurations are generally kept in proprietary databases (e.g., the Windows registry) which require specialised tools for their management.
  • The Unix administrative (and, for many years, development) interface has traditionally been the command line and the virtual terminal. Windows started off as a GUI and administrative functions have only recently started moving away from being exclusively GUI-based. We can expect the Unix experience on the command line to be a richer, more mature one given the significant lead it has on PowerShell, and my experience matches this. On this, in my experience:

    • The Unix administrative experience is geared towards making things easy to do in a minimal amount of key strokes; this is probably as a result of the historical situation of having to administer a server over a slow 9600 baud dial-up connection. Now PowerShell does have aliases which go a long way to getting around the rather verbose Verb-Noun standard, but getting to know those aliases is a bit of a pain (anyone know of something better than: alias | where {$_.ResolvedCommandName -eq "<command>"}?).

      An example of the rich way in which history can be manipulated:

      iptables commands are often long-winded and repeating them with slight differences would be a pain if it weren't for just one of many neat features of history manipulation built into Bash, so inserting an iptables rule like the following:

      iptables -I camera-1-internet -s 192.168.0.50 -m state --state NEW -j ACCEPT

      a second time for another camera ("camera-2"), is just a case of issuing:

      !!:s/-1-/-2-/:s/50/51

      which means "perform the previous command, but substitute -1- with -2- and 50 with 51.

    • The Unix experience is optimised for touch-typists; one can pretty much do everything without leaving the "home" position. For example, in Bash, using the Emacs key bindings (yes, Bash also supports vi bindings), cycling through the history is done using Ctrl-P and Ctrl-N whilst moving to the start and end of a line is done using Ctrl-A and Ctrl-E respectively ... and it definitely doesn't end there. Try even the simplest of navigation in the PowerShell console without moving from the home position and you're in trouble.

    • Simple things like versatile paging (a la less) on Unix don't seem to be available out-of-the-box in PowerShell which is a little frustrating, and a rich editor experience doesn't exist either. Of course, one can always download third-party tools that will fill those gaps, but it sure would be nice if these things were just "there" like they are on pretty much any flavour of Unix.
  • The Windows culture, at least in terms of system API's is largely driven by the supporting frameworks, viz., COM and .NET, both of-which are highly structured and object-based. On the other hand, access to Unix APIs has traditionally been through a file interface (/dev and /proc) or (non-object-oriented) C-style library calls. It's no surprise then that the scripting experiences match their respective OS paradigms. PowerShell is by nature structured (everything is an object) and Bash-and-friends file-based. The structured API which is at the disposal of a PowerShell programmer is vast (essentially matching the vastness of the existing set of standard COM and .NET interfaces).

In short, although the scripting capabilities of PowerShell are arguably more powerful than Bash (especially when you consider the availability of the .NET BCL), the interactive experience is significantly weaker, particularly if you're coming at it from an entirely keyboard-driven, console-based perspective (as many Unix-heads are).

Android update activity UI from service

Clyde's solution works, but it is a broadcast, which I am pretty sure will be less efficient than calling a method directly. I could be mistaken, but I think the broadcasts are meant more for inter-application communication.

I'm assuming you already know how to bind a service with an Activity. I do something sort of like the code below to handle this kind of problem:

class MyService extends Service {
    MyFragment mMyFragment = null;
    MyFragment mMyOtherFragment = null;

    private void networkLoop() {
        ...

        //received new data for list.
        if(myFragment != null)
            myFragment.updateList();
        }

        ...

        //received new data for textView
        if(myFragment !=null)
            myFragment.updateText();

        ...

        //received new data for textView
        if(myOtherFragment !=null)
            myOtherFragment.updateSomething();

        ...
    }
}


class MyFragment extends Fragment {

    public void onResume() {
        super.onResume()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyFragment=this;
    }

    public void onPause() {
        super.onPause()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyFragment=null;
    }

    public void updateList() {
        runOnUiThread(new Runnable() {
            public void run() {
                //Update the list.
            }
        });
    }

    public void updateText() {
       //as above
    }
}

class MyOtherFragment extends Fragment {
             public void onResume() {
        super.onResume()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyOtherFragment=this;
    }

    public void onPause() {
        super.onPause()
        //Assuming your activity bound to your service
        getActivity().mMyService.mMyOtherFragment=null;
    }

    public void updateSomething() {//etc... }
}

I left out bits for thread safety, which is essential. Make sure to use locks or something like that when checking and using or changing the fragment references on the service.

How do I get a specific range of numbers from rand()?

As others have noted, simply using a modulus will skew the probabilities for individual numbers so that smaller numbers are preferred.

A very ingenious and good solution to that problem is used in Java's java.util.Random class:

public int nextInt(int n) {
    if (n <= 0)
        throw new IllegalArgumentException("n must be positive");

    if ((n & -n) == n)  // i.e., n is a power of 2
        return (int)((n * (long)next(31)) >> 31);

    int bits, val;
    do {
        bits = next(31);
        val = bits % n;
    } while (bits - val + (n-1) < 0);
    return val;
}

It took me a while to understand why it works and I leave that as an exercise for the reader but it's a pretty concise solution which will ensure that numbers have equal probabilities.

The important part in that piece of code is the condition for the while loop, which rejects numbers that fall in the range of numbers which otherwise would result in an uneven distribution.

How do I join two lines in vi?

In Vim you can also use gJ.

??

What is the dual table in Oracle?

DUAL is necessary in PL/SQL development for using functions that are only available in SQL

e.g.

DECLARE
x XMLTYPE;
BEGIN
SELECT xmlelement("hhh", 'stuff')
INTO x
FROM dual;
END;

how to find all indexes and their columns for tables, views and synonyms in oracle

Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?

Combining multiple commits before pushing in Git

And my way of squashing multiple push is (perhaps you pushed to your own branch many commits and now you wish to do a pull request and you don't want to clutter them with many commits which you have already pushed). The way I do that (no other simpler option as far as I can tell is).

  1. Create new branch for the sake of squash (branch from the original branch you wish to pull request to).
  2. Push the newly created branch.
  3. Merge branch with commits (already pushed) to new branch.
  4. Rebase new branch and squash.
  5. Push new branch.
  6. Create new pull request for new branch which now has single commit.

Example:

git checkout from_branch_you_wish_to_pull_request_to
git checkout -b new_branch_will_have_single_squashed_commit
git push -u new_branch_will_have_single_squashed_commit
git merge older_branch_with_all_those_multiple_commits
git rebase -i (here you squash)
git push origin new_branch_will_have_single_squashed_commit

You can now pull request into from_branch_you_wish_to_pull_request_to

How to get the Facebook user id using the access token

You just have to hit another Graph API:

https://graph.facebook.com/me?access_token={access-token}

It will give your e-mail Id and user Id (for Facebook) also.

How to resolve 'npm should be run outside of the node repl, in your normal shell'

If you're like me running in a restricted environment without administrative privileges, that means your only way to get node up and running is to grab the executable (node.exe) without using the installer. You also cannot change the path variable which makes it that much more challenging.

Here's what I did (for Windows)

  1. Throw node.exe into its own folder (Downloaded the node.exe stand-alone )
  2. Grab an NPM release zip off of github: https://github.com/npm/npm/releases
  3. Create a folder named: node_modules in the node.exe folder
  4. Extract the NPM zip into the node_modules folder
  5. Make sure the top most folder is named npm (remove any of the versioning on the npm folder name ie: npm-2.12.1 --> npm)
  6. Copy npm.cmd out of the npm/bin folder into the top most folder with node.exe
  7. Open a command prompt to the node.exe directory (shift right-click "Open command window here")
  8. Now you will be able to run your npm installers via: npm install -g express

Running the installers through npm will now auto install packages where they need to be located (node_modules and the root)

Don't forget you will not be able to set the path variable if you do not have proper permissions. So your best route is to open a command prompt in the node.exe directory (shift right-click "Open command window here")

Create Excel file in Java

I've created the API "generator-excel" to create an Excel file, below the dependecy:

<dependency>
  <groupId>com.github.bld-commons.excel</groupId>
  <artifactId>generator-excel</artifactId>
  <version>3.1.0</version>
</dependency>

This library can to configure the styles, the functions, the charts, the pivot table and etc. through a series of annotations.
You can write rows by getting data from a datasource trough a query with or without parameters.
Below an example to develop

  1. I created 2 classes that represents the row of the table.
  2. package bld.generator.report.junit.entity;
        
        import java.util.Date;
        
        import org.apache.poi.ss.usermodel.HorizontalAlignment;
        
        import bld.generator.report.excel.RowSheet;
        import bld.generator.report.excel.annotation.ExcelCellLayout;
        import bld.generator.report.excel.annotation.ExcelColumn;
        import bld.generator.report.excel.annotation.ExcelDate;
        import bld.generator.report.excel.annotation.ExcelImage;
        import bld.generator.report.excel.annotation.ExcelRowHeight;
        
        @ExcelRowHeight(height = 3)
        public class UtenteRow implements RowSheet {
            
            @ExcelColumn(columnName = "Id", indexColumn = 0)
            @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
            private Integer idUtente; 
            @ExcelColumn(columnName = "Nome", indexColumn = 2)
            @ExcelCellLayout
            private String nome; 
            @ExcelColumn(columnName = "Cognome", indexColumn = 1)
            @ExcelCellLayout
            private String cognome;
            @ExcelColumn(columnName = "Data di nascita", indexColumn = 3)
            @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.CENTER)
            @ExcelDate
            private Date dataNascita;
            @ExcelColumn(columnName = "Immagine", indexColumn = 4)
            @ExcelCellLayout
            @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
            private byte[] image;   
            
            @ExcelColumn(columnName = "Path", indexColumn = 5)
            @ExcelCellLayout
            @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6)
            private String path;    
            
        
            public UtenteRow() {
            }
        
        
            public UtenteRow(Integer idUtente, String nome, String cognome, Date dataNascita) {
                super();
                this.idUtente = idUtente;
                this.nome = nome;
                this.cognome = cognome;
                this.dataNascita = dataNascita;
            }
        
        
            public Integer getIdUtente() {
                return idUtente;
            }
        
        
            public void setIdUtente(Integer idUtente) {
                this.idUtente = idUtente;
            }
        
        
            public String getNome() {
                return nome;
            }
        
        
            public void setNome(String nome) {
                this.nome = nome;
            }
        
        
            public String getCognome() {
                return cognome;
            }
        
        
            public void setCognome(String cognome) {
                this.cognome = cognome;
            }
        
        
            public Date getDataNascita() {
                return dataNascita;
            }
        
        
            public void setDataNascita(Date dataNascita) {
                this.dataNascita = dataNascita;
            }
        
        
            public byte[] getImage() {
                return image;
            }
        
        
            public String getPath() {
                return path;
            }
        
        
            public void setImage(byte[] image) {
                this.image = image;
            }
        
        
            public void setPath(String path) {
                this.path = path;
            }
        
        }
    

    package bld.generator.report.junit.entity;
    
    import org.apache.poi.ss.usermodel.DataConsolidateFunction;
    import org.apache.poi.ss.usermodel.HorizontalAlignment;
    
    import bld.generator.report.excel.RowSheet;
    import bld.generator.report.excel.annotation.ExcelCellLayout;
    import bld.generator.report.excel.annotation.ExcelColumn;
    import bld.generator.report.excel.annotation.ExcelFont;
    import bld.generator.report.excel.annotation.ExcelSubtotal;
    import bld.generator.report.excel.annotation.ExcelSubtotals;
    
    @ExcelSubtotals(labelTotalGroup = "Total",endLabel = "total")
    public class SalaryRow implements RowSheet {
    
        @ExcelColumn(columnName = "Name", indexColumn = 0)
        @ExcelCellLayout
        private String name;
        @ExcelColumn(columnName = "Amount", indexColumn = 1)
        @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT)
        @ExcelSubtotal(dataConsolidateFunction = DataConsolidateFunction.SUM,excelCellLayout = @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT,font=@ExcelFont(bold = true)))
        private Double amount;
        
        public SalaryRow() {
            super();
        }
        public SalaryRow(String name, Double amount) {
            super();
            this.name = name;
            this.amount = amount;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Double getAmount() {
            return amount;
        }
        public void setAmount(Double amount) {
            this.amount = amount;
        }
        
    }
    
  3. I created 2 class that represents the sheets.
  4. package bld.generator.report.junit.entity;
    
    import javax.validation.constraints.Size;
    
    import bld.generator.report.excel.QuerySheetData;
    import bld.generator.report.excel.annotation.ExcelHeaderLayout;
    import bld.generator.report.excel.annotation.ExcelMarginSheet;
    import bld.generator.report.excel.annotation.ExcelQuery;
    import bld.generator.report.excel.annotation.ExcelSheetLayout;
    
    @ExcelSheetLayout
    @ExcelHeaderLayout
    @ExcelMarginSheet(bottom = 1.5, left = 1.5, right = 1.5, top = 1.5)
    @ExcelQuery(select = "SELECT id_utente, nome, cognome, data_nascita,image,path "
            + "FROM utente "
            + "WHERE cognome=:cognome "
            + "order by cognome,nome")
    public class UtenteSheet extends QuerySheetData<UtenteRow> {
        
    
        public UtenteSheet(@Size(max = 31) String sheetName) {
            super(sheetName);
        }
    
        
    }
    

    package bld.generator.report.junit.entity;
    
    import javax.validation.constraints.Size;
    
    import bld.generator.report.excel.SheetData;
    import bld.generator.report.excel.annotation.ExcelHeaderLayout;
    import bld.generator.report.excel.annotation.ExcelMarginSheet;
    import bld.generator.report.excel.annotation.ExcelSheetLayout;
    @ExcelSheetLayout
    @ExcelHeaderLayout
    @ExcelMarginSheet(bottom = 1.5,left = 1.5,right = 1.5,top = 1.5)
    public class SalarySheet extends SheetData<SalaryRow> {
    
        public SalarySheet(@Size(max = 31) String sheetName) {
            super(sheetName);
        }
    
    }
    
  5. Class test, in the test function there are antoher sheets
  6. package bld.generator.report.junit;
    
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    import bld.generator.report.excel.BaseSheet;
    import bld.generator.report.excel.GenerateExcel;
    import bld.generator.report.excel.data.ReportExcel;
    import bld.generator.report.junit.entity.AutoreLibriSheet;
    import bld.generator.report.junit.entity.CasaEditrice;
    import bld.generator.report.junit.entity.GenereSheet;
    import bld.generator.report.junit.entity.SalaryRow;
    import bld.generator.report.junit.entity.SalarySheet;
    import bld.generator.report.junit.entity.TotaleAutoreLibriRow;
    import bld.generator.report.junit.entity.TotaleAutoreLibriSheet;
    import bld.generator.report.junit.entity.UtenteSheet;
    import bld.generator.report.utils.ExcelUtils;
    
    /**
     * The Class ReportTest.
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @ConfigurationProperties
    @ComponentScan(basePackages = {"bld.generator","bld.read"})
    @EnableTransactionManagement
    public class ReportTestJpa {
    
        /** The Constant PATH_FILE. */
        private static final String PATH_FILE = "/mnt/report/";
    
        /** The generate excel. */
        @Autowired
        private GenerateExcel generateExcel;
    
        /**
         * Sets the up.
         *
         * @throws Exception the exception
         */
        @Before
        public void setUp() throws Exception {
        }
    
        /**
         * Test.
         *
         * @throws Exception the exception
         */
        @Test
        public void test() throws Exception {
            List<BaseSheet> listBaseSheet = new ArrayList<>();
            
            UtenteSheet utenteSheet=new UtenteSheet("Utente");
            utenteSheet.getMapParameters().put("cognome", "Rossi");
            listBaseSheet.add(utenteSheet);
            
            CasaEditrice casaEditrice = new CasaEditrice("Casa Editrice","Mondadori", new GregorianCalendar(1955, Calendar.MAY, 10), "Roma", "/home/francesco/Documents/git-project/dev-excel/linux.jpg","Drammatico");
            listBaseSheet.add(casaEditrice);
            
            
            AutoreLibriSheet autoreLibriSheet = new AutoreLibriSheet("Libri d'autore","Test label");
            TotaleAutoreLibriSheet totaleAutoreLibriSheet=new TotaleAutoreLibriSheet();
            totaleAutoreLibriSheet.getListRowSheet().add(new TotaleAutoreLibriRow("Totale"));
            autoreLibriSheet.setSheetFunctionsTotal(totaleAutoreLibriSheet);
            listBaseSheet.add(autoreLibriSheet);
            GenereSheet genereSheet=new GenereSheet("Genere");
            listBaseSheet.add(genereSheet);
            SalarySheet salarySheet=new SalarySheet("salary");
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("a",2.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            salarySheet.getListRowSheet().add(new SalaryRow("c",1.0));
            listBaseSheet.add(salarySheet);
            ReportExcel excel = new ReportExcel("Mondadori JPA", listBaseSheet);
    
            byte[] byteReport = this.generateExcel.createFileXlsx(excel);
    
            ExcelUtils.writeToFile(PATH_FILE,excel.getTitle(), ".xlsx", byteReport);
    
        }
    
        
    
    }
    
  7. Application yaml
  8. logging:
      level:
        root: WARN
        org:
          springframework:
            web: DEBUG
          hibernate: ERROR
    
    
    
    spring:
      datasource:
        url: jdbc:postgresql://localhost:5432/excel_db
        username: ${EXCEL_USER_DB}
        password: ${EXCEL_PASSWORD_DB}
      jpa:
        show-sql: true
        properties:
          hibernate:
            default_schema: public
            jdbc:
              lob:
                non_contextual_creation: true 
            format_sql: true    
            ddl-auto: auto
        database-platform: org.hibernate.dialect.PostgreSQLDialect
        generate-ddl: true
    

below the link of the project on github:

How to add parameters to HttpURLConnection using POST using NameValuePair

To call POST/PUT/DELETE/GET Restful methods with custom header or json data the following Async class can be used

public class HttpUrlConnectionUtlity extends AsyncTask<Integer, Void, String> {
private static final String TAG = "HttpUrlConnectionUtlity";
Context mContext;
public static final int GET_METHOD = 0,
        POST_METHOD = 1,
        PUT_METHOD = 2,
        HEAD_METHOD = 3,
        DELETE_METHOD = 4,
        TRACE_METHOD = 5,
        OPTIONS_METHOD = 6;
HashMap<String, String> headerMap;

String entityString;
String url;
int requestType = -1;
final String timeOut = "TIMED_OUT";

int TIME_OUT = 60 * 1000;

public HttpUrlConnectionUtlity (Context mContext) {
    this.mContext = mContext;
    this.callback = callback;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(Integer... params) {
    int requestType = getRequestType();
    String response = "";
    try {


        URL url = getUrl();
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection = setRequestMethod(urlConnection, requestType);
        urlConnection.setConnectTimeout(TIME_OUT);
        urlConnection.setReadTimeout(TIME_OUT);
        urlConnection.setDoOutput(true);
        urlConnection = setHeaderData(urlConnection);
        urlConnection = setEntity(urlConnection);

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response = readResponseStream(urlConnection.getInputStream());
            Logger.v(TAG, response);
        }
        urlConnection.disconnect();
        return response;


    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (SocketTimeoutException e) {
        return timeOut;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        Logger.e(TAG, "ALREADY CONNECTED");
    }
    return response;
}

@Override
protected void onPostExecute(String response) {
    super.onPostExecute(response);

    if (TextUtils.isEmpty(response)) {
        //empty response
    } else if (response != null && response.equals(timeOut)) {
        //request timed out 
    } else    {
    //process your response
   }
}


private String getEntityString() {
    return entityString;
}

public void setEntityString(String s) {
    this.entityString = s;
}

private String readResponseStream(InputStream in) {
    BufferedReader reader = null;
    StringBuffer response = new StringBuffer();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response.toString();
}

private HttpURLConnection setEntity(HttpURLConnection urlConnection) throws IOException {
    if (getEntityString() != null) {
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(getEntityString());
        writer.flush();
        writer.close();
        outputStream.close();
    } else {
        Logger.w(TAG, "NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND");
    }
    return urlConnection;
}

private HttpURLConnection setHeaderData(HttpURLConnection urlConnection) throws UnsupportedEncodingException {
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.setRequestProperty("Accept", "application/json");
    if (getHeaderMap() != null) {
        for (Map.Entry<String, String> entry : getHeaderMap().entrySet()) {
            urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    } else {
        Logger.w(TAG, "NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND");
    }
    return urlConnection;
}

private HttpURLConnection setRequestMethod(HttpURLConnection urlConnection, int requestMethod) {
    try {
        switch (requestMethod) {
            case GET_METHOD:
                urlConnection.setRequestMethod("GET");
                break;
            case POST_METHOD:
                urlConnection.setRequestMethod("POST");
                break;
            case PUT_METHOD:
                urlConnection.setRequestMethod("PUT");
                break;
            case DELETE_METHOD:
                urlConnection.setRequestMethod("DELETE");
                break;
            case OPTIONS_METHOD:
                urlConnection.setRequestMethod("OPTIONS");
                break;
            case HEAD_METHOD:
                urlConnection.setRequestMethod("HEAD");
                break;
            case TRACE_METHOD:
                urlConnection.setRequestMethod("TRACE");
                break;
        }
    } catch (ProtocolException e) {
        e.printStackTrace();
    }
    return urlConnection;
}

public int getRequestType() {
    return requestType;
}

public void setRequestType(int requestType) {
    this.requestType = requestType;
}

public URL getUrl() throws MalformedURLException {
    return new URL(url);
}

public void setUrl(String url) {
    this.url = url;
}

public HashMap<String, String> getHeaderMap() {
    return headerMap;
}

public void setHeaderMap(HashMap<String, String> headerMap) {
    this.headerMap = headerMap;
}   }

And The Usage is

    HttpUrlConnectionUtlity httpMethod = new HttpUrlConnectionUtlity (mContext);
    JSONObject jsonEntity = new JSONObject();

    try {
        jsonEntity.put("key1", value1);
        jsonEntity.put("key2", value2);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    httpMethod.setUrl(YOUR_URL_STRING);
    HashMap<String, String> headerMap = new HashMap<>();
    headerMap.put("key",value);
    headerMap.put("key1",value1);
    httpMethod.setHeaderMap(headerMap);
    httpMethod.setRequestType(WiseConnectHttpMethod.POST_METHOD); //specify POST/GET/DELETE/PUT
    httpMethod.setEntityString(jsonEntity.toString());
    httpMethod.execute();

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

Python - OpenCV - imread - Displaying Image

In openCV whenever you try to display an oversized image or image bigger than your display resolution you get the cropped display. It's a default behaviour.
In order to view the image in the window of your choice openCV encourages to use named window. Please refer to namedWindow documentation

The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.

cv.namedWindow(name, flags=CV_WINDOW_AUTOSIZE) where each window is related to image container by the name arg, make sure to use same name

eg:

import cv2
frame = cv2.imread('1.jpg')
cv2.namedWindow("Display 1")
cv2.resizeWindow("Display 1", 300, 300)
cv2.imshow("Display 1", frame)

Using media breakpoints in Bootstrap 4-alpha

Use breakpoint mixins like this:

.something {
    padding: 5px;
    @include media-breakpoint-up(sm) { 
        padding: 20px;
    }
    @include media-breakpoint-up(md) { 
        padding: 40px;
    }
}

v4 breakpoints reference

v4 alpha6 breakpoints reference


Below full options and values.

Breakpoint & up (toggle on value and above):

@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }

breakpoint & up values:

// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

breakpoint & down (toggle on value and down):

@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }

breakpoint & down values:

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }

// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }

// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }

// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width

breakpoint only:

@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }

breakpoint only values (toggle in between values only):

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Maven: add a folder or jar file into current classpath

This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?

In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.

See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html

How to call javascript function from code-behind

One way of doing it is to use the ClientScriptManager:

Page.ClientScript.RegisterStartupScript(
    GetType(), 
    "MyKey", 
    "Myfunction();", 
    true);

Java JTable setting Column Width

Reading the remark of Kleopatra (her 2nd time she suggested to have a look at javax.swing.JXTable, and now I Am sorry I didn't have a look the first time :) ) I suggest you follow the link

I had this solution for the same problem: (but I suggest you follow the link above) On resize the table, scale the table column widths to the current table total width. to do this I use a global array of ints for the (relative) column widths):

private int[] columnWidths=null;

I use this function to set the table column widths:

public void setColumnWidths(int[] widths){
    int nrCols=table.getModel().getColumnCount();
    if(nrCols==0||widths==null){
        return;
    }
    this.columnWidths=widths.clone();

    //current width of the table:
    int totalWidth=table.getWidth();
    
    int totalWidthRequested=0;
    int nrRequestedWidths=columnWidths.length;
    int defaultWidth=(int)Math.floor((double)totalWidth/(double)nrCols);

    for(int col=0;col<nrCols;col++){
        int width = 0;
        if(columnWidths.length>col){
            width=columnWidths[col];
        }
        totalWidthRequested+=width;
    }
    //Note: for the not defined columns: use the defaultWidth
    if(nrRequestedWidths<nrCols){
        log.fine("Setting column widths: nr of columns do not match column widths requested");
        totalWidthRequested+=((nrCols-nrRequestedWidths)*defaultWidth);
    }
    //calculate the scale for the column width
    double factor=(double)totalWidth/(double)totalWidthRequested;

    for(int col=0;col<nrCols;col++){
        int width = defaultWidth;
        if(columnWidths.length>col){
            //scale the requested width to the current table width
            width=(int)Math.floor(factor*(double)columnWidths[col]);
        }
        table.getColumnModel().getColumn(col).setPreferredWidth(width);
        table.getColumnModel().getColumn(col).setWidth(width);
    }
    
}

When setting the data I call:

    setColumnWidths(this.columnWidths);

and on changing I call the ComponentListener set to the parent of the table (in my case the JScrollPane that is the container of my table):

public void componentResized(ComponentEvent componentEvent) {
    this.setColumnWidths(this.columnWidths);
}

note that the JTable table is also global:

private JTable table;

And here I set the listener:

    scrollPane=new JScrollPane(table);
    scrollPane.addComponentListener(this);

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

How to install toolbox for MATLAB

Use ver it will list all the installed toolboxes and versions of the toolbox.

Make a link use POST instead of GET

HTML + JQuery: A link that submits a hidden form with POST.

Since I spent a lot of time to understand all these answers, and since all of them have some interesting details, here is the combined version that finally worked for me and which I prefer for its simplicity.

My approach is again to create a hidden form and to submit it by clicking a link somewhere else in the page. It doesn't matter where in the body of the page the form will be placed.

The code for the form:

<form id="myHiddenFormId" action="myAction.php" method="post" style="display: none">
  <input type="hidden" name="myParameterName" value="myParameterValue">
</form>

Description:

The display: none hides the form. You can alternatively put it in a div or another element and set the display: none on the element.

The type="hidden" will create an fild that will not be shown but its data will be transmitted to the action eitherways (see W3C). I understand that this is the simplest input type.

The code for the link:

<a href="" onclick="$('#myHiddenFormId').submit(); return false;" title="My link title">My link text</a>

Description:

The empty href just targets the same page. But it doesn't really matter in this case since the return false will stop the browser from following the link. You may want to change this behavior of course. In my specific case, the action contained a redirection at the end.

The onclick was used to avoid using href="javascript:..." as noted by mplungjan. The $('#myHiddenFormId').submit(); was used to submit the form (instead of defining a function, since the code is very small).

This link will look exactly like any other <a> element. You can actually use any other element instead of the <a> (for example a <span> or an image).

Excel VBA Run Time Error '424' object required

Simply remove the .value from your code.

Set envFrmwrkPath = ActiveSheet.Range("D6").Value

instead of this, use:

Set envFrmwrkPath = ActiveSheet.Range("D6")

Short circuit Array.forEach like calling break

Why don't you try wrapping the function in a Promise?

The only reason I bring it up is that I am using a function in an API that acts in a similar manner to forEach. I don't want it to keep iterating once it finds a value, and I need to return something so I am simply going to resolve a Promise and do it that way.

traverseTree(doc): Promise<any> {
  return new Promise<any>((resolve, reject) => {
    this.gridOptions.api.forEachNode((node, index) => {
    //the above function is the one I want to short circuit.
      if(node.data.id === doc.id) {
        return resolve(node);
      }
    });
  });
}

Then all you need to do is do something with the result like

this.traverseTree(doc).then((result) => {
   this.doSomething(result);
});

My above example is in typescript, simply ignore the types. The logic should hopefully help you "break" out of your loop.

Reusing output from last command in Bash

I have an idea that I don't have time to try to implement immediately.

But what if you do something like the following:

$ MY_HISTORY_FILE = `get_temp_filename`
$ MY_HISTORY_FILE=$MY_HISTORY_FILE bash -i 2>&1 | tee $MY_HISTORY_FILE
$ some_command
$ cat $MY_HISTORY_FILE
$ # ^You'll want to filter that down in practice!

There might be issues with IO buffering. Also the file might get too huge. One would have to come up with a solution to these problems.

Iterate through 2 dimensional array

Simple idea: get the lenght of the longest row, iterate over each column printing the content of a row if it has elements. The below code might have some off-by-one errors as it was coded in a simple text editor.

  int longestRow = 0;
  for (int i = 0; i < array.length; i++) {
    if (array[i].length > longestRow) {
      longestRow = array[i].length;
    }
  }

  for (int j = 0; j < longestRow; j++) {
    for (int i = 0; i < array.length; i++) {
      if(array[i].length > j) {
        System.out.println(array[i][j]);
      }
    }
  }

Does functional programming replace GoF design patterns?

I think only two GoF Design Patterns are designed to introduce the functional programming logic into natural OO language. I think about Strategy and Command. Some of the other GoF design patterns can be modified by functional programming to simplify the design and keep the purpose.

What is the exact meaning of Git Bash?

Bash is a Command Line Interface that was created over twenty-seven years ago by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of Command Line Interface. Bash is "open source" which means that anyone can read the code and suggest changes. Since its beginning, it has been supported by a large community of engineers who have worked to make it an incredible tool. Bash is the default shell for Linux and Mac. For these reasons, Bash is the most used and widely distributed shell.

Windows has a different Command Line Interface, called Command Prompt. While this has many of the same features as Bash, Bash is much more popular. Because of the strength of the open source community and the tools they provide, mastering Bash is a better investment than mastering Command Prompt.

To use Bash on a Windows computer, we need to download and install a program called Git Bash. Git Bash (Is the Bash for windows) allows us to easily access Bash as well as another tool called Git, inside the Windows environment.

Iterate a certain number of times without storing the iteration number anywhere

Although I agree completely with delnan's answer, it's not impossible:

loop = range(NUM_ITERATIONS+1)
while loop.pop():
    do_stuff()

Note, however, that this will not work for an arbitrary list: If the first value in the list (the last one popped) does not evaluate to False, you will get another iteration and an exception on the next pass: IndexError: pop from empty list. Also, your list (loop) will be empty after the loop.

Just for curiosity's sake. ;)

How to insert a line break before an element using CSS

Following CSS worked for me:

/* newline before element */
#myelementId:before{
    content:"\a";
    white-space: pre;
}

JS jQuery - check if value is in array

As to your bonus question, try if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)

How can I get the assembly file version

When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used

versionlabel.Text = "Version " + Application.ProductVersion;

This approach requires a reference to System.Windows.Forms.

Remove Array Value By index in jquery

Your syntax is incorrect, you should either specify a hash:

hash = {abc: true, def: true, ghi: true};

Or an array:

arr = ['abc','def','ghi'];

You can effectively remove an item from a hash by simply setting it to null:

hash['def'] = null;
hash.def = null;

Or removing it entirely:

delete hash.def;

To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:

arr.splice(arr.indexOf("def"), 1);

This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:

arr.filter(function(item) { return item !== 'def'; });

This will create a new array with only elements that are not 'def'.

It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.

Reinitialize Slick js after successful ajax call

The best way would be to use the unslick setting or function(depending on your version of slick) as stated in the other answers but that did not work for me. I'm getting some errors from slick that seem to be related to this.

What did work for now, however, is removing the slick-initialized and slick-slider classes from the container before reinitializing slick, like so:

function slickCarousel() {
    $('.skills_section').removeClass("slick-initialized slick-slider");
    $('.skills_section').slick({
        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 1
    });
}

Removing the classes doesn't seem to initiate the destroy event(not tested but makes sense) but does cause the later slick() call to behave properly so as long as you don't have any triggers on destroy, you should be good.

Most efficient way to get table row count

try this

Execute this SQL:

SHOW TABLE STATUS LIKE '<tablename>'

and fetch the value of the field Auto_increment

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

How to dynamically change a web page's title?

The simplest way is to delete <title> tag from index.html, and include

<head>
<title> Website - The page </title></head>

in every page in the web. Spiders will find this and will be shown in search results :)

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

What's the difference between Invoke() and BeginInvoke()

Do you mean Delegate.Invoke/BeginInvoke or Control.Invoke/BeginInvoke?

  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

Tim's answer mentions when you might want to use BeginInvoke - although it was mostly geared towards Delegate.BeginInvoke, I suspect.

For Windows Forms apps, I would suggest that you should usually use BeginInvoke. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person with FirstName and LastName properties, and you did:

person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";

Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)

Unless you have this sort of issue, however, Control.BeginInvoke is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a "fire and forget" manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.

Concatenating variables and strings in React

you can simply do this..

 <img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>

Text Progress Bar in the Console

Check this library: clint

it has a lot of features including a progress bar:

from time import sleep  
from random import random  
from clint.textui import progress  
if __name__ == '__main__':
    for i in progress.bar(range(100)):
        sleep(random() * 0.2)

    for i in progress.dots(range(100)):
        sleep(random() * 0.2)

this link provides a quick overview of its features

Is there a program to decompile Delphi?

Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )

I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)

Getting Django admin url for an object

There's another way for the later versions, for example in 1.10:

{% load admin_urls %}
<a href="{% url opts|admin_urlname:'add' %}">Add user</a>
<a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>

Where opts is something like mymodelinstance._meta or MyModelClass._meta

One gotcha is you can't access underscore attributes directly in Django templates (like {{ myinstance._meta }}) so you have to pass the opts object in from the view as template context.

Contain form within a bootstrap popover?

like this Working demo http://jsfiddle.net/7e2XU/21/show/# * Update: http://jsfiddle.net/kz5kjmbt/

 <div class="container">
    <div class="row" style="padding-top: 240px;"> <a href="#" class="btn btn-large btn-primary" rel="popover" data-content='
<form id="mainForm" name="mainForm" method="post" action="">
    <p>
        <label>Name :</label>
        <input type="text" id="txtName" name="txtName" />
    </p>
    <p>
        <label>Address 1 :</label>
        <input type="text" id="txtAddress" name="txtAddress" />
    </p>
    <p>
        <label>City :</label>
        <input type="text" id="txtCity" name="txtCity" />
    </p>
    <p>
        <input type="submit" name="Submit" value="Submit" />
    </p>
</form>
 data-placement="top" data-original-title="Fill in form">Open form</a>

    </div>
</div>

JavaScript code:

    $('a[rel=popover]').popover({
      html: 'true',
      placement: 'right'
    })

ScreenShot

working updated fiddle screenshot

How to convert a negative number to positive?

The inbuilt function abs() would do the trick.

positivenum = abs(negativenum)

How to use `replace` of directive definition?

Replace [True | False (default)]

Effect

1.  Replace the directive element. 

Dependency:

1. When replace: true, the template or templateUrl must be required. 

How to get UTC timestamp in Ruby?

time = Time.zone.now()

It will work as

irb> Time.zone.now
=> 2017-12-02 12:06:41 UTC

Boolean operators && and ||

&& and || are what is called "short circuiting". That means that they will not evaluate the second operand if the first operand is enough to determine the value of the expression.

For example if the first operand to && is false then there is no point in evaluating the second operand, since it can't change the value of the expression (false && true and false && false are both false). The same goes for || when the first operand is true.

You can read more about this here: http://en.wikipedia.org/wiki/Short-circuit_evaluation From the table on that page you can see that && is equivalent to AndAlso in VB.NET, which I assume you are referring to.

How do emulators work and how are they written?

Yes, you have to interpret the whole binary machine code mess "by hand". Not only that, most of the time you also have to simulate some exotic hardware that doesn't have an equivalent on the target machine.

The simple approach is to interpret the instructions one-by-one. That works well, but it's slow. A faster approach is recompilation - translating the source machine code to target machine code. This is more complicated, as most instructions will not map one-to-one. Instead you will have to make elaborate work-arounds that involve additional code. But in the end it's much faster. Most modern emulators do this.

Fix footer to bottom of page

Your footer element won't inherently be fixed to the bottom of your viewport unless you style it that way.
So if you happen to have a page that doesn't have enough content to push it all the way down it'll end up somewhere in the middle of the viewport; looking very awkward and not sure what to do with itself, like my first day of high school.

Positioning the element by declaring the fixed rule is great if you always want your footer visible regardless of initial page height - but then remember to set a bottom margin so that it doesn't overlay the last bit of content on that page. This becomes tricky if your footer has a dynamic height; which is often the case with responsive sites since it's in the nature of elements to stack.

You'll find a similar problem with absolute positioning. And although it does take the element in question out of the natural flow of the document, it still won't fix it to the bottom of the screen should you find yourself with a page that has little to no content to flesh it out.

Consider achieving this by:

  1. Declaring a height value for the <body> & <html> tags
  2. Declaring a minimum-height value to the nested wrapper element, usually the element which wraps all your descendant elements contained within the body structure (this wouldn't include your footer element)

Code Pen Example

_x000D_
_x000D_
$("#addBodyContent").on("click", function() {_x000D_
  $("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo(".flex-col:first-of-type");_x000D_
});_x000D_
_x000D_
$("#resetBodyContent").on("click", function() {_x000D_
  $(".flex-col p").remove();_x000D_
});_x000D_
_x000D_
$("#addFooterContent").on("click", function() {_x000D_
  $("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo("footer");_x000D_
});_x000D_
_x000D_
$("#resetFooterContent").on("click", function() {_x000D_
  $("footer p").remove();_x000D_
});
_x000D_
html, body {_x000D_
    height: 91%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
    width: 100%;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    box-sizing: border-box;_x000D_
    padding: 10px;_x000D_
    display: block;_x000D_
    min-height: 100%;_x000D_
}_x000D_
_x000D_
footer {_x000D_
    background: black;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    box-sizing: border-box;_x000D_
    padding: 10px;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
    display: flex;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.flex-col {_x000D_
    flex: 1 1;_x000D_
    background: #ccc;_x000D_
    margin: 0px 10px;_x000D_
    box-sizing: border-box;_x000D_
    padding: 20px;_x000D_
}_x000D_
_x000D_
.flex-btn-wrapper {_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    flex-direction: row;_x000D_
}_x000D_
_x000D_
.btn {_x000D_
    box-sizing: border-box;_x000D_
    padding: 10px;_x000D_
    transition: .7s;_x000D_
    margin: 10px 10px;_x000D_
    min-width: 200px;_x000D_
}_x000D_
_x000D_
.btn:hover {_x000D_
    background: transparent;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
.dark {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    border: 3px solid black;_x000D_
}_x000D_
_x000D_
.light {_x000D_
    background: white;_x000D_
    border: 3px solid white;_x000D_
}_x000D_
_x000D_
.light:hover {_x000D_
    color: white;_x000D_
}_x000D_
_x000D_
.dark:hover {_x000D_
    color: black;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrapper">_x000D_
    <div class="flex-btn-wrapper">_x000D_
        <button id="addBodyContent" class="dark btn">Add Content</button>_x000D_
        <button id="resetBodyContent" class="dark btn">Reset Content</button>_x000D_
    </div>_x000D_
    <div class="flex">_x000D_
    <div class="flex-col">_x000D_
      lorem ipsum dolor..._x000D_
    </div>_x000D_
    <div class="flex-col">_x000D_
      lorem ipsum dolor..._x000D_
    </div>_x000D_
    </div>_x000D_
    </div>_x000D_
<footer>_x000D_
    <div class="flex-btn-wrapper">_x000D_
        <button id="addFooterContent" class="light btn">Add Content</button>_x000D_
        <button id="resetFooterContent" class="light btn">Reset Content</button>_x000D_
    </div>_x000D_
    lorem ipsum dolor..._x000D_
</footer>
_x000D_
_x000D_
_x000D_

Closing WebSocket correctly (HTML5, Javascript)

Very simple, you close it :)

var myWebSocket = new WebSocket("ws://example.org"); 
myWebSocket.send("Hello Web Sockets!"); 
myWebSocket.close();

Did you check also the following site And check the introduction article of Opera

Get hostname of current request in node.js Express

If you're talking about an HTTP request, you can find the request host in:

request.headers.host

But that relies on an incoming request.

More at http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest

If you're looking for machine/native information, try the process object.

Laravel 5.4 Specific Table Migration

First you should to make the following commands:

Step 1:

php artisan migrate:rollback

Step 2:

php artisan migrate

Your table will be back in database .

Updating Python on Mac

Python 2.7 and 3 can co-exist.
Python version shows on terminal is 2.7, but you can invoke it using "python3", see this:

PeiwenMAC:git Peiwen$ python --version
Python 2.7.2
PeiwenMAC:git Peiwen$ python3
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

HTML5 and frameborder

style="border:none; scrolling:no; frameborder:0;  marginheight:0; marginwidth:0; "

How to pass ArrayList of Objects from one to another activity using Intent in android?

I found that most of the answers work but with a warning. So I have a tricky way to achieve this without any warning.

ArrayList<Question> questionList = new ArrayList<>();
...
Intent intent = new Intent(CurrentActivity.this, ToOpenActivity.class);
for (int i = 0; i < questionList.size(); i++) {
    Question question = questionList.get(i);
    intent.putExtra("question" + i, question);
}
startActivity(intent);

And now in Second Activity

ArrayList<Question> questionList = new ArrayList<>();

Intent intent = getIntent();
int i = 0;
while (intent.hasExtra("question" + i)){
    Question model = (Question) intent.getSerializableExtra("question" + i);
    questionList.add(model);
    i++;
}

Note: implements Serializable in your Question class.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

You have to set LANG as well, look for files named 'sp1*.msb', and set for instance export LANG=us if you find a file name sp1us.msb. The error message could sure be better :)

Checking if a double (or float) is NaN in C++

As for me the solution could be a macro to make it explicitly inline and thus fast enough. It also works for any float type. It bases on the fact that the only case when a value is not equals itself is when the value is not a number.

#ifndef isnan
  #define isnan(a) (a != a)
#endif

How to skip a iteration/loop in while-loop

You're looking for the continue; statement.

Import PEM into Java Key Store

In my case I had a pem file which contained two certificates and an encrypted private key to be used in mutual SSL authentication. So my pem file looked like this:

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

-----BEGIN RSA PRIVATE KEY-----

Proc-Type: 4,ENCRYPTED

DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9

...

-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

Here is what I did

Split the file into three separate files, so that each one contains just one entry, starting with ---BEGIN.. and ending with ---END.. lines. Lets assume we now have three files: cert1.pem, cert2.pem, and pkey.pem.

Convert pkey.pem into DER format using openssl and the following syntax:

openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER

Note, that if the private key is encrypted you need to supply a password( obtain it from the supplier of the original pem file ) to convert to DER format, openssl will ask you for the password like this: "enter a passphrase for pkey.pem: ".

If conversion is successful, you will get a new file called pkey.der.

Create a new java keystore and import the private key and the certificates:

String keypass = "password";  // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");

// this section does not make much sense to me, 
// but I will leave it intact as this is how it was in the original example I found on internet:   
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore"  ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ),    keypass.toCharArray());
// end of section..


// read the key file from disk and create a PrivateKey

FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();

PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);


// read the certificates from the files and load them into the key store:

Collection  col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection  col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));

Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };

String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();

ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);

// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );

// save the key store to a file         
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());

(optional) Verify the content of your new key store:

$ keytool -list -keystore mykeystore -storepass password

Keystore type: JKS Keystore provider: SUN

Your keystore contains 3 entries:

  • cn=...,ou=...,o=.., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 2C:B8: ...

  • importkey, Sep 2, 2014, PrivateKeyEntry, Certificate fingerprint (SHA1): 9C:B0: ...

  • cn=...,o=...., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83:63: ...

(optional) Test your certificates and private key from your new key store against your SSL server: ( You may want to enable debugging as an VM option: -Djavax.net.debug=all )

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        SSLSocketFactory factory = sclx.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
        socket.startHandshake();

        //if no exceptions are thrown in the startHandshake method, then everything is fine..

Finally register your certificates with HttpsURLConnection if plan to use it:

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        HostnameVerifier hv = new HostnameVerifier()
        {
            public boolean verify(String urlHostName, SSLSession session)
            {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
                {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

Parsing HTML using Python

Compared to the other parser libraries lxml is extremely fast:

And with cssselect it’s quite easy to use for scraping HTML pages too:

from lxml.html import parse
doc = parse('http://www.google.com').getroot()
for div in doc.cssselect('a'):
    print '%s: %s' % (div.text_content(), div.get('href'))

lxml.html Documentation

Prevent textbox autofill with previously entered values

Adding autocomplete="new-password" to the password field did the trick. Removed auto filling of both user name and password fields in Chrome.

<input type="password" name="whatever" autocomplete="new-password" />

How to include JavaScript file or library in Chrome console?

As a follow-up to the answer of @maciej-bukowski above ^^^, in modern browsers as of now (spring 2017) that support async/await you can load as follows. In this example we load the load html2canvas library:

_x000D_
_x000D_
async function loadScript(url) {_x000D_
  let response = await fetch(url);_x000D_
  let script = await response.text();_x000D_
  eval(script);_x000D_
}_x000D_
_x000D_
let scriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js'_x000D_
loadScript(scriptUrl);
_x000D_
_x000D_
_x000D_

If you run the snippet and then open your browser's console you should see the function html2canvas() is now defined.

jQuery click event not working in mobile browsers

I had the same problem and fixed it by adding "mousedown touchstart"

$(document).on("mousedown touchstart", ".className", function() { // your code here });

inested of others

ReactJS call parent method

Using Function || stateless component

Parent Component

 import React from "react";
 import ChildComponent from "./childComponent";

 export default function Parent(){

 const handleParentFun = (value) =>{
   console.log("Call to Parent Component!",value);
 }
 return (<>
           This is Parent Component
           <ChildComponent 
             handleParentFun={(value)=>{
               console.log("your value -->",value);
               handleParentFun(value);
             }}
           />
        </>);
}

Child Component

import React from "react";


export default function ChildComponent(props){
  return(
         <> This is Child Component 
          <button onClick={props.handleParentFun("YoureValue")}>
            Call to Parent Component Function
          </button>
         </>
        );
}

Go to beginning of line without opening new line in VI

Move the cursor to the begining or end with insert mode

  • I - Moves the cursor to the first non blank character in the current line and enables insert mode.
  • A - Moves the cursor to the last character in the current line and enables insert mode.

Here I is equivalent to ^ + i. Similarly A is equivalent to $ + a.

Just moving the cursor to the begining or end

  • ^ - Moves the cursor to the first non blank character in the current line
  • 0 - Moves the cursor to the first character in the current line
  • $ - Moves the cursor to the last character in the current line

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

How can I view all historical changes to a file in SVN

Slightly different from what you described, but I think this might be what you actually need:

svn blame filename

It will print the file with each line prefixed by the time and author of the commit that last changed it.

How to close a Java Swing application from the code

If I understand you correctly you want to close the application even if the user did not click on the close button. You will need to register WindowEvents maybe with addWindowListener() or enableEvents() whichever suits your needs better.

You can then invoke the event with a call to processWindowEvent(). Here is a sample code that will create a JFrame, wait 5 seconds and close the JFrame without user interaction.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ClosingFrame extends JFrame implements WindowListener{

public ClosingFrame(){
    super("A Frame");
    setSize(400, 400);
            //in case the user closes the window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            //enables Window Events on this Component
            this.addWindowListener(this);

            //start a timer
    Thread t = new Timer();
            t.start();
    }

public void windowOpened(WindowEvent e){}
public void windowClosing(WindowEvent e){}

    //the event that we are interested in
public void windowClosed(WindowEvent e){
    System.exit(0);
}

public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}

    //a simple timer 
    class Timer extends Thread{
           int time = 10;
           public void run(){
     while(time-- > 0){
       System.out.println("Still Waiting:" + time);
               try{
                 sleep(500);                     
               }catch(InterruptedException e){}
             }
             System.out.println("About to close");
    //close the frame
            ClosingFrame.this.processWindowEvent(
                 new WindowEvent(
                       ClosingFrame.this, WindowEvent.WINDOW_CLOSED));
           }
    }

    //instantiate the Frame
public static void main(String args[]){
          new ClosingFrame();
    }

}

As you can see, the processWindowEvent() method causes the WindowClosed event to be fired where you have an oportunity to do some clean up code if you require before closing the application.

How to explicitly obtain post data in Spring MVC?

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");

The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

How to use a Bootstrap 3 glyphicon in an html select

To my knowledge the only way to achieve this in a native select would be to use the unicode representations of the font. You'll have to apply the glyphicon font to the select and as such can't mix it with other fonts. However, glyphicons include regular characters, so you can add text. Unfortunately setting the font for individual options doesn't seem to be possible.

<select class="form-control glyphicon">
    <option value="">&#x2212; &#x2212; &#x2212; Hello</option>
    <option value="glyphicon-list-alt">&#xe032; Text</option>
</select>

Here's a list of the icons with their unicode:

http://glyphicons.bootstrapcheatsheets.com/

I can't delete a remote master branch on git

The quickest way is to switch default branch from master to another and you can remove master branch from the web interface.

IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    
    SELECT * FROM table
    WHERE column = ANY(subquery);
    

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);
    

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

JSON: why are forward slashes escaped?

The JSON spec says you CAN escape forward slash, but you don't have to.

Call Stored Procedure within Create Trigger in SQL Server

The following should do the trick - Only SqlServer


Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update
AS
BEGIN

SET NOCOUNT ON;

Declare @id int
DECLARE @cDate as DateTime
    set @cDate =(select Getdate())

select @id=deleted.Catagory_id from deleted
print @cDate

execute dbo.psp_Update_Category @id

END

Alter PROCEDURE dbo.psp_Update_Category
@id int
AS
BEGIN

DECLARE @cDate as DateTime
    set @cDate =(select Getdate())
    --Update Catagory_Master Set Modify_date=''+@cDate+'' Where Catagory_ID=@id   --@UserID
    Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')
END 

EXCEL VBA Check if entry is empty or not 'space'

Most terse version I can think of

Len(Trim(TextBox1.Value)) = 0

If you need to do this multiple times, wrap it in a function

Public Function HasContent(text_box as Object) as Boolean
    HasContent = (Len(Trim(text_box.Value)) > 0)
End Function

Usage

If HasContent(TextBox1) Then
    ' ...

How do I check if the mouse is over an element in jQuery?

JUST FYI for future finders of this.

I made a jQuery plugin that can do this and a lot more. In my plugin, to get all elements the cursor is currently hovered over, simply do the following:

$.cursor("isHover"); // will return jQ object of all elements the cursor is 
                     // currently over & doesn't require timer

As I mentioned, it also has alot of other uses as you can see in the

jsFiddle found here

HTML5 Video tag not working in Safari , iPhone and iPad

I had this problem where .mp4 playback in Safari didn't work, but in other browsers it was fine. The error that I was seeing in the console was: error media src not supported. In my case this turned out to be a MIME type issue, but not because it wasn't declared as MIME type in IIS, rather that it was declared twice (once in IIS and also in a web.config file). I found this out by trying to download the .mp4 file locally on the server. I removed the config file from the location of the content I was trying to play and it fixed the issue. I could have just deleted the MIME type from the web.config file, but in this case the web.config file wasn't needed.

Read/write to file using jQuery

Yes it is possible.

The technique is described below

http://jquery.tiddlywiki.org/twFile.html

Does JavaScript guarantee object property order?

As of ES2015, property order is guaranteed for certain methods that iterate over properties. but not others. Unfortunately, the methods which are not guaranteed to have an order are generally the most often used:

  • Object.keys, Object.values, Object.entries
  • for..in loops
  • JSON.stringify

But, as of ES2020, property order for these previously untrustworthy methods will be guaranteed by the specification to be iterated over in the same deterministic manner as the others, due to to the finished proposal: for-in mechanics.

Just like with the methods which have a guaranteed iteration order (like Reflect.ownKeys and Object.getOwnPropertyNames), the previously-unspecified methods will also iterate in the following order:

  • Numeric array keys, in ascending numeric order
  • All other non-Symbol keys, in insertion order
  • Symbol keys, in insertion order

This is what pretty much every implementation does already (and has done for many years), but the new proposal has made it official.

Although the current specification leaves for..in iteration order "almost totally unspecified, real engines tend to be more consistent:"

The lack of specificity in ECMA-262 does not reflect reality. In discussion going back years, implementors have observed that there are some constraints on the behavior of for-in which anyone who wants to run code on the web needs to follow.

Because every implementation already iterates over properties predictably, it can be put into the specification without breaking backwards compatibility.


There are a few weird cases which implementations currently do not agree on, and in such cases, the resulting order will continue be unspecified. For property order to be guaranteed:

Neither the object being iterated nor anything in its prototype chain is a proxy, typed array, module namespace object, or host exotic object.

Neither the object nor anything in its prototype chain has its prototype change during iteration.

Neither the object nor anything in its prototype chain has a property deleted during iteration.

Nothing in the object's prototype chain has a property added during iteration.

No property of the object or anything in its prototype chain has its enumerability change during iteration.

No non-enumerable property shadows an enumerable one.

How can I change a file's encoding with vim?

From the doc:

:write ++enc=utf-8 russian.txt

So you should be able to change the encoding as part of the write command.

Can Windows' built-in ZIP compression be scripted?

to create a compressed archive you can use the utility MAKECAB.EXE

How to execute a remote command over ssh with arguments?

Reviving an old thread, but this pretty clean approach was not listed.

function mycommand() {
    ssh [email protected] <<+
    cd testdir;./test.sh "$1"
+
}

Find a string by searching all tables in SQL Server Management Studio 2008

I have written a SP for the this which returns the search results in form of Table name, the Column names in which the search keyword string was found as well as the searches the corresponding rows as shown in below screen shot.

Sample Search Result

This might not be the most efficient solution but you can always modify and use it according to your need.

IF OBJECT_ID('sp_KeywordSearch', 'P') IS NOT NULL
    DROP PROC sp_KeywordSearch
GO

CREATE PROCEDURE sp_KeywordSearch @KeyWord NVARCHAR(100)
AS
BEGIN
    DECLARE @Result TABLE
        (TableName NVARCHAR(300),
         ColumnName NVARCHAR(MAX))

    DECLARE @Sql NVARCHAR(MAX),
        @TableName NVARCHAR(300),
        @ColumnName NVARCHAR(300),
        @Count INT

    DECLARE @tableCursor CURSOR

    SET @tableCursor = CURSOR LOCAL SCROLL FOR
    SELECT  N'SELECT @Count = COUNT(1) FROM [dbo].[' + T.TABLE_NAME + '] WITH (NOLOCK) WHERE CAST([' + C.COLUMN_NAME +
            '] AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + N'%''',
            T.TABLE_NAME,
            C.COLUMN_NAME
    FROM    INFORMATION_SCHEMA.TABLES AS T WITH (NOLOCK)
    INNER JOIN INFORMATION_SCHEMA.COLUMNS AS C WITH (NOLOCK)
    ON      T.TABLE_SCHEMA = C.TABLE_SCHEMA AND
            T.TABLE_NAME = C.TABLE_NAME
    WHERE   T.TABLE_TYPE = 'BASE TABLE' AND
            C.TABLE_SCHEMA = 'dbo' AND
            C.DATA_TYPE NOT IN ('image', 'timestamp')

    OPEN @tableCursor
    FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName

    WHILE (@@FETCH_STATUS = 0)
    BEGIN
        SET @Count = 0

        EXEC sys.sp_executesql
            @Sql,
            N'@Count INT OUTPUT',
            @Count OUTPUT

        IF @Count > 0
        BEGIN
            INSERT  INTO @Result
                    (TableName, ColumnName)
            VALUES  (@TableName, @ColumnName)
        END

        FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
    END

    CLOSE @tableCursor
    DEALLOCATE @tableCursor

    SET @tableCursor = CURSOR LOCAL SCROLL FOR
    SELECT  SUBSTRING(TB.Sql, 1, LEN(TB.Sql) - 3) AS Sql, TB.TableName, SUBSTRING(TB.Columns, 1, LEN(TB.Columns) - 1) AS Columns
    FROM    (SELECT R.TableName, (SELECT R2.ColumnName + ', ' FROM @Result AS R2 WHERE R.TableName = R2.TableName FOR XML PATH('')) AS Columns,
                    'SELECT * FROM ' + R.TableName + ' WITH (NOLOCK) WHERE ' +
                    (SELECT 'CAST(' + R2.ColumnName + ' AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + '%'' OR '
                     FROM   @Result AS R2
                     WHERE  R.TableName = R2.TableName
                    FOR
                     XML PATH('')) AS Sql
             FROM   @Result AS R
             GROUP BY R.TableName) TB
    ORDER BY TB.Sql

    OPEN @tableCursor
    FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName

    WHILE (@@FETCH_STATUS = 0)
    BEGIN
        PRINT @Sql
        SELECT  @TableName AS [Table],
                @ColumnName AS Columns
        EXEC(@Sql)

        FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
    END

    CLOSE @tableCursor
    DEALLOCATE @tableCursor

END

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.