Programs & Examples On #Rotateanimation

View's getWidth() and getHeight() returns 0

We need to wait for view will be drawn. For this purpose use OnPreDrawListener. Kotlin example:

val preDrawListener = object : ViewTreeObserver.OnPreDrawListener {

                override fun onPreDraw(): Boolean {
                    view.viewTreeObserver.removeOnPreDrawListener(this)

                    // code which requires view size parameters

                    return true
                }
            }

            view.viewTreeObserver.addOnPreDrawListener(preDrawListener)

How to make a smooth image rotation in Android?

Rotation Object programmatically.

// clockwise rotation :

    public void rotate_Clockwise(View view) {
        ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", 180f, 0f);
//        rotate.setRepeatCount(10);
        rotate.setDuration(500);
        rotate.start();
    }

// AntiClockwise rotation :

 public void rotate_AntiClockwise(View view) {
        ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", 0f, 180f);
//        rotate.setRepeatCount(10);
        rotate.setDuration(500);
        rotate.start();
    } 

view is object of your ImageView or other widgets.

rotate.setRepeatCount(10); use to repeat your rotation.

500 is your animation time duration.

Check if enum exists in Java

Most of the answers suggest either using a loop with equals to check if the enum exists or using try/catch with enum.valueOf(). I wanted to know which method is faster and tried it. I am not very good at benchmarking, so please correct me if I made any mistakes.

Heres the code of my main class:

    package enumtest;

public class TestMain {

    static long timeCatch, timeIterate;
    static String checkFor;
    static int corrects;

    public static void main(String[] args) {
        timeCatch = 0;
        timeIterate = 0;
        TestingEnum[] enumVals = TestingEnum.values();
        String[] testingStrings = new String[enumVals.length * 5];
        for (int j = 0; j < 10000; j++) {
            for (int i = 0; i < testingStrings.length; i++) {
                if (i % 5 == 0) {
                    testingStrings[i] = enumVals[i / 5].toString();
                } else {
                    testingStrings[i] = "DOES_NOT_EXIST" + i;
                }
            }

            for (String s : testingStrings) {
                checkFor = s;
                if (tryCatch()) {
                    ++corrects;
                }
                if (iterate()) {
                    ++corrects;
                }
            }
        }

        System.out.println(timeCatch / 1000 + "us for try catch");
        System.out.println(timeIterate / 1000 + "us for iterate");
        System.out.println(corrects);
    }

    static boolean tryCatch() {
        long timeStart, timeEnd;
        timeStart = System.nanoTime();
        try {
            TestingEnum.valueOf(checkFor);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        } finally {
            timeEnd = System.nanoTime();
            timeCatch += timeEnd - timeStart;
        }

    }

    static boolean iterate() {
        long timeStart, timeEnd;
        timeStart = System.nanoTime();
        TestingEnum[] values = TestingEnum.values();
        for (TestingEnum v : values) {
            if (v.toString().equals(checkFor)) {
                timeEnd = System.nanoTime();
                timeIterate += timeEnd - timeStart;
                return true;
            }
        }
        timeEnd = System.nanoTime();
        timeIterate += timeEnd - timeStart;
        return false;
    }
}

This means, each methods run 50000 times the lenght of the enum I ran this test multiple times, with 10, 20, 50 and 100 enum constants. Here are the results:

  • 10: try/catch: 760ms | iteration: 62ms
  • 20: try/catch: 1671ms | iteration: 177ms
  • 50: try/catch: 3113ms | iteration: 488ms
  • 100: try/catch: 6834ms | iteration: 1760ms

These results were not exact. When executing it again, there is up to 10% difference in the results, but they are enough to show, that the try/catch method is far less efficient, especially with small enums.

jQuery - setting the selected value of a select control via its text description

This line worked:

$("#myDropDown option:contains(myText)").attr('selected', true);

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

MySQL is notoriously cranky, especially with regards to foreign keys and triggers. I am right now in the process of fine tuning one such database, and ran into this problem. It is not self evident or intuitive, so here it goes:

Besides checking if the two columns you want to reference in the relationship have the same data type, you must also make sure the column on the table you are referencing is an index. If you are using the MySQL Workbench, select the tab "Indexes" right next to "Columns" and make sure the column referenced by the foreign key is an index. If not, create one, name it something meaningful, and give it the type "INDEX".

A good practice is to clean up the tables involved in relationships to make sure previous attempts did not create indexes you don't want or need.

I hope it helped, some MySQL errors are maddening to track.

Stored procedure - return identity as output parameter or scalar

Either as recordset or output parameter. The latter has less overhead and I'd tend to use that rather than a single column/row recordset.

If I expected to >1 row I'd use the OUTPUT clause and a recordset

Return values would normally be used for error handling.

How to change environment's font size?

Currently it is not possible to change the font family or size outside the editor. You can however zoom the entire user interface in and out from the View menu.

Update for our VS Code 1.0 release:

A newly introduced setting window.zoomLevel allows to persist the zoom level for good! It can have both negative and positive values to zoom in or out.

How to read/write a boolean when implementing the Parcelable interface?

I normally have them in an array and call writeBooleanArray and readBooleanArray

If it's a single boolean you need to pack, you could do this:

parcel.writeBooleanArray(new boolean[] {myBool});

How to form tuple column from two columns in Pandas

Pandas has the itertuples method to do exactly this:

list(df[['lat', 'long']].itertuples(index=False, name=None))

What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki


Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.


gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

How to fix "set SameSite cookie to none" warning?

I ended up fixing our Ubuntu 18.04 / Apache 2.4.29 / PHP 7.2 install for Chrome 80 by installing mod_headers:

a2enmod headers

Adding the following directive to our Apache VirtualHost configurations:

Header edit Set-Cookie ^(.*)$ "$1; Secure; SameSite=None"

And restarting Apache:

service apache2 restart

In reviewing the docs (http://www.balkangreenfoundation.org/manual/en/mod/mod_headers.html) I noticed the "always" condition has certain situations where it does not work from the same pool of response headers. Thus not using "always" is what worked for me with PHP but the docs suggest that if you want to cover all your bases you could add the directive both with and without "always". I have not tested that.

GridView - Show headers on empty data source

Juste add ShowHeaderWhenEmpty property and set it at true

This solution works for me

What is the `data-target` attribute in Bootstrap 3?

data-target is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.

The data-target attribute should contain a CSS selector that points to the HTML Element that will be changed.

Modal Example Code from BS3:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  [...]
</div>

In this example, the button has data-target="#myModal", if you click on it, <div id="myModal">...</div> will be modified (in this case faded in). This happens because #myModal in CSS selectors points to elements that have an id attribute with the myModal value.

Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

How to create and write to a txt file using VBA

Use FSO to create the file and write to it.

Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test" 
oFile.Close
Set fso = Nothing
Set oFile = Nothing    

See the documentation here:

preg_match in JavaScript?

JavaScript has a RegExp object which does what you want. The String object has a match() function that will help you out.

var matches = text.match(/price\[(\d+)\]\[(\d+)\]/);
var productId = matches[1];
var shopId    = matches[2];

How to make the web page height to fit screen height

As another guy described here, all you need to do is add

height: 100vh;

to the style of whatever you need to fill the screen

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

In my case the problem was that many scikit functions return numpy arrays, which are devoid of pandas index. So there was an index mismatch when I used those numpy arrays to build new DataFrames and then I tried to mix them with the original data.

Setting the default Java character encoding

Recently I bumped into a local company's Notes 6.5 system and found out the webmail would show unidentifiable characters on a non-Zhongwen localed Windows installation. Have dug for several weeks online, figured it out just few minutes ago:

In Java properties, add the following string to Runtime Parameters

-Dfile.encoding=MS950 -Duser.language=zh -Duser.country=TW -Dsun.jnu.encoding=MS950

UTF-8 setting would not work in this case.

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

Get the ID of a drawable in ImageView

Even easier: just store the R.drawable id in the view's id: use v.setId(). Then get it back with v.getId().

How can I get the value of a registry key from within a batch script?

I've come across many errors on Windows XP computers when using WMIC (eg due to corrupted files on machines). Hence imo best not to use WMIC for Win XP in code. No problems with WMIC on Win 7 though.

AngularJS routing without the hash '#'

If you enabled html5mode as others have said, and create an .htaccess file with the following contents (adjust for your needs):

RewriteEngine   On
RewriteBase     /
RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_FILENAME} !-d
RewriteRule     ./index.html [L]

Users will be directed to the your app when they enter a proper route, and your app will read the route and bring them to the correct "page" within it.

EDIT: Just make sure not to have any file or directory names conflict with your routes.

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

Dealing with commas in a CSV file

Put double quotes around strings. That is generally what Excel does.

Ala Eli,

you escape a double quote as two double quotes. E.g. "test1","foo""bar","test2"

What is DOM element?

See that your statements refer to "elements of the DOM", which are things such as the HTML tags (A, INPUT, etc). Thse statements simply mean that multiple CSS classes may be assigned to one such element.

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

Only need:

var place = autocomplete.getPlace();
// get lat
var lat = place.geometry.location.lat();
// get lng
var lng = place.geometry.location.lng();

How do I shut down a python simpleHTTPserver?

Turns out there is a shutdown, but this must be initiated from another thread.

This solution worked for me: https://stackoverflow.com/a/22533929/573216

Why call super() in a constructor?

There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).

An example, where the explicit call to super() gives you some extra control over the title of the frame:

class MyFrame extends JFrame
{
    public MyFrame() {
        super("My Window Title");
        ...
    }
}

including parameters in OPENQUERY

Actually, We found a way to do this:

DECLARE @username varchar(50)
SET @username = 'username'
DECLARE @Output as numeric(18,4)
DECLARE @OpenSelect As nvarchar(500)
SET @OpenSelect = '(SELECT @Output = CAST((CAST(pwdLastSet As bigint) / 864000000000) As numeric(18,4)) FROM OpenQuery (ADSI,''SELECT pwdLastSet
                                FROM  ''''LDAP://domain.net.intra/DC=domain,DC=net,DC=intra''''
                                WHERE objectClass =  ''''User'''' AND sAMAccountName = ''''' + @username + '''''
                          '') AS tblADSI)'
EXEC sp_executesql @OpenSelect, N'@Output numeric(18,4) out', @Output out
SELECT @Output As Outputs

This will assign the result of the OpenQuery execution, in the variable @Output.

We tested for Store procedure in MSSQL 2012, but should work with MSSQL 2008+.

Microsoft Says that sp_executesql(Transact-SQL): Applies to: SQL Server (SQL Server 2008 through current version), Windows Azure SQL Database (Initial release through current release). (http://msdn.microsoft.com/en-us/library/ms188001.aspx)

'Missing contentDescription attribute on image' in XML

If you don't care at all do this:

    android:contentDescription="@null"

Although I would advise the accepted solutions, this is a hack :D

How to get back to the latest commit after checking out a previous commit?

If you know the commit you want to return to is the head of some branch, or is tagged, then you can just

git checkout branchname

You can also use git reflog to see what other commits your HEAD (or any other ref) has pointed to in the past.


Edited to add:

In newer versions of Git, if you only ran git checkout or something else to move your HEAD once, you can also do

git checkout -

to switch back to wherever it was before the last checkout. This was motivated by the analogy to the shell idiom cd - to go back to whatever working directory one was previously in.

PHP Warning: PHP Startup: ????????: Unable to initialize module

try to upgrade each of those modules using pecl command

# pecl upgrade fileinfo
# pecl upgrade memcache
# pecl upgrade mhash
# pecl upgrade readline

etc...

Error in plot.window(...) : need finite 'xlim' values

I had the same problem. My solution was to make all vectors numeric.

How to check Elasticsearch cluster health?

To check on elasticsearch cluster health you need to use

curl localhost:9200/_cat/health

More on the cat APIs here.

I usually use elasticsearch-head plugin to visualize that.

You can find it's github project here.

It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head and then you can open localhost:9200/_plugin/head/ in your web brower.

You should have something that looks like this :

enter image description here

Multiline editing in Visual Studio Code

In addition to all of the answers, there is one more way. Select the lines you want and then press:

  • Windows: Shift + Alt + i
  • Mac: shift + option + i

This puts a cursor in every row in the selection.

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

The docs give a fair indicator of what's required., however requests allow us to skip a few steps:

You only need to install the security package extras (thanks @admdrew for pointing it out)

$ pip install requests[security]

or, install them directly:

$ pip install pyopenssl ndg-httpsclient pyasn1

Requests will then automatically inject pyopenssl into urllib3


If you're on ubuntu, you may run into trouble installing pyopenssl, you'll need these dependencies:

$ apt-get install libffi-dev libssl-dev

How to exit a 'git status' list in a terminal?

Please try this steps in git bash, It may help you.

  1. CTRL + C
  2. :qa!

Can I have multiple primary keys in a single table?

A primary key is the key that uniquely identifies a record and is used in all indexes. This is why you can't have more than one. It is also generally the key that is used in joining to child tables but this is not a requirement. The real purpose of a PK is to make sure that something allows you to uniquely identify a record so that data changes affect the correct record and so that indexes can be created.

However, you can put multiple fields in one primary key (a composite PK). This will make your joins slower (espcially if they are larger string type fields) and your indexes larger but it may remove the need to do joins in some of the child tables, so as far as performance and design, take it on a case by case basis. When you do this, each field itself is not unique, but the combination of them is. If one or more of the fields in a composite key should also be unique, then you need a unique index on it. It is likely though that if one field is unique, this is a better candidate for the PK.

Now at times, you have more than one candidate for the PK. In this case you choose one as the PK or use a surrogate key (I personally prefer surrogate keys for this instance). And (this is critical!) you add unique indexes to each of the candidate keys that were not chosen as the PK. If the data needs to be unique, it needs a unique index whether it is the PK or not. This is a data integrity issue. (Note this is also true anytime you use a surrogate key; people get into trouble with surrogate keys because they forget to create unique indexes on the candidate keys.)

There are occasionally times when you want more than one surrogate key (which are usually the PK if you have them). In this case what you want isn't more PK's, it is more fields with autogenerated keys. Most DBs don't allow this, but there are ways of getting around it. First consider if the second field could be calculated based on the first autogenerated key (Field1 * -1 for instance) or perhaps the need for a second autogenerated key really means you should create a related table. Related tables can be in a one-to-one relationship. You would enforce that by adding the PK from the parent table to the child table and then adding the new autogenerated field to the table and then whatever fields are appropriate for this table. Then choose one of the two keys as the PK and put a unique index on the other (the autogenerated field does not have to be a PK). And make sure to add the FK to the field that is in the parent table. In general if you have no additional fields for the child table, you need to examine why you think you need two autogenerated fields.

Access mysql remote database from command line

edit my.cnf file:

vi /etc/my.cnf:

make sure that:

bind-address=YOUR-SERVER-IP

and if you have the line:

skip-networking

make sure to comment it:

#skip-networking

don't forget to restart:

/etc/init.d/mysqld restart

How do you clear your Visual Studio cache on Windows Vista?

I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.

So I cleared the .Net Temp folder.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.

My issue was sorted.

What is the role of "Flatten" in Keras?

I came across this recently, it certainly helped me understand: https://www.cs.ryerson.ca/~aharley/vis/conv/

So there's an input, a Conv2D, MaxPooling2D etc, the Flatten layers are at the end and show exactly how they are formed and how they go on to define the final classifications (0-9).

CSS3 Continuous Rotate Animation (Just like a loading sundial)

You could use animation like this:

-webkit-animation: spin 1s infinite linear;

@-webkit-keyframes spin {
    0%   {-webkit-transform: rotate(0deg)}
    100% {-webkit-transform: rotate(360deg)}
}

How do I iterate over a JSON structure?

_x000D_
_x000D_
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
    
for (var i = 0; i < arr.length; i++){
  document.write("<br><br>array index: " + i);
  var obj = arr[i];
  for (var key in obj){
    var value = obj[key];
    document.write("<br> - " + key + ": " + value);
  }
}
_x000D_
_x000D_
_x000D_

note: the for-in method is cool for simple objects. Not very smart to use with DOM object.

How to debug apk signed for release?

Add the following to your app build.gradle and select the specified release build variant and run

signingConfigs {
        config {
            keyAlias 'keyalias'
            keyPassword 'keypwd'
            storeFile file('<<KEYSTORE-PATH>>.keystore')
            storePassword 'pwd'
        }
    }
    buildTypes {
      release {
          debuggable true
          signingConfig signingConfigs.config
          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

$('body').on('click', '.anything', function(){})

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

$(document).on('click','body *',function(){
    //  $(this) = your current element that clicked.
    // additional code
});

Git add all subdirectories

I saw this problem before, when the (sub)folder I was trying to add had its name begin with "_Something_"

I removed the underscores and it worked. Check to see if your folder has characters which may be causing problems.

Custom thread pool in Java 8 parallel stream

We can change the default parallelism using the following property:

-Djava.util.concurrent.ForkJoinPool.common.parallelism=16

which can set up to use more parallelism.

phpinfo() is not working on my CentOS server

Save the page which contains

<?php
    phpinfo();
?>

with the .php extension. Something like info.php, not info.html...

How to find the remainder of a division in C?

All the above answers are correct. Just providing with your dataset to find perfect divisor:

#include <stdio.h>

int main() 
{

int arr[7] = {3,5,7,8,9,17,19};
int j = 51;
int i = 0;

for (i=0 ; i < 7; i++) {
    if (j % arr[i] == 0)
        printf("%d is the perfect divisor of %d\n", arr[i], j);
}

return 0;
}

Linux : Search for a Particular word in a List of files under a directory

You can use this command:

grep -rn "string" *

n for showing line number with the filename r for recursive

Shift column in pandas dataframe up by one?

shift column gdp up:

df.gdp = df.gdp.shift(-1)

and then remove the last row

How can a Javascript object refer to values in itself?

This is not JSON. JSON was designed to be simple; allowing arbitrary expressions is not simple.

In full JavaScript, I don't think you can do this directly. You cannot refer to this until the object called obj is fully constructed. So you need a workaround, that someone with more JavaScript-fu than I will provide.

Correctly ignore all files recursively under a specific folder except for a specific file type

The best answer is to add a Resources/.gitignore file under Resources containing:

# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo

You will need to edit that pattern if you add directories deeper than specified.

Can I use wget to check , but not download

There is the command line parameter --spider exactly for this. In this mode, wget does not download the files and its return value is zero if the resource was found and non-zero if it was not found. Try this (in your favorite shell):

wget -q --spider address
echo $?

Or if you want full output, leave the -q off, so just wget --spider address. -nv shows some output, but not as much as the default.

CRC32 C or C++ implementation

Use the Boost C++ libraries. There is a CRC included there and the license is good.

SQL Server ORDER BY date and nulls last

If your SQL doesn't support NULLS FIRST or NULLS LAST, the simplest way to do this is to use the value IS NULL expression:

ORDER BY Next_Contact_Date IS NULL, Next_Contact_Date

to put the nulls at the end (NULLS LAST) or

ORDER BY Next_Contact_Date IS NOT NULL, Next_Contact_Date

to put the nulls at the front. This doesn't require knowing the type of the column and is easier to read than the CASE expression.

EDIT: Alas, while this works in other SQL implementations like PostgreSQL and MySQL, it doesn't work in MS SQL Server. I didn't have a SQL Server to test against and relied on Microsoft's documentation and testing with other SQL implementations. According to Microsoft, value IS NULL is an expression that should be usable just like any other expression. And ORDER BY is supposed to take expressions just like any other statement that takes an expression. But it doesn't actually work.

The best solution for SQL Server therefore appears to be the CASE expression.

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

Just like Nasser, I know this was a while ago but I wanted to post my solution for anyone who has this problem in the future.

I had my report setup so that it would use a data connection in a Data Connection library hosted on SharePoint. My issue was that I did not have the data connection 'approved' so that it was usable by other users.

Another thing to look for would to make sure that the permissions on that Data Connection library also allows read to the select users.

Hope this helps someone sooner or later!

Set focus on TextBox in WPF from view model

System.Windows.Forms.Application.DoEvents();
Keyboard.Focus(tbxLastName);

Jinja2 shorthand conditional

Alternative way (but it's not python style. It's JS style)

{{ files and 'Update' or 'Continue' }}

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

I had a similar issue recently which turned out to be due to ssl_ciphers that I was using.

From http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html,

"CloudFront forwards HTTPS requests to the origin server using the SSLv3 or TLSv1 protocols and the AES128-SHA1 or RC4-MD5 ciphers. If your origin server does not support either the AES128-SHA1 or RC4-MD5 ciphers, CloudFront cannot establish an SSL connection to your origin. "

I had to change my nginx confg to add AES128-SHA ( deprecated RC4:HIGH ) to ssl_ciphers to fix the 302 error. I hope this helps. I have pasted the line from my ssl.conf

ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:RSA+3DES:AES128-SHA:!ADH:!AECDH:!MD5;

Difference between @click and v-on:click Vuejs

They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.

Source: official documentation.

What are the differences between C, C# and C++ in terms of real-world applications?

C is the bare-bones, simple, clean language that makes you do everything yourself. It doesn't hold your hand, it doesn't stop you from shooting yourself in the foot. But it has everything you need to do what you want.

C++ is C with classes added, and then a whole bunch of other things, and then some more stuff. It doesn't hold your hand, but it'll let you hold your own hand, with add-on GC, or RAII and smart-pointers. If there's something you want to accomplish, chances are there's a way to abuse the template system to give you a relatively easy syntax for it. (moreso with C++0x). This complexity also gives you the power to accidentally create a dozen instances of yourself and shoot them all in the foot.

C# is Microsoft's stab at improving on C++ and Java. Tons of syntactical features, but no where near the complexity of C++. It runs in a full managed environment, so memory management is done for you. It does let you "get dirty" and use unsafe code if you need to, but it's not the default, and you have to do some work to shoot yourself.

How to install a node.js module without using npm?

You need to download their source from the github. Find the main file and then include it in your main file.

An example of this can be found here > How to manually install a node.js module?

Usually you need to find the source and go through the package.json file. There you can find which is the main file. So that you can include that in your application.

To include example.js in your app. Copy it in your application folder and append this on the top of your main js file.

var moduleName = require("path/to/example.js")

Iterating through a variable length array

here is an example, where the length of the array is changed during execution of the loop

import java.util.ArrayList;
public class VariableArrayLengthLoop {

public static void main(String[] args) {

    //create new ArrayList
    ArrayList<String> aListFruits = new ArrayList<String>();

    //add objects to ArrayList
    aListFruits.add("Apple");
    aListFruits.add("Banana");
    aListFruits.add("Orange");
    aListFruits.add("Strawberry");

    //iterate ArrayList using for loop
    for(int i = 0; i < aListFruits.size(); i++){

        System.out.println( aListFruits.get(i) + " i = "+i );
         if ( i == 2 ) {
                aListFruits.add("Pineapple");  
                System.out.println( "added now a Fruit to the List "); 
                }
        }
    }
}

How to pass 2D array (matrix) in a function in C?

Easiest Way in Passing A Variable-Length 2D Array

Most clean technique for both C & C++ is: pass 2D array like a 1D array, then use as 2D inside the function.

#include <stdio.h>

void func(int row, int col, int* matrix){
    int i, j;
    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
        }
        printf("\n");
    }
}

int main(){
    int matrix[2][3] = { {0, 1, 2}, {3, 4, 5} };
    func(2, 3, matrix[0]);

    return 0;
}

Internally, no matter how many dimensions an array has, C/C++ always maintains a 1D array. And so, we can pass any multi-dimensional array like this.

input file appears to be a text format dump. Please use psql

if you use pg_dump with -Fp to backup in plain text format, use following command:

cat db.txt | psql dbname

to copy all data to your database with name dbname

How can I count all the lines of code in a directory recursively?

If you're on Linux (and I take it you are), I recommend my tool polyglot. It is dramatically faster than either sloccount or cloc and it is more featureful than sloccount.

You can invoke it with

poly .

or

poly

so it's much more user-friendly than some convoluted Bash script.

Convert Uri to String and String to Uri

I am not sure if you got this resolved. To follow up on "CommonsWare's" comment.

That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.

Change

Uri uri=Uri.parse("/external/images/media/470939");

to

Uri uri=Uri.parse("content://external/images/media/470939");

in my case

Uri uri = Uri.parse("content://media/external/images/media/6562");

Bubble Sort Homework

arr = [5,4,3,1,6,8,10,9] # array not sorted

for i in range(len(arr)):
    for j in range(i, len(arr)):
        if(arr[i] > arr[j]):
            arr[i], arr[j] = arr[j], arr[i]

            print (arr)

How do I access properties of a javascript object if I don't know the names?

You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."

You can use any object in place of stats:

_x000D_
_x000D_
var stats = {_x000D_
  a: 3,_x000D_
  b: 6,_x000D_
  d: 7,_x000D_
  erijgolekngo: 35_x000D_
}_x000D_
/*  this is the answer here  */_x000D_
for (var key in Object.keys(stats)) {_x000D_
  var t = Object.keys(stats)[key];_x000D_
  console.log(t + " value =: " + stats[t]);_x000D_
}
_x000D_
_x000D_
_x000D_

What datatype should be used for storing phone numbers in SQL Server 2005?

We use varchar(15) and certainly index on that field.

The reason being is that International standards can support up to 15 digits

Wikipedia - Telephone Number Formats

If you do support International numbers, I recommend the separate storage of a World Zone Code or Country Code to better filter queries by so that you do not find yourself parsing and checking the length of your phone number fields to limit the returned calls to USA for example

Permission denied on accessing host directory in Docker

It is an SELinux issue.

You can temporarily issue

su -c "setenforce 0"

on the host to access or else add an SELinux rule by running

chcon -Rt svirt_sandbox_file_t /path/to/volume

How to upload folders on GitHub

You can also use the command line, Change directory where your folder is located then type the following :

     git init
     git add <folder1> <folder2> <etc.>
     git commit -m "Your message about the commit"
     git remote add origin https://github.com/yourUsername/yourRepository.git
     git push -u origin master
     git push origin master  

Getting Django admin url for an object

from django.core.urlresolvers import reverse
def url_to_edit_object(obj):
  url = reverse('admin:%s_%s_change' % (obj._meta.app_label,  obj._meta.model_name),  args=[obj.id] )
  return u'<a href="%s">Edit %s</a>' % (url,  obj.__unicode__())

This is similar to hansen_j's solution except that it uses url namespaces, admin: being the admin's default application namespace.

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

Example to get the last input element:

document.querySelector(".groups-container >div:last-child input")

Check if a string contains a number

What about this one?

import string

def containsNumber(line):
    res = False
    try:
        for val in line.split():
            if (float(val.strip(string.punctuation))):
                res = True
                break
    except ValueError:
        pass
    return res

containsNumber('234.12 a22') # returns True
containsNumber('234.12L a22') # returns False
containsNumber('234.12, a22') # returns True

How to store the hostname in a variable in a .bat file?

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

LINQ: Distinct values

In addition to Jon Skeet's answer, you can also use the group by expressions to get the unique groups along w/ a count for each groups iterations:

var query = from e in doc.Elements("whatever")
            group e by new { id = e.Key, val = e.Value } into g
            select new { id = g.Key.id, val = g.Key.val, count = g.Count() };

Why did my Git repo enter a detached HEAD state?

Detached HEAD means that what's currently checked out is not a local branch.

Some scenarios that will result in a Detached HEAD state:

  • If you checkout a remote branch, say origin/master. This is a read-only branch. Thus, when creating a commit from origin/master it will be free-floating, i.e. not connected to any branch.

  • If you checkout a specific tag or commit. When doing a new commit from here, it will again be free-floating, i.e. not connected to any branch. Note that when a branch is checked out, new commits always gets automatically placed at the tip.

    When you want to go back and checkout a specific commit or tag to start working from there, you could create a new branch originating from that commit and switch to it by git checkout -b new_branch_name. This will prevent the Detached HEAD state as you now have a branch checked out and not a commit.

Is there a way to word-wrap long words in a div?

Reading the original comment, rutherford is looking for a cross-browser way to wrap unbroken text (inferred by his use of word-wrap for IE, designed to break unbroken strings).

/* Source: http://snipplr.com/view/10979/css-cross-browser-word-wrap */
.wordwrap { 
   white-space: pre-wrap;      /* CSS3 */   
   white-space: -moz-pre-wrap; /* Firefox */    
   white-space: -pre-wrap;     /* Opera <7 */   
   white-space: -o-pre-wrap;   /* Opera 7 */    
   word-wrap: break-word;      /* IE */
}

I've used this class for a bit now, and works like a charm. (note: I've only tested in FireFox and IE)

How to specify a min but no max decimal using the range data annotation attribute?

[Range(0.01,100000000,ErrorMessage = "Price must be greter than zero !")]

How to read data when some numbers contain commas as thousand separator?

We can also use readr::parse_number, the columns must be characters though. If we want to apply it for multiple columns we can loop through columns using lapply

df[2:3] <- lapply(df[2:3], readr::parse_number)
df

#  a        b        c
#1 a    12234       12
#2 b      123  1234123
#3 c     1234     1234
#4 d 13456234    15342
#5 e    12312 12334512

Or use mutate_at from dplyr to apply it to specific variables.

library(dplyr)
df %>% mutate_at(2:3, readr::parse_number)
#Or
df %>% mutate_at(vars(b:c), readr::parse_number)

data

df <- data.frame(a = letters[1:5], 
                 b = c("12,234", "123", "1,234", "13,456,234", "123,12"),
                 c = c("12", "1,234,123","1234", "15,342", "123,345,12"), 
                 stringsAsFactors = FALSE)

Set CSS property in Javascript?

<body>
  <h1 id="h1">Silence and Smile</h1><br />
  <h3 id="h3">Silence and Smile</h3>

  <script type="text/javascript">
    document.getElementById("h1").style.color = "Red";
    document.getElementById("h1").style.background = "Green";
    document.getElementById("h3").style.fontSize = "larger" ; 
    document.getElementById("h3").style.fontFamily = "Arial";
  </script>
</body>

Convert Text to Uppercase while typing in Text box

if you can use LinqToObjects in your Project

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   return YourTextBox.Text.Where(c=> c.ToUpper());
}

An if you can't use LINQ (e.g. your project's target FW is .NET Framework 2.0) then

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   YourTextBox.Text = YourTextBox.Text.ToUpper();
}

Why Text_Changed Event ?

There are few user input events in framework..

1-) OnKeyPressed fires (starts to work) when user presses to a key from keyboard after the key pressed and released

2-) OnKeyDown fires when user presses to a key from keyboard during key presses

3-) OnKeyUp fires when user presses to a key from keyboard and key start to release (user take up his finger from key)

As you see, All three are about keyboard event..So what about if the user copy and paste some data to the textbox?

if you use one of these keyboard events then your code work when and only user uses keyboard..in example if user uses a screen keyboard with mouse click or copy paste the data your code which implemented in keyboard events never fires (never start to work)

so, and Fortunately there is another option to work around : The Text Changed event..

Text Changed event don't care where the data comes from..Even can be a copy-paste, a touchscreen tap (like phones or tablets), a virtual keyboard, a screen keyboard with mouse-clicks (some bank operations use this to much more security, or may be your user would be a disabled person who can't press to a standard keyboard) or a code-injection ;) ..

No Matter !

Text Changed event just care about is there any changes with it's responsibility component area ( here, Your TextBox's Text area) or not..

If there is any change occurs, then your code which implemented under Text changed event works..

Reporting Services export to Excel with Multiple Worksheets

Here are screenshots for SQL Server 2008 R2, using SSRS Report Designer in Visual Studio 2010.

I have done screenshots as some of the dialogs are not easy to find.

1: Add the group

SsrsAddGroup

2: Specify the field you want to group on

SsrsAddGroupDialog

3: Now click on the group in the 'Row Groups' selector, directly below the report designer

SsrsRowGroupsSelector

4: F4 to select property pane; expand 'Group' and set Group > PageBreak > BreakLocation = 'Between', then enter the expression you want for Group > PageName

SsrsGroupProperty

5: Here is an example expression

SsrsGroupPropertyDialog

Here is the result of the report exported to Excel, with tabs named according to the PageName expression

SsrsExcelTabs

How to align an input tag to the center without specifying the width?

write this:

#siteInfo{text-align:center}
p, input{display:inline-block}

http://jsfiddle.net/XfSz6/

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

C# LINQ find duplicates in List

Linq query:

var query = from s2 in (from s in someList group s by new { s.Column1, s.Column2 } into sg select sg) where s2.Count() > 1 select s2;

How can I trim beginning and ending double quotes from a string?

Kotlin

In Kotlin you can use String.removeSurrounding(delimiter: CharSequence)

E.g.

string.removeSurrounding("\"")

Removes the given delimiter string from both the start and the end of this string if and only if it starts with and ends with the delimiter. Otherwise returns this string unchanged.

The source code looks like this:

public fun String.removeSurrounding(delimiter: CharSequence): String = removeSurrounding(delimiter, delimiter)

public fun String.removeSurrounding(prefix: CharSequence, suffix: CharSequence): String {
    if ((length >= prefix.length + suffix.length) && startsWith(prefix) && endsWith(suffix)) {
        return substring(prefix.length, length - suffix.length)
    }
    return this
}

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

Best way to convert IList or IEnumerable to Array

I feel like reinventing the wheel...

public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
    if (enumerable == null)
        throw new ArgumentNullException("enumerable");

    return enumerable as T[] ?? enumerable.ToArray();
}

Can't import javax.servlet.annotation.WebServlet

Simply add the below to your maven project pom.xml flie:

<dependencies>
          <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
         </dependency>
  </dependencies>

GitHub README.md center image

To extend the answer a little bit to support local images, just replace FILE_PATH_PLACEHOLDER to your image path and check it out.

<p align="center">
  <img src="FILE_PATH_PLACEHOLDER">
</p>

Input type=password, don't let browser remember the password

I've found the following works on Firefox and Chrome.

<form ... > <!-- more stuff -->
<input name="person" type="text" size=30 value="">
<input name="mypswd" type="password" size=6 value="" autocomplete="off">
<input name="userid" type="text" value="security" style="display:none">
<input name="passwd" type="password" value="faker" style="display:none">
<!-- more stuff --> </form>

All of these are within the forms section. "person" and "mypswd" are what you want, but the browser will save "userid" and "passwd" once, and never again since they don't change. You could eliminate the "person" field if you don't really need it. In that case, all you want is the "mypswd" field, which could change in some way known to the user of your web-page.

How to avoid HTTP error 429 (Too Many Requests) python

Writing this piece of code fixed my problem:

requests.get(link, headers = {'User-agent': 'your bot 0.1'})

How do operator.itemgetter() and sort() work?

You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter returns a callable:

>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8

To do it in a different way, you can use lambda:

a.sort(key=lambda x: x[1])

And reverse it:

a.sort(key=operator.itemgetter(1), reverse=True)

Sort by more than one column:

a.sort(key=operator.itemgetter(1,2))

See the sorting How To.

Difference between variable declaration syntaxes in Javascript (including global variables)?

<title>Index.html</title>
<script>
    var varDeclaration = true;
    noVarDeclaration = true;
    window.hungOnWindow = true;
    document.hungOnDocument = true;
</script>
<script src="external.js"></script>

/* external.js */

console.info(varDeclaration == true); // could be .log, alert etc
// returns false in IE8

console.info(noVarDeclaration == true); // could be .log, alert etc
// returns false in IE8

console.info(window.hungOnWindow == true); // could be .log, alert etc
// returns true in IE8

console.info(document.hungOnDocument == true); // could be .log, alert etc
// returns ??? in IE8 (untested!)  *I personally find this more clugy than hanging off window obj

Is there a global object that all vars are hung off of by default? eg: 'globals.noVar declaration'

Double precision floating values in Python?

Python's built-in float type has double precision (it's a C double in CPython, a Java double in Jython). If you need more precision, get NumPy and use its numpy.float128.

How to open select file dialog via js?

For the sake of completeness, Ron van der Heijden's solution in pure JavaScript:

<button onclick="document.querySelector('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">

Creating stored procedure and SQLite?

SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, stored procedures, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth

Source : Appropriate Uses For SQLite

How do I verify that a string only contains letters, numbers, underscores and dashes?

You could always use a list comprehension and check the results with all, it would be a little less resource intensive than using a regex: all([c in string.letters + string.digits + ["_", "-"] for c in mystring])

Rails: Adding an index after adding column

You can run another migration, just for the index:

class AddIndexToTable < ActiveRecord::Migration
  def change
    add_index :table, :user_id
  end
end

How to get file path from OpenFileDialog and FolderBrowserDialog?

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);

Is it possible to use 'else' in a list comprehension?

The syntax a if b else c is a ternary operator in Python that evaluates to a if the condition b is true - otherwise, it evaluates to c. It can be used in comprehension statements:

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

So for your example,

table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

How to distinguish mouse "click" and "drag"

Another solution for class based vanilla JS using a distance threshold

private initDetectDrag(element) {
    let clickOrigin = { x: 0, y: 0 };
    const dragDistanceThreshhold = 20;

    element.addEventListener('mousedown', (event) => {
        this.isDragged = false
        clickOrigin = { x: event.clientX, y: event.clientY };
    });
    element.addEventListener('mousemove', (event) => {
        if (Math.sqrt(Math.pow(clickOrigin.y - event.clientY, 2) + Math.pow(clickOrigin.x - event.clientX, 2)) > dragDistanceThreshhold) {
            this.isDragged = true
        }
    });
}

Add inside the class (SOMESLIDER_ELEMENT can also be document to be global):

private isDragged: boolean;
constructor() {
    this.initDetectDrag(SOMESLIDER_ELEMENT);
    this.doSomeSlideStuff(SOMESLIDER_ELEMENT);
    element.addEventListener('click', (event) => {
        if (!this.sliderIsDragged) {
            console.log('was clicked');
        } else {
            console.log('was dragged, ignore click or handle this');
        }
    }, false);
}

Create two-dimensional arrays and access sub-arrays in Ruby

rows, cols = x,y  # your values
grid = Array.new(rows) { Array.new(cols) }

As for accessing elements, this article is pretty good for step by step way to encapsulate an array in the way you want:

How to ruby array

How to normalize a histogram in MATLAB?

hist can not only plot an histogram but also return you the count of elements in each bin, so you can get that count, normalize it by dividing each bin by the total and plotting the result using bar. Example:

Y = rand(10,1);
C = hist(Y);
C = C ./ sum(C);
bar(C)

or if you want a one-liner:

bar(hist(Y) ./ sum(hist(Y)))

Documentation:

Edit: This solution answers the question How to have the sum of all bins equal to 1. This approximation is valid only if your bin size is small relative to the variance of your data. The sum used here correspond to a simple quadrature formula, more complex ones can be used like trapz as proposed by R. M.

Python: How to remove empty lists from a list?

Calling filter with None will filter out all falsey values from the list (which an empty list is)

list2 = filter(None, list1)

Python, Unicode, and the Windows console

TL;DR:

print(yourstring.encode('ascii','replace'));

I ran into this myself, working on a Twitch chat (IRC) bot. (Python 2.7 latest)

I wanted to parse chat messages in order to respond...

msg = s.recv(1024).decode("utf-8")

but also print them safely to the console in a human-readable format:

print(msg.encode('ascii','replace'));

This corrected the issue of the bot throwing UnicodeEncodeError: 'charmap' errors and replaced the unicode characters with ?.

Best practice to return errors in ASP.NET Web API

It looks like you're having more trouble with Validation than errors/exceptions so I'll say a bit about both.

Validation

Controller actions should generally take Input Models where the validation is declared directly on the model.

public class Customer
{ 
    [Require]
    public string Name { get; set; }
}

Then you can use an ActionFilter that automatically sends validation messages back to the client.

public class ValidationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var modelState = actionContext.ModelState;

        if (!modelState.IsValid) {
            actionContext.Response = actionContext.Request
                 .CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
        }
    }
} 

For more information about this check out http://ben.onfabrik.com/posts/automatic-modelstate-validation-in-aspnet-mvc

Error handling

It's best to return a message back to the client that represents the exception that happened (with relevant status code).

Out of the box you have to use Request.CreateErrorResponse(HttpStatusCode, message) if you want to specify a message. However, this ties the code to the Request object, which you shouldn't need to do.

I usually create my own type of "safe" exception that I expect the client would know how to handle and wrap all others with a generic 500 error.

Using an action filter to handle the exceptions would look like this:

public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        var exception = context.Exception as ApiException;
        if (exception != null) {
            context.Response = context.Request.CreateErrorResponse(exception.StatusCode, exception.Message);
        }
    }
}

Then you can register it globally.

GlobalConfiguration.Configuration.Filters.Add(new ApiExceptionFilterAttribute());

This is my custom exception type.

using System;
using System.Net;

namespace WebApi
{
    public class ApiException : Exception
    {
        private readonly HttpStatusCode statusCode;

        public ApiException (HttpStatusCode statusCode, string message, Exception ex)
            : base(message, ex)
        {
            this.statusCode = statusCode;
        }

        public ApiException (HttpStatusCode statusCode, string message)
            : base(message)
        {
            this.statusCode = statusCode;
        }

        public ApiException (HttpStatusCode statusCode)
        {
            this.statusCode = statusCode;
        }

        public HttpStatusCode StatusCode
        {
            get { return this.statusCode; }
        }
    }
}

An example exception that my API can throw.

public class NotAuthenticatedException : ApiException
{
    public NotAuthenticatedException()
        : base(HttpStatusCode.Forbidden)
    {
    }
}

throwing exceptions out of a destructor

The real question to ask yourself about throwing from a destructor is "What can the caller do with this?" Is there actually anything useful you can do with the exception, that would offset the dangers created by throwing from a destructor?

If I destroy a Foo object, and the Foo destructor tosses out an exception, what I can reasonably do with it? I can log it, or I can ignore it. That's all. I can't "fix" it, because the Foo object is already gone. Best case, I log the exception and continue as if nothing happened (or terminate the program). Is that really worth potentially causing undefined behavior by throwing from a destructor?

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;

https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat

From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

Load arrayList data into JTable

I created an arrayList from it and I somehow can't find a way to store this information into a JTable.

The DefaultTableModel doesn't support displaying custom Objects stored in an ArrayList. You need to create a custom TableModel.

You can check out the Bean Table Model. It is a reusable class that will use reflection to find all the data in your FootballClub class and display in a JTable.

Or, you can extend the Row Table Model found in the above link to make is easier to create your own custom TableModel by implementing a few methods. The JButtomTableModel.java source code give a complete example of how you can do this.

How to solve npm install throwing fsevents warning on non-MAC OS?

If anyone get this error for ionic cordova install . just use this code npm install --no-optional in your cmd. And then run this code npm install -g ionic@latest cordova

There has been an error processing your request, Error log record number

Rename pub/local.xml.sample into local.xml . then i will show you exactly error.

Length of array in function argument

As stated by @Will, the decay happens during the parameter passing. One way to get around it is to pass the number of elements. To add onto this, you may find the _countof() macro useful - it does the equivalent of what you've done ;)

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

Math.random() explanation

int randomWithRange(int min, int max)
{
   int range = (max - min) + 1;     
   return (int)(Math.random() * range) + min;
}

Output of randomWithRange(2, 5) 10 times:

5
2
3
3
2
4
4
4
5
4

The bounds are inclusive, ie [2,5], and min must be less than max in the above example.

EDIT: If someone was going to try and be stupid and reverse min and max, you could change the code to:

int randomWithRange(int min, int max)
{
   int range = Math.abs(max - min) + 1;     
   return (int)(Math.random() * range) + (min <= max ? min : max);
}

EDIT2: For your question about doubles, it's just:

double randomWithRange(double min, double max)
{
   double range = (max - min);     
   return (Math.random() * range) + min;
}

And again if you want to idiot-proof it it's just:

double randomWithRange(double min, double max)
{
   double range = Math.abs(max - min);     
   return (Math.random() * range) + (min <= max ? min : max);
}

Connect multiple devices to one device via Bluetooth

Bluetooth 4.0 Allows you in a Bluetooth piconet one master can communicate up to 7 active slaves, there can be some other devices up to 248 devices which sleeping.

Also you can use some slaves as bridge to participate with more devices.

Simple way to read single record from MySQL

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');  
$db->set_charset('utf8mb4');

if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
    $id = $row[0];
}

Eclipse hangs on loading workbench

The procedure shown at http://off-topic.biz/en/eclipse-hangs-at-startup-showing-only-the-splash-screen/ worked for me:

  1. cd .metadata/.plugins
  2. mv org.eclipse.core.resources org.eclipse.core.resources.bak
  3. Start eclipse. (It should show an error message or an empty workspace because no project is found.)
  4. Close all open editors tabs.
  5. Exit eclipse.
  6. rm -rf org.eclipse.core.resources (Delete the newly created directory.)
  7. mv org.eclipse.core.resources.bak/ org.eclipse.core.resources (Restore the original directory.)
  8. Start eclipse and start working. :-)

In other answers:

eclipse -clean -clearPersistedState

is mentioned - which seems to have the same or even better effect.

Here is a script for MacOS (using Macports) and Linux (tested on Ubuntu with Eclipse Equinox) to do the start with an an optional kill of the running eclipse. You might want to adapt the script to your needs. If you add new platforms please edit the script right in this answer.

#!/bin/bash
# WF 2014-03-14
#
# ceclipse:
#   start Eclipse cleanly
#
#   this script calls eclipse with -clean and -clearPersistedState
#   if an instance of eclipse is already running the user is asked
#   if it should be killed first and if answered yes the process will be killed
#
# usage: ceclipse
#

#
# error
#
#   show an error message and exit
#
#   params:
#     1: l_msg - the message to display
error() {
  local l_msg="$1"
  echo "error: $l_msg" 1>&2
  exit 1 
}

#
# autoinstall
#
#  check that l_prog is available by calling which
#  if not available install from given package depending on Operating system
#
#  params: 
#    1: l_prog: The program that shall be checked
#    2: l_linuxpackage: The apt-package to install from
#    3: l_macospackage: The MacPorts package to install from
#
autoinstall() {
  local l_prog=$1
  local l_linuxpackage=$2
  local l_macospackage=$3
  echo "checking that $l_prog  is installed on os $os ..."
  which $l_prog 
  if [ $? -eq 1 ]
  then
    case $os in 
      # Mac OS
      Darwin) 
        echo "installing $l_prog from MacPorts package $l_macospackage"        
        sudo port install $l_macospackage
      ;;
      # e.g. Ubuntu/Fedora/Debian/Suse
      Linux)
        echo "installing $l_prog from apt-package $l_linuxpackage"        
        sudo apt-get install $l_linuxpackage
      ;;
      # git bash (Windows)
      MINGW32_NT-6.1)
        error "$l_prog ist not installed"
      ;;
      *)
        error "unknown operating system $os" 
    esac
  fi
}

# global operating system variable
os=`uname`

# first set 
#  eclipse_proc - the name of the eclipse process to look for
#  eclipse_app - the name of the eclipse application to start
case $os in 
    # Mac OS
    Darwin) 
      eclipse_proc="Eclipse.app" 
      eclipse_app="/Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse"
      ;;
    # e.g. Ubuntu/Fedora/Debian/Suse
    Linux)
      eclipse_proc="/usr/lib/eclipse//plugins/org.eclipse.equinox.launcher_1.2.0.dist.jar"
      eclipse_app=`which eclipse`
      ;;
    # git bash (Windows)
    MINGW32_NT-6.1)
      eclipse_app=`which eclipse`
      error "$os not implemented yet"
      ;;
    *)
      error "unknown operating system $os" 
esac

# check that pgrep is installed or install it
autoinstall pgrep procps

# check whether eclipse process is running
# first check that we only find one process
echo "looking for $eclipse_proc process"
pgrep -fl "$eclipse_proc"
# can't use -c option on MacOS - use platform independent approach 
#eclipse_count=`pgrep -cfl "$eclipse_proc"`
eclipse_count=`pgrep -fl "$eclipse_proc" | wc -l | tr -d ' '`

# check how many processes matched
case $eclipse_count in
  # no eclipse - do nothing
  0) ;;
  # exactly one - offer to kill it
  1) 
     echo "Eclipse is running - shall i kill and restart it with -clean? y/n?"
       read answer
       case $answer in
         y|Y) ;;
           *) error "aborted ..." ;;
       esac
     echo "killing current $eclipse_proc"
     pkill -f "$eclipse_proc"
     ;;
  # multiple - this is bogus
  *) error "$eclipse_count processes matching $eclipse_proc found - please adapt $0";;
esac

tmp=/tmp/eclipse$$
echo "starting eclipse cleanly ... using $tmp for nohup.out"
mkdir -p $tmp
cd $tmp

# start eclipse with clean options
nohup $eclipse_app -clean -clearPersistedState&

What "wmic bios get serialnumber" actually retrieves?

wmic bios get serialnumber     

if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)

I had to do exactly that.:):)

PHP Regex to get youtube video ID?

I think you are trying to do this.

<?php
  $video = 'https://www.youtube.com/watch?v=u00FY9vADfQ';
  $parsed_video = parse_url($video, PHP_URL_QUERY);
  parse_str($parsed_video, $arr);
?>
<iframe
src="https://www.youtube.com/embed/<?php echo $arr['v'];  ?>"
frameborder="0">
</iframe>

How can I use onItemSelected in Android?

Joseph: spinner.setOnItemSelectedListener(this) should be below Spinner firstSpinner = (Spinner) findViewById(R.id.spinner1); on onCreate

Looping over arrays, printing both index and value

you can always use iteration param:

ITER=0
for I in ${FOO[@]}
do  
    echo ${I} ${ITER}
    ITER=$(expr $ITER + 1)
done

How can I check whether a option already exist in select by JQuery

It's help me :

  var key = 'Hallo';

   if ( $("#chosen_b option[value='"+key+"']").length == 0 ){
   alert("option not exist!");

    $('#chosen_b').append("<option value='"+key+"'>"+key+"</option>");
    $('#chosen_b').val(key);
   $('#chosen_b').trigger("chosen:updated");
                         }
  });

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

BH's answer of installing Java 6u45 was very close... still got the popup on reboot...BUT after uninstalling Java 6u45, rebooted, no warning! Thank you BH! Then installed the latest version, 8u151-i586, rebooted no warning.

I added lines in PATH as above, didn't do anything.

My system: Windows 7, 64 bit. Warning was for No JVM, 32 bit Java not found. Yes, I could have installed the 64 bit version, but 32bit is more compatible with all programs.

Passing additional variables from command line to make

The simplest way is:

make foo=bar target

Then in your makefile you can refer to $(foo). Note that this won't propagate to sub-makes automatically.

If you are using sub-makes, see this article: Communicating Variables to a Sub-make

How to generate .NET 4.0 classes from xsd?

If you want to generate the class with auto properties, convert the XSD to XML using this then convert the XML to JSON using this and copy to clipboard the result. Then in VS, inside the file where your class will be created, go to Edit>Paste Special>Paste JSON as classes.

make script execution to unlimited

You'll have to set it to zero. Zero means the script can run forever. Add the following at the start of your script:

ini_set('max_execution_time', 0);

Refer to the PHP documentation of max_execution_time

Note that:

set_time_limit(0);

will have the same effect.

Fixing npm path in Windows 8 and 10

You can follow the following steps:

  • Search environment variables from start menu's search box.
  • Click it then go to Environment Variables
  • Click PATH
  • click Edit
  • Click New and try to copy and paste your path for 'bin' folder [find where you installed the node] for example according to my machine 'C:\Program Files\nodejs\node_modules\npm\bin'

If you got any error. try the another step:

  • Click New, then browse for the 'bin' folder

Why a function checking if a string is empty always returns true?

Just use strlen() function

if (strlen($s)) {
   // not empty
}

What is web.xml file and what are all things can I do with it?

Deployment descriptor file "web.xml" : Through the proper use of the deployment descriptor file, web.xml, you can control many aspects of the Web application behavior, from preloading servlets, to restricting resource access, to controlling session time-outs.

web.xml : is used to control many facets of a Web application. Using web.xml, you can assign custom URLs for invoking servlets, specify initialization parameters for the entire application as well as for specific servlets, control session timeouts, declare filters, declare security roles, restrict access to Web resources based on declared security roles, and so on.

Python mock multiple return values

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

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

Quoting the Mock() documentation:

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

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

You can change the type of created field from datetime to varchar(255), then you can set (update) all records that have the value "0000-00-00 00:00:00" to NULL.

Now, you can do your queries without error. After you finished, you can alter the type of the field created to datetime.

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

This is the best way to get a simple date string :

 @DateTime.Parse(Html.DisplayFor(Model => Model.AuditDate).ToString()).ToShortDateString()

Get started with Latex on Linux

I would personally use a complete editing package such as:

  • TexWorks
  • TexStudio

Then I would install "MikTeX" as the compiling package, which allows you to generate a PDF from your document, using the pdfLaTeX compiler.

JOptionPane YES/No Options Confirm Dialog Box Issue

You need to look at the return value of the call to showConfirmDialog. I.E.:

int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
  // Saving code here
}

You were testing against dialogButton, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton would never have been anything other than JOptionPane.YES_NO_OPTION.

Per the Javadoc for showConfirmDialog:

Returns: an integer indicating the option selected by the user

Django - what is the difference between render(), render_to_response() and direct_to_template()?

From django docs:

render() is the same as a call to render_to_response() with a context_instance argument that that forces the use of a RequestContext.

direct_to_template is something different. It's a generic view that uses a data dictionary to render the html without the need of the views.py, you use it in urls.py. Docs here

can't start MySql in Mac OS 10.6 Snow Leopard

Okay... Finally I could install it! Why? or what I did? well I am not sure. first I downloaded and installed the package (I installed all the files(3) from the disk image) but I couldn't start it. (nor from the preferences panel, nor from the termial)

second I removed it and installed through mac ports.

again, the same thing. could not start it.

Now I deleted it again, installed from the package. (i am not sure if it was the exact same package but I think it is) Only this time I got the package from another site(its a mirror).

the site:

http://www.mmisoftware.co.uk/weblog/2009/08/29/mac-os-x-10-6-snow-leopard-and-mysql/

and the link:

http://mirror.services.wisc.edu/mysql/Downloads/MySQL-5.1/mysql-5.1.37-osx10.5-x86.dmg

1.- install mysql-5-1.37-osx10.5-x86.pkg

2.- install MySQLStartupItem.pkg

3.- install MySQL.prefpanel

And this time is working fine (even the preferences panel!)

Nothing special, I don't know what happened the first two times.

But thank you all. Regards.

Counting repeated characters in a string in Python

s = 'today is sunday i would like to relax'
numberOfDuplicatedChar = len(s) - len(set(s))

#no duplicated element in set.

Using GCC to produce readable assembly?

If you compile with debug symbols, you can use objdump to produce a more readable disassembly.

>objdump --help
[...]
-S, --source             Intermix source code with disassembly
-l, --line-numbers       Include line numbers and filenames in output

objdump -drwC -Mintel is nice:

  • -r shows symbol names on relocations (so you'd see puts in the call instruction below)
  • -R shows dynamic-linking relocations / symbol names (useful on shared libraries)
  • -C demangles C++ symbol names
  • -w is "wide" mode: it doesn't line-wrap the machine-code bytes
  • -Mintel: use GAS/binutils MASM-like .intel_syntax noprefix syntax instead of AT&T
  • -S: interleave source lines with disassembly.

You could put something like alias disas="objdump -drwCS -Mintel" in your ~/.bashrc


Example:

> gcc -g -c test.c
> objdump -d -M intel -S test.o

test.o:     file format elf32-i386


Disassembly of section .text:

00000000 <main>:
#include <stdio.h>

int main(void)
{
   0:   55                      push   ebp
   1:   89 e5                   mov    ebp,esp
   3:   83 e4 f0                and    esp,0xfffffff0
   6:   83 ec 10                sub    esp,0x10
    puts("test");
   9:   c7 04 24 00 00 00 00    mov    DWORD PTR [esp],0x0
  10:   e8 fc ff ff ff          call   11 <main+0x11>

    return 0;
  15:   b8 00 00 00 00          mov    eax,0x0
}
  1a:   c9                      leave  
  1b:   c3                      ret

Note that this isn't using -r so the call rel32=-4 isn't annotated with the puts symbol name. And looks like a broken call that jumps into the middle of the call instruction in main. Remember that the rel32 displacement in the call encoding is just a placeholder until the linker fills in a real offset (to a PLT stub in this case, unless you statically link libc).

Attempt to set a non-property-list object as an NSUserDefaults

I had this problem trying save a dictionary to NSUserDefaults. It turns out it wouldn't save because it contained NSNull values. So I just copied the dictionary into a mutable dictionary removed the nulls then saved to NSUserDefaults

NSMutableDictionary* dictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary_trying_to_save];
[dictionary removeObjectForKey:@"NullKey"];
[[NSUserDefaults standardUserDefaults] setObject:dictionary forKey:@"key"];

In this case I knew which keys might be NSNull values.

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);

Stop Chrome Caching My JS Files

I know this is an "old" question. But the headaches with caching never are. After heaps of trial and errors, I found that one of our web hosting providers had through CPanel this app called Cachewall. I just clicked on Enable Development mode and... voilà!!! It stopped the long suffered pain straight away :) Hope this helps somebody else... R

Multiple radio button groups in one form

This is very simple you need to keep different names of every radio input group.

_x000D_
_x000D_
      <input type="radio" name="price">Thousand<br>_x000D_
      <input type="radio" name="price">Lakh<br>_x000D_
      <input type="radio" name="price">Crore_x000D_
      _x000D_
      </br><hr>_x000D_
_x000D_
      <input type="radio" name="gender">Male<br>_x000D_
      <input type="radio" name="gender">Female<br>_x000D_
      <input type="radio" name="gender">Other
_x000D_
_x000D_
_x000D_

How to compare two colors for similarity/difference

Android for ColorUtils API RGBToHSL: I had two int argb colors (color1, color2) and I wanted to get distance/difference among the two colors. Here is what I did;

private float getHue(int color) {
    int R = (color >> 16) & 0xff;
    int G = (color >>  8) & 0xff;
    int B = (color      ) & 0xff;
    float[] colorHue = new float[3];
    ColorUtils.RGBToHSL(R, G, B, colorHue);
    return colorHue[0];
}

Then I used below code to find the distance between the two colors.

private float getDistance(getHue(color1), getHue(color2)) {
    float avgHue = (hue1 + hue2)/2;
    return Math.abs(hue1 - avgHue);
}

How to change the data type of a column without dropping the column with query?

This work for postgresql 9.0.3

 alter table [table name] ALTER COLUMN [column name] TYPE [character varying];

http://www.postgresql.org/docs/8.0/static/sql-altertable.html

How to vertically align an image inside a div

For centering an image inside a container (it could be a logo) besides some text like this:

Enter image description here

Basically you wrap the image

_x000D_
_x000D_
.outer-frame {_x000D_
  border: 1px solid red;_x000D_
  min-height: 200px;_x000D_
  text-align: center; /* Only to align horizontally */_x000D_
}_x000D_
_x000D_
.wrapper{_x000D_
  line-height: 200px;_x000D_
  border: 2px dashed blue;_x000D_
  border-radius: 20px;_x000D_
  margin: 50px_x000D_
}_x000D_
_x000D_
img {_x000D_
  /* height: auto; */_x000D_
  vertical-align: middle;   /* Only to align vertically */_x000D_
}
_x000D_
<div class="outer-frame">_x000D_
  <div class="wrapper">_x000D_
    some text_x000D_
    <img src="http://via.placeholder.com/150x150">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Start an activity from a fragment

with Kotlin I execute this code:

requireContext().startActivity<YourTargetActivity>()

"FATAL: Module not found error" using modprobe

i think there should be entry of your your_module.ko in /lib/modules/uname -r/modules.dep and in /lib/modules/uname -r/modules.dep.bin for "modprobe your_module" command to work

MongoError: connect ECONNREFUSED 127.0.0.1:27017

Press CTRL+ALT+DELETE/task manager , then go to services , find MongoDB , right click on it. start. go back to terminal . npm start it will work.

What is The Rule of Three?

Basically if you have a destructor (not the default destructor) it means that the class that you defined has some memory allocation. Suppose that the class is used outside by some client code or by you.

    MyClass x(a, b);
    MyClass y(c, d);
    x = y; // This is a shallow copy if assignment operator is not provided

If MyClass has only some primitive typed members a default assignment operator would work but if it has some pointer members and objects that do not have assignment operators the result would be unpredictable. Therefore we can say that if there is something to delete in destructor of a class, we might need a deep copy operator which means we should provide a copy constructor and assignment operator.

how to make negative numbers into positive

Well, in mathematics to convert a negative number to a positive number you just need to multiple the negative number by -1;

Then your solution could be like this:

a = a * -1;

or shorter:

a *= -1;

Java - Check if input is a positive integer, negative integer, natural number and so on.

For integers you can use Integer.signum()

Returns the signum function of the specified int value. (The return value is -1 if the specified value is negative; 0 if the specified value is zero; and 1 if the specified value is positive.)

Python not working in command prompt?

Just go with the command py. I'm running python 3.6.2 on windows 7 and it works just fine.
I removed all the python paths from the system directory and the paths don't show up when I run the command echo %path% in cmd. Python is still working fine.
I ran into this by accidentally pressing enter while typing python...

EDIT: I didn't mention that I installed python to a custom folder C:\Python\

Reliable method to get machine's MAC address in C#

public static PhysicalAddress GetMacAddress()
{
    var myInterfaceAddress = NetworkInterface.GetAllNetworkInterfaces()
        .Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
        .OrderByDescending(n => n.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
        .Select(n => n.GetPhysicalAddress())
        .FirstOrDefault();

    return myInterfaceAddress;
}

Depend on a branch or tag using a git URL in a package.json?

per @dantheta's comment:

As of npm 1.1.65, Github URL can be more concise user/project. npmjs.org/doc/files/package.json.html You can attach the branch like user/project#branch

So

"babel-eslint": "babel/babel-eslint",

Or for tag v1.12.0 on jscs:

"jscs": "jscs-dev/node-jscs#v1.12.0",

Note, if you use npm --save, you'll get the longer git

From https://docs.npmjs.com/cli/v6/configuring-npm/package-json#git-urls-as-dependencies

Git URLs as Dependencies

Git urls are of the form:

git+ssh://[email protected]:npm/cli.git#v1.0.27 git+ssh://[email protected]:npm/cli#semver:^5.0 git+https://[email protected]/npm/cli.git
git://github.com/npm/cli.git#v1.0.27

If #<commit-ish> is provided, it will be used to clone exactly that commit. If > the commit-ish has the format #semver:<semver>, <semver> can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #<commit-ish> or #semver:<semver> is specified, then master is used.

GitHub URLs

As of version 1.1.65, you can refer to GitHub urls as just "foo": "user/foo-project". Just as with git URLs, a commit-ish suffix can be included. For example:

{
 "name": "foo",
 "version": "0.0.0",
 "dependencies": {
   "express": "expressjs/express",
   "mocha": "mochajs/mocha#4727d357ea",
   "module": "user/repo#feature\/branch"
 }
}```

How to obtain the number of CPUs/cores in Linux from the command line?

For the total number of physical cores:

grep '^core id' /proc/cpuinfo |sort -u|wc -l

On multiple-socket machines (or always), multiply the above result by the number of sockets:

echo $(($(grep "^physical id" /proc/cpuinfo | awk '{print $4}' | sort -un | tail -1)+1))

@mklement0 has quite a nice answer below using lscpu. I have written a more succinct version in the comments

How Can I Remove “public/index.php” in the URL Generated Laravel?

For Laravel 4 & 5:

  1. Rename server.php in your Laravel root folder to index.php
  2. Copy the .htaccess file from /public directory to your Laravel root folder.

That's it !! :)

How to open a link in new tab using angular?

Just add target="_blank" to the

<a mat-raised-button target="_blank" [routerLink]="['/find-post/post', post.postID]"
    class="theme-btn bg-grey white-text mx-2 mb-2">
    Open in New Window
</a>

What is difference between XML Schema and DTD?

Similarities:

DTDs and Schemas both perform the same basic functions:

  • First, they both declare a laundry list of elements and attributes.
  • Second, both describe how those elements are grouped, nested or used within the XML. In other words, they declare the rules by which you are allowing someone to create an XML file within your workflow, and
  • Third, both DTDs and schemas provide methods for restricting, or forcing, the type or format of an element. For example, within the DTD or Schema you can force a date field to be written as 01/05/06 or 1/5/2006.

Differences:

  • DTDs are better for text-intensive applications, while schemas have several advantages for data-intensive workflows.

  • Schemas are written in XML and thusly follow the same rules, while DTDs are written in a completely different language.

Examples:

DTD:

<?xml version="1.0" encoding="UTF-8"?>
    <!ELEMENT employees (Efirstname, Elastname, Etitle, Ephone, Eemail)>
         <!ELEMENT Efirstname (#PCDATA)>
         <!ELEMENT Elastname (#PCDATA)>
         <!ELEMENT Etitle (#PCDATA)>
         <!ELEMENT Ephone (#PCDATA)>
         <!ELEMENT Eemail (#PCDATA)>

XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:od="urn:schemas-microsoft-com:officedata">
<xsd:element name="dataroot">
     <xsd:complexType>
          <xsd:sequence>
               <xsd:element ref="employees" minOccurs="0" maxOccurs="unbounded"/>
          </xsd:sequence>
          <xsd:attribute name="generated" type="xsd:dateTime"/>
      </xsd:complexType>
</xsd:element>
<xsd:element name="employees">
      <xsd:annotation>
           <xsd:appinfo>
               <od:index index-name="PrimaryKey" index-key="Employeeid " primary="yes"
                unique="yes" clustered="no"/>
          <od:index index-name="Employeeid" index-key="Employeeid " primary="no" unique="no"
           clustered="no"/>
     </xsd:appinfo>
</xsd:annotation>
     <xsd:complexType>
          <xsd:sequence>
               <xsd:element name="Elastname" minOccurs="0" od:jetType="text"
                od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Etitle" minOccurs="0" od:jetType="text" od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Ephone" minOccurs="0" od:jetType="text"
                od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Eemail" minOccurs="0" od:jetType="text"
               od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
               <xsd:element name="Ephoto" minOccurs="0" od:jetType="text"
                od:sqlSType="nvarchar">
                    <xsd:simpleType>
                         <xsd:restriction base="xsd:string">
                              <xsd:maxLength value="50"/>
                         </xsd:restriction>
                    </xsd:simpleType>
               </xsd:element>
          </xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

Nth max salary in Oracle

select min(sal) from (select distinct(sal) from emp  order by sal desc) where rownum <=&n;

Inner query select distinct(sal) from emp order by sal desc will give the below output as given below.

SAL 5000 3000 2975 2850 2450 1600 1500 1300 1250 1100 950 800

without distinct in the above query select sal from emp order by sal desc output as given below.

SAL 5000 3000 3000 2975 2850 2450 1600 1500 1300 1250 1250 1100 950 800

outer query will give the 'N'th max sal (E.g) I have tried here for 4th Max sal and out put as given below.

MIN(SAL) 2850

Moment.js - two dates difference in number of days

From the moment.js docs: format('E') stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.

From the moment.js docs again, here is what they suggest:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Here is a JSFiddle for your particular case:

_x000D_
_x000D_
$('#test').click(function() {_x000D_
  var startDate = moment("13.04.2016", "DD.MM.YYYY");_x000D_
  var endDate = moment("28.04.2016", "DD.MM.YYYY");_x000D_
_x000D_
  var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
  $('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #ffb;_x000D_
  padding: 10px;_x000D_
  border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
_x000D_
_x000D_

django no such table:

If you are using latest version of django 2.x or 1.11.x then you have to first create migrations ,

python manage.py makemigrations

After that you just have to run migrate command for syncing database .

python manage.py migrate --run-syncdb

These will sync your database and python models and also second command will print all sql behind it.

Dynamically set value of a file input

I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.

Converting String to Cstring in C++

string name;
char *c_string;

getline(cin, name);

c_string = new char[name.length()];

for (int index = 0; index < name.length(); index++){
    c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
                              // the char array

I know this is not the predefined method but thought it may be useful to someone nevertheless.

How do I see the commit differences between branches in git?

#! /bin/bash
if ((2==$#)); then
  a=$1
  b=$2
  alog=$(echo $a | tr '/' '-').log
  blog=$(echo $b | tr '/' '-').log
  git log --oneline $a > $alog
  git log --oneline $b > $blog
  diff $alog $blog
fi

Contributing this because it allows a and b logs to be diff'ed visually, side by side, if you have a visual diff tool. Replace diff command at end with command to start visual diff tool.

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

How to get selected value of a dropdown menu in ReactJS

You can handle it all within the same function as following

_x000D_
_x000D_
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>_x000D_
_x000D_
  <option value="5">5 dollars</option>_x000D_
  <option value="10">10 dollars</option>_x000D_
                                         _x000D_
</select>
_x000D_
_x000D_
_x000D_

as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!

How to use Bootstrap 4 in ASP.NET Core

We use bootstrap 4 in asp.net core but reference the libraries from "npm" using the "Package Installer" extension and found this to be better than Nuget for Javascript/CSS libraries.

We then use the "Bundler & Minifier" extension to copy the relevant files for distribution (from the npm node_modules folder, which sits outside the project) into wwwroot as we like for development/deployment.

Why is the gets function so dangerous that it should not be used?

Why is gets() dangerous

The first internet worm (the Morris Internet Worm) escaped about 30 years ago (1988-11-02), and it used gets() and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.

You should forget you ever heard that gets() existed.

The C11 standard ISO/IEC 9899:2011 eliminated gets() as a standard function, which is A Good Thing™ (it was formally marked as 'obsolescent' and 'deprecated' in ISO/IEC 9899:1999/Cor.3:2007 — Technical Corrigendum 3 for C99, and then removed in C11). Sadly, it will remain in libraries for many years (meaning 'decades') for reasons of backwards compatibility. If it were up to me, the implementation of gets() would become:

char *gets(char *buffer)
{
    assert(buffer != 0);
    abort();
    return 0;
}

Given that your code will crash anyway, sooner or later, it is better to head the trouble off sooner rather than later. I'd be prepared to add an error message:

fputs("obsolete and dangerous function gets() called\n", stderr);

Modern versions of the Linux compilation system generates warnings if you link gets() — and also for some other functions that also have security problems (mktemp(), …).

Alternatives to gets()

fgets()

As everyone else said, the canonical alternative to gets() is fgets() specifying stdin as the file stream.

char buffer[BUFSIZ];

while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
    ...process line of data...
}

What no-one else yet mentioned is that gets() does not include the newline but fgets() does. So, you might need to use a wrapper around fgets() that deletes the newline:

char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        size_t len = strlen(buffer);
        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        return buffer;
    }
    return 0;
}

Or, better:

char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        return buffer;
    }
    return 0;
}

Also, as caf points out in a comment and paxdiablo shows in his answer, with fgets() you might have data left over on a line. My wrapper code leaves that data to be read next time; you can readily modify it to gobble the rest of the line of data if you prefer:

        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        else
        {
             int ch;
             while ((ch = getc(fp)) != EOF && ch != '\n')
                 ;
        }

The residual problem is how to report the three different result states — EOF or error, line read and not truncated, and partial line read but data was truncated.

This problem doesn't arise with gets() because it doesn't know where your buffer ends and merrily tramples beyond the end, wreaking havoc on your beautifully tended memory layout, often messing up the return stack (a Stack Overflow) if the buffer is allocated on the stack, or trampling over the control information if the buffer is dynamically allocated, or copying data over other precious global (or module) variables if the buffer is statically allocated. None of these is a good idea — they epitomize the phrase 'undefined behaviour`.


There is also the TR 24731-1 (Technical Report from the C Standard Committee) which provides safer alternatives to a variety of functions, including gets():

§6.5.4.1 The gets_s function

Synopsis

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
char *gets_s(char *s, rsize_t n);

Runtime-constraints

s shall not be a null pointer. n shall neither be equal to zero nor be greater than RSIZE_MAX. A new-line character, end-of-file, or read error shall occur within reading n-1 characters from stdin.25)

3 If there is a runtime-constraint violation, s[0] is set to the null character, and characters are read and discarded from stdin until a new-line character is read, or end-of-file or a read error occurs.

Description

4 The gets_s function reads at most one less than the number of characters specified by n from the stream pointed to by stdin, into the array pointed to by s. No additional characters are read after a new-line character (which is discarded) or after end-of-file. The discarded new-line character does not count towards number of characters read. A null character is written immediately after the last character read into the array.

5 If end-of-file is encountered and no characters have been read into the array, or if a read error occurs during the operation, then s[0] is set to the null character, and the other elements of s take unspecified values.

Recommended practice

6 The fgets function allows properly-written programs to safely process input lines too long to store in the result array. In general this requires that callers of fgets pay attention to the presence or absence of a new-line character in the result array. Consider using fgets (along with any needed processing based on new-line characters) instead of gets_s.

25) The gets_s function, unlike gets, makes it a runtime-constraint violation for a line of input to overflow the buffer to store it. Unlike fgets, gets_s maintains a one-to-one relationship between input lines and successful calls to gets_s. Programs that use gets expect such a relationship.

The Microsoft Visual Studio compilers implement an approximation to the TR 24731-1 standard, but there are differences between the signatures implemented by Microsoft and those in the TR.

The C11 standard, ISO/IEC 9899-2011, includes TR24731 in Annex K as an optional part of the library. Unfortunately, it is seldom implemented on Unix-like systems.


getline() — POSIX

POSIX 2008 also provides a safe alternative to gets() called getline(). It allocates space for the line dynamically, so you end up needing to free it. It removes the limitation on line length, therefore. It also returns the length of the data that was read, or -1 (and not EOF!), which means that null bytes in the input can be handled reliably. There is also a 'choose your own single-character delimiter' variation called getdelim(); this can be useful if you are dealing with the output from find -print0 where the ends of the file names are marked with an ASCII NUL '\0' character, for example.

How to get screen dimensions as pixels in Android

Kotlin Version via Extension Property

There are multiple ways of achieving the screen dimensions in android, but I think the best solution could be independent of a Context instance, so you can use it everywhere in your code. Here I've provided a solution via kotlin extension property, which makes it easy to know the screen size in pixels as well as dp:


DimensionUtils.kt

import android.content.res.Resources
import android.graphics.Rect
import android.graphics.RectF
import android.util.DisplayMetrics
import kotlin.math.roundToInt

/**
 * @author aminography
 */

private val displayMetrics: DisplayMetrics by lazy { Resources.getSystem().displayMetrics }

val screenRectPx: Rect
    get() = displayMetrics.run { Rect(0, 0, widthPixels, heightPixels) }

val screenRectDp: RectF
    get() = displayMetrics.run { RectF(0f, 0f, widthPixels.px2dp, heightPixels.px2dp) }

val Number.px2dp: Float
    get() = this.toFloat() / displayMetrics.density

val Number.dp2px: Int
    get() = (this.toFloat() * displayMetrics.density).roundToInt()


Usage:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val widthPx = screenRectPx.width()
        val heightPx = screenRectPx.height()
        println("[PX] screen width: $widthPx , height: $heightPx")

        val widthDp = screenRectDp.width()
        val heightDp = screenRectDp.height()
        println("[DP] screen width: $widthDp , height: $heightDp")
    }
}

Result:

When the device is in portrait orientation:

[PX] screen width: 1440 , height: 2392
[DP] screen width: 360.0 , height: 598.0

When the device is in landscape orientation:

[PX] screen width: 2392 , height: 1440
[DP] screen width: 598.0 , height: 360.0


If you are not a fan of kotlin, use the java version:

import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.DisplayMetrics;

/**
 * @author aminography
 */
public class DimensionUtils {

    private static DisplayMetrics displayMetrics;

    private static DisplayMetrics getDisplayMetrics() {
        if (displayMetrics == null) {
            displayMetrics = Resources.getSystem().getDisplayMetrics();
        }
        return displayMetrics;
    }

    public static Rect screenRectPx() {
        return new Rect(0, 0, getDisplayMetrics().widthPixels, getDisplayMetrics().heightPixels);
    }

    public static RectF screenRectDp() {
        return new RectF(0f, 0f, px2dp(getDisplayMetrics().widthPixels), px2dp(getDisplayMetrics().heightPixels));
    }

    public static float px2dp(int value) {
        return value / getDisplayMetrics().density;
    }

    public static int dp2px(float value) {
        return (int) (value * getDisplayMetrics().density);
    }
}

How to read a value from the Windows registry

RegQueryValueEx

This gives the value if it exists, and returns an error code ERROR_FILE_NOT_FOUND if the key doesn't exist.

(I can't tell if my link is working or not, but if you just google for "RegQueryValueEx" the first hit is the msdn documentation.)

URLEncoder not able to translate space character

This behaves as expected. The URLEncoder implements the HTML Specifications for how to encode URLs in HTML forms.

From the javadocs:

This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format.

and from the HTML Specification:

application/x-www-form-urlencoded

Forms submitted with this content type must be encoded as follows:

  1. Control names and values are escaped. Space characters are replaced by `+'

You will have to replace it, e.g.:

System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));

SQL Server : error converting data type varchar to numeric

SQL Server 2012 and Later

Just use Try_Convert instead:

TRY_CONVERT takes the value passed to it and tries to convert it to the specified data_type. If the cast succeeds, TRY_CONVERT returns the value as the specified data_type; if an error occurs, null is returned. However if you request a conversion that is explicitly not permitted, then TRY_CONVERT fails with an error.

Read more about Try_Convert.

SQL Server 2008 and Earlier

The traditional way of handling this is by guarding every expression with a case statement so that no matter when it is evaluated, it will not create an error, even if it logically seems that the CASE statement should not be needed. Something like this:

SELECT
   Account_Code =
      Convert(
         bigint, -- only gives up to 18 digits, so use decimal(20, 0) if you must
         CASE
         WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
         ELSE X.Account_Code
         END
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      CASE
      WHEN X.Account_Code LIKE '%[^0-9]%' THEN NULL
      ELSE X.Account_Code
      END
   ) BETWEEN 503100 AND 503205

However, I like using strategies such as this with SQL Server 2005 and up:

SELECT
   Account_Code = Convert(bigint, X.Account_Code),
   A.Descr
FROM
   dbo.Account A
   OUTER APPLY (
      SELECT A.Account_Code WHERE A.Account_Code NOT LIKE '%[^0-9]%'
   ) X
WHERE
   Convert(bigint, X.Account_Code) BETWEEN 503100 AND 503205

What this does is strategically switch the Account_Code values to NULL inside of the X table when they are not numeric. I initially used CROSS APPLY but as Mikael Eriksson so aptly pointed out, this resulted in the same error because the query parser ran into the exact same problem of optimizing away my attempt to force the expression order (predicate pushdown defeated it). By switching to OUTER APPLY it changed the actual meaning of the operation so that X.Account_Code could contain NULL values within the outer query, thus requiring proper evaluation order.

You may be interested to read Erland Sommarskog's Microsoft Connect request about this evaluation order issue. He in fact calls it a bug.

There are additional issues here but I can't address them now.

P.S. I had a brainstorm today. An alternate to the "traditional way" that I suggested is a SELECT expression with an outer reference, which also works in SQL Server 2000. (I've noticed that since learning CROSS/OUTER APPLY I've improved my query capability with older SQL Server versions, too--as I am getting more versatile with the "outer reference" capabilities of SELECT, ON, and WHERE clauses!)

SELECT
   Account_Code =
      Convert(
         bigint,
         (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
      ),
   A.Descr
FROM dbo.Account A
WHERE
   Convert(
      bigint,
      (SELECT A.AccountCode WHERE A.Account_Code NOT LIKE '%[^0-9]%')
   ) BETWEEN 503100 AND 503205

It's a lot shorter than the CASE statement.

setOnItemClickListener on custom ListView

I too had that same problem.. If we think logically little bit we can get the answer.. It worked for me very well.. I hope u will get it..

  1. listviewdemo.xml

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="30dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />
    

  2. listviewcontent.xml - note that TextView - android:id="@+id/txtLstItem"

    <LinearLayout
        android:id="@+id/listviewcontentlayout"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="horizontal">
    
        <ImageView
            android:id="@+id/img1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dp" />
    
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:orientation="vertical">
    
            <TextView
                android:id="@+id/txtLstItem"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:shadowColor="@android:color/black"
                android:shadowRadius="5"
                android:textColor="@android:color/white" />
    
        </LinearLayout>
    
        <ImageView
            android:id="@+id/img2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dp" />
    </LinearLayout>
    

  3. ListViewActivity.java - Note that view.findViewById(R.id.txtLstItem) - as we setting the value to TextView by setText() method we getting text from TextView by View object returned by onItemClick method. OnItemClick() returns the current view.

    TextView v=(TextView) view.findViewById(R.id.txtLstItem);
    Toast.makeText(getApplicationContext(), "selected Item Name is "+v.getText(), Toast.LENGTH_LONG).show();**
    

    Using this simple logic we can get other values like CheckBox, RadioButton, ImageView etc.

    ListView List = (ListView) findViewById(R.id.listview);
    cursor = cr.query(CONTENT_URI,projection,null,null,null);
    adapter = new ListViewCursorAdapter(ListViewActivity.this, R.layout.listviewcontent, cursor, from, to);
    
    cursor.moveToFirst();
    
    // Let activity manage the cursor
    startManagingCursor(cursor);
    
    List.setAdapter(adapter);
    List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick (AdapterView < ? > adapter, View view,int position, long arg){
                // TODO Auto-generated method stub
                TextView v = (TextView) view.findViewById(R.id.txtLstItem);
                Toast.makeText(getApplicationContext(), "selected Item Name is " + v.getText(), Toast.LENGTH_LONG).show();
            }
        }
    );
    

How to convert an NSTimeInterval (seconds) into minutes

Swift 2 version

extension NSTimeInterval {
            func toMM_SS() -> String {
                let interval = self
                let componentFormatter = NSDateComponentsFormatter()

                componentFormatter.unitsStyle = .Positional
                componentFormatter.zeroFormattingBehavior = .Pad
                componentFormatter.allowedUnits = [.Minute, .Second]
                return componentFormatter.stringFromTimeInterval(interval) ?? ""
            }
        }
    let duration = 326.4.toMM_SS()
    print(duration)    //"5:26"

Cannot assign requested address using ServerSocket.socketBind

As the error states, it can't bind - which typically means it's in use by another process. From a command line run:

netstat -a -n -o

Interrogate the output for port 9999 in use in the left hand column.

For more information: http://www.zdnetasia.com/see-what-process-is-using-a-tcp-port-62047950.htm

Is there an easy way to return a string repeated X number of times?

        string indent = "---";
        string n = string.Concat(Enumerable.Repeat(indent, 1).ToArray());
        string n = string.Concat(Enumerable.Repeat(indent, 2).ToArray());
        string n = string.Concat(Enumerable.Repeat(indent, 3).ToArray());

Restart container within pod

We use a pretty convenient command line to force re-deployment of fresh images on integration pod.
We noticed that our alpine containers all run their "sustaining" command on PID 5. Therefore, sending it a SIGTERM signal takes the container down. imagePullPolicy being set to Always has the kubelet re-pull the latest image when it brings the container back.

kubectl exec -i [pod name] -c [container-name] -- kill -15 5

How to get client IP address using jQuery

function GetUserIP(){
  var ret_ip;
  $.ajaxSetup({async: false});
  $.get('http://jsonip.com/', function(r){ 
    ret_ip = r.ip; 
  });
  return ret_ip;
}

If you want to use the IP and assign it to a variable, Try this. Just call GetUserIP()

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Express-js wildcard routing to cover everything under and including a path

For those who are learning node/express (just like me): do not use wildcard routing if possible!

I also wanted to implement the routing for GET /users/:id/whatever using wildcard routing. This is how I got here.

More info: https://blog.praveen.science/wildcard-routing-is-an-anti-pattern/

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

Clear MySQL query cache without restarting server

according the documentation, this should do it...

RESET QUERY CACHE 

Generate pdf from HTML in div using Javascript

i use jspdf and html2canvas for css rendering and i export content of specific div as this is my code

$(document).ready(function () {
    let btn=$('#c-oreder-preview');
    btn.text('download');
    btn.on('click',()=> {

        $('#c-invoice').modal('show');
        setTimeout(function () {
            html2canvas(document.querySelector("#c-print")).then(canvas => {
                //$("#previewBeforeDownload").html(canvas);
                var imgData = canvas.toDataURL("image/jpeg",1);
                var pdf = new jsPDF("p", "mm", "a4");
                var pageWidth = pdf.internal.pageSize.getWidth();
                var pageHeight = pdf.internal.pageSize.getHeight();
                var imageWidth = canvas.width;
                var imageHeight = canvas.height;

                var ratio = imageWidth/imageHeight >= pageWidth/pageHeight ? pageWidth/imageWidth : pageHeight/imageHeight;
                //pdf = new jsPDF(this.state.orientation, undefined, format);
                pdf.addImage(imgData, 'JPEG', 0, 0, imageWidth * ratio, imageHeight * ratio);
                pdf.save("invoice.pdf");
                //$("#previewBeforeDownload").hide();
                $('#c-invoice').modal('hide');
            });
        },500);

        });
});

Adding Lombok plugin to IntelliJ project

For me it didn't work after doing all of the steps suggested in the question and in the top answer. Initially the import didn't work, and then when I restarted IntelliJ, I got these messages from the Gradle Plugin:

Gradle DSL method not found: 'annotationProcessor()'
Possible causes:<ul><li>The project 'wq-handler-service' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
Upgrade plugin to version 2.3.2 and sync project</li><li>The project 'wq-handler-service' may be using a version of Gradle that does not contain the method.
Open Gradle wrapper file</li><li>The build file may be missing a Gradle plugin.
Apply Gradle plugin</li>

This was weird because I don't develop for Android, just using IntelliJ for Mac OS.

To be fair, my build.gradle file had these lines in the dependencies section, which I copied from a colleague:

compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.16.20'
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.16.20'

After checking versions, the only thing that completely solved my problem was adding the below to the plugins section of build.gradle, which I found on this page:

id 'net.ltgt.apt' version '0.15'

Looks like it's a

Gradle plugin making it easier/safer to use Java annotation processors

(ltgt plugin page)

Laravel Eloquent update just if changes have been made

I like to add this method, if you are using an edit form, you can use this code to save the changes in your update(Request $request, $id) function:

$post = Post::find($id);    
$post->fill($request->input())->save();

keep in mind that you have to name your inputs with the same column name. The fill() function will do all the work for you :)

Android Pop-up message

sample code show custom dialog in kotlin:

fun showDlgFurtherDetails(context: Context,title: String?, details: String?) {

    val dialog = Dialog(context)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)
    dialog.setContentView(R.layout.dlg_further_details)
    dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    val lblService = dialog.findViewById(R.id.lblService) as TextView
    val lblDetails = dialog.findViewById(R.id.lblDetails) as TextView
    val imgCloseDlg = dialog.findViewById(R.id.imgCloseDlg) as ImageView

    lblService.text = title
    lblDetails.text = details
    lblDetails.movementMethod = ScrollingMovementMethod()
    lblDetails.isScrollbarFadingEnabled = false
    imgCloseDlg.setOnClickListener {
        dialog.dismiss()
    }
    dialog.show()
}

Find the number of columns in a table

Using JDBC in Java:

    String quer="SELECT * FROM sample2 where 1=2";
    
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery(quer);
    ResultSetMetaData rsmd = rs.getMetaData();
    int NumOfCol=0;
    NumOfCol=rsmd.getColumnCount();
    System.out.println("Query Executed!! No of Colm="+NumOfCol);

pandas dataframe columns scaling with sklearn

Like this?

dfTest = pd.DataFrame({
           'A':[14.00,90.20,90.95,96.27,91.21],
           'B':[103.02,107.26,110.35,114.23,114.68], 
           'C':['big','small','big','small','small']
         })
dfTest[['A','B']] = dfTest[['A','B']].apply(
                           lambda x: MinMaxScaler().fit_transform(x))
dfTest

    A           B           C
0   0.000000    0.000000    big
1   0.926219    0.363636    small
2   0.935335    0.628645    big
3   1.000000    0.961407    small
4   0.938495    1.000000    small

DLL References in Visual C++

The additional include directories are relative to the project dir. This is normally the dir where your project file, *.vcproj, is located. I guess that in your case you have to add just "include" to your include and library directories.

If you want to be sure what your project dir is, you can check the value of the $(ProjectDir) macro. To do that go to "C/C++ -> Additional Include Directories", press the "..." button and in the pop-up dialog press "Macros>>".