Programs & Examples On #Server mode

Show all tables inside a MySQL database using PHP?

<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
//Try This code is running perfectly !!!!!!!!!!


How do I get the current Date/time in DD/MM/YYYY HH:MM format?

The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):

Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"

Updated for the shifting:

d = DateTime.now
d.strftime("%d/%m/%Y %H:%M")
#=> "11/06/2017 18:11"
d.next_month.strftime("%d/%m/%Y %H:%M")
#=> "11/07/2017 18:11"

You need to require 'date' for this btw.

How do I check if a PowerShell module is installed?

You can use the ListAvailable option of Get-Module:

if (Get-Module -ListAvailable -Name SomeModule) {
    Write-Host "Module exists"
} 
else {
    Write-Host "Module does not exist"
}

Use FontAwesome or Glyphicons with css :before

@keithwyland answer is great. Here's a SCSS mixin:

@mixin font-awesome($content){
    font-family: FontAwesome;
    font-weight: normal;
    font-style: normal;
    display: inline-block;
    text-decoration: inherit;
    content: $content;
}

Usage:

@include font-awesome("\f054");

How to compare data between two table in different databases using Sql Server 2008?

In order to compare two databases, I've written the procedures bellow. If you want to compare two tables you can use procedure 'CompareTables'. Example :

EXEC master.dbo.CompareTables 'DB1', 'dbo', 'table1', 'DB2', 'dbo', 'table2'

If you want to compare two databases, use the procedure 'CompareDatabases'. Example :

EXEC master.dbo.CompareDatabases 'DB1', 'DB2'

Note : - I tried to make the procedures secure, but anyway, those procedures are only for testing and debugging. - If you want a complete solution for comparison use third party like (Visual Studio, ...)

USE [master]
GO

create proc [dbo].[CompareDatabases]
    @FirstDatabaseName nvarchar(50),
    @SecondDatabaseName nvarchar(50)
    as
begin
    -- Check that databases exist
    if not exists(SELECT name FROM sys.databases WHERE name=@FirstDatabaseName)
        return 0
    if not exists(SELECT name FROM sys.databases WHERE name=@SecondDatabaseName)
        return 0

    declare @result table (TABLE_NAME nvarchar(256))
    SET NOCOUNT ON
    insert into @result EXEC('(Select distinct TABLE_NAME from ' + @FirstDatabaseName  + '.INFORMATION_SCHEMA.COLUMNS '
                                    +'Where TABLE_SCHEMA=''dbo'')'
                            + 'intersect'
                            + '(Select distinct TABLE_NAME from ' + @SecondDatabaseName  + '.INFORMATION_SCHEMA.COLUMNS '
                                    +'Where TABLE_SCHEMA=''dbo'')')

    DECLARE @TABLE_NAME nvarchar(256)
    DECLARE curseur CURSOR FOR
        SELECT TABLE_NAME FROM @result
    OPEN curseur
    FETCH curseur INTO @TABLE_NAME
        WHILE @@FETCH_STATUS = 0
            BEGIN
                print 'TABLE : ' + @TABLE_NAME
                EXEC master.dbo.CompareTables @FirstDatabaseName, 'dbo', @TABLE_NAME, @SecondDatabaseName, 'dbo', @TABLE_NAME
                FETCH curseur INTO @TABLE_NAME
            END
        CLOSE curseur
    DEALLOCATE curseur
    SET NOCOUNT OFF
end
GO

.

USE [master]
GO

CREATE PROC [dbo].[CompareTables]
    @FirstTABLE_CATALOG nvarchar(256),
    @FirstTABLE_SCHEMA nvarchar(256),
    @FirstTABLE_NAME nvarchar(256),
    @SecondTABLE_CATALOG nvarchar(256),
    @SecondTABLE_SCHEMA nvarchar(256),
    @SecondTABLE_NAME nvarchar(256)
    AS
BEGIN
    -- Verify if first table exist
    DECLARE @table1 nvarchar(256) = @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME
    DECLARE @return_status int
    EXEC @return_status = master.dbo.TableExist @FirstTABLE_CATALOG, @FirstTABLE_SCHEMA, @FirstTABLE_NAME
    IF @return_status = 0
        BEGIN
            PRINT @table1 + ' : Table Not FOUND'
            RETURN 0
        END



    -- Verify if second table exist
    DECLARE @table2 nvarchar(256) = @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME
    EXEC @return_status = master.dbo.TableExist @SecondTABLE_CATALOG, @SecondTABLE_SCHEMA, @SecondTABLE_NAME
    IF @return_status = 0
        BEGIN
            PRINT @table2 + ' : Table Not FOUND'
            RETURN 0
        END

    -- Compare the two tables
    DECLARE @sql AS NVARCHAR(MAX)
    SELECT @sql = '('
                + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
                + 'EXCEPT'
                + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
                + ')'
                + 'UNION'
                + '('
                + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
                + 'EXCEPT'
                + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
                + ')'
    DECLARE @wrapper AS NVARCHAR(MAX) = 'if exists (' + @sql + ')' + char(10) + '    (' + @sql + ')ORDER BY 2'
    Exec(@wrapper)
END
GO

.

USE [master]
GO

CREATE PROC [dbo].[TableExist]
    @TABLE_CATALOG nvarchar(256),
    @TABLE_SCHEMA nvarchar(256),
    @TABLE_NAME nvarchar(256)
    AS
BEGIN
    IF NOT EXISTS(SELECT name FROM sys.databases WHERE name=@TABLE_CATALOG)
        RETURN 0

    declare @result table (TABLE_SCHEMA nvarchar(256), TABLE_NAME nvarchar(256))
    SET NOCOUNT ON
    insert into @result EXEC('Select TABLE_SCHEMA, TABLE_NAME from ' + @TABLE_CATALOG  + '.INFORMATION_SCHEMA.COLUMNS')
    SET NOCOUNT OFF

    IF EXISTS(SELECT TABLE_SCHEMA, TABLE_NAME FROM @result
                WHERE TABLE_SCHEMA=@TABLE_SCHEMA AND TABLE_NAME=@TABLE_NAME)
        RETURN 1

    RETURN 0
END

GO

Call angularjs function using jquery/javascript

Try this:

const scope = angular.element(document.getElementById('YourElementId')).scope();
scope.$apply(function(){
     scope.myfunction('test');
});

How to check for empty array in vba macro

You can check its count.

Here cid is an array.

if (jsonObject("result")("cid").Count) = 0 them
MsgBox "Empty Array"

I hope this helps. Have a nice day!

GoTo Next Iteration in For Loop in java

Use the continue keyword. Read here.

The continue statement skips the current iteration of a for, while , or do-while loop.

How can I find out which server hosts LDAP on my windows domain?

If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):

    mokey 0 /home/jj33 > nslookup example.ad
    Server:         172.16.2.10
    Address:        172.16.2.10#53

    Non-authoritative answer:
    Name:   example.ad
    Address: 172.16.6.2
    Name:   example.ad
    Address: 172.16.141.160
    Name:   example.ad
    Address: 172.16.7.9
    Name:   example.ad
    Address: 172.19.1.14
    Name:   example.ad
    Address: 172.19.1.3
    Name:   example.ad
    Address: 172.19.1.11
    Name:   example.ad
    Address: 172.16.3.2

Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.

I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.

How to use a variable for a key in a JavaScript object literal?

I couldn't find a simple example about the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.

ES6

var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';

matrix[a] = {[b]: {[c]: d}};

ES5

var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';

function addObj(obj, key, value) {
  obj[key] = value;
  return obj;
}

matrix[a] = addObj({}, b, addObj({}, c, d));

Remove Select arrow on IE

In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before css to match yours.

In case if it is IE10 then using below css3 it is possible

select::-ms-expand {
    display: none;
}

However if you're interested in jQuery plugin, try Chosen.js or you can create your own in js.

How can I find the version of the Fedora I use?

You could try

lsb_release -a

which works on at least Debian and Ubuntu (and since it's LSB, it should surely be on most of the other mainstream distros at least). http://rpmfind.net/linux/RPM/sourceforge/l/ls/lsb/lsb_release-1.0-1.i386.html suggests it's been around quite a while.

How to Animate Addition or Removal of Android ListView Rows

I have done something similar to this. One approach is to interpolate over the animation time the height of the view over time inside the rows onMeasure while issuing requestLayout() for the listView. Yes it may be be better to do inside the listView code directly but it was a quick solution (that looked good!)

Cleanest way to build an SQL string in Java

One technology you should consider is SQLJ - a way to embed SQL statements directly in Java. As a simple example, you might have the following in a file called TestQueries.sqlj:

public class TestQueries
{
    public String getUsername(int id)
    {
        String username;
        #sql
        {
            select username into :username
            from users
            where pkey = :id
        };
        return username;
    }
}

There is an additional precompile step which takes your .sqlj files and translates them into pure Java - in short, it looks for the special blocks delimited with

#sql
{
    ...
}

and turns them into JDBC calls. There are several key benefits to using SQLJ:

  • completely abstracts away the JDBC layer - programmers only need to think about Java and SQL
  • the translator can be made to check your queries for syntax etc. against the database at compile time
  • ability to directly bind Java variables in queries using the ":" prefix

There are implementations of the translator around for most of the major database vendors, so you should be able to find everything you need easily.

Return positions of a regex match() in Javascript?

Here is a cool feature I discovered recently, I tried this on the console and it seems to work:

var text = "border-bottom-left-radius";

var newText = text.replace(/-/g,function(match, index){
    return " " + index + " ";
});

Which returned: "border 6 bottom 13 left 18 radius"

So this seems to be what you are looking for.

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

In my case LD_LIBRARY_PATH had /usr/lib64 first before /usr/local/lib64. (I was builing llvm 3.9).
The new gcc compiler that I installed to compile llvm 3.9 had libraries using newer GLIBCXX libraries under /usr/local/lib64 So I fixed LD_LIBRARY_PATH for the linker to see /usr/local/lib64 first.
That solved this problem.

java.security.AccessControlException: Access denied (java.io.FilePermission

Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy file (path is as in the reply of Petey B)

permission java.io.FilePermission "your folder path", "write"

In your case it would be

permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"

Here /- means any files or sub-folders inside this folder.

Warning: But by doing this, you are inviting some security risk.

Add JsonArray to JsonObject

Your list:

List<MyCustomObject> myCustomObjectList;

Your JSONArray:

// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)

Your response:

return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));

Your post/put http body request would be like this:

    {
        "yourCustomKey: [
           {
               "myCustomObjectProperty": 1
           },
           {
               "myCustomObjectProperty": 2
           }
        ]
    }

How to stop mongo DB in one command

I simply did:

quit();

Please note I'm using mongo 3.0.

Mongo

How do I get information about an index and table owner in Oracle?

Below are two simple query using which you can check index created on a table in Oracle.

select index_name
  from dba_indexes
 where table_name='&TABLE_NAME'
   and owner='&TABLE_OWNER';
select index_name 
  from user_indexes 
 where table_name='&TABLE_NAME';

Please check for more details and index size below. Index on a table and its size in Oracle

How to change working directory in Jupyter Notebook?

on Jupyter notebook, try this:

pwd                  #this shows the current directory 

if this is not the directory you like and you would like to change, try this:

import os 
os.chdir ('THIS SHOULD BE YOUR DESIRED DIRECTORY')

Then try pwd again to see if the directory is what you want.

It works for me.

Static nested class in Java, why?

There are non-obvious memory retention issues to take into account here. Since a non-static inner class maintains an implicit reference to it's 'outer' class, if an instance of the inner class is strongly referenced, then the outer instance is strongly referenced too. This can lead to some head-scratching when the outer class is not garbage collected, even though it appears that nothing references it.

Should __init__() call the parent class's __init__()?

If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:

>>> class C(object):
        def __init__(self):
            self.b = 1


>>> class D(C):
        def __init__(self):
            super().__init__() # in Python 2 use super(D, self).__init__()
            self.a = 1


>>> class E(C):
        def __init__(self):
            self.a = 1


>>> d = D()
>>> d.a
1
>>> d.b  # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b  # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    e.b  # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'

__del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).

I rarely use __new__. I do all the initialization in __init__.

MySQL - Using COUNT(*) in the WHERE clause

SELECT COUNT(*)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC;

EDIT (if you just want the gids):

SELECT MIN(gid)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC

ReCaptcha API v2 Styling

You can also choose between a dark or light ReCaptcha theme. I used this in one of my Angular 8 Apps

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

What is the definition of "interface" in object oriented programming

In short, The basic problem an interface is trying to solve is to separate how we use something from how it is implemented. But you should consider interface is not a contract. Read more here.

Flatten List in LINQ

With query syntax:

var values =
from inner in outer
from value in inner
select value;

Difference between Dictionary and Hashtable

Want to add a difference:

Trying to acess a inexistent key gives runtime error in Dictionary but no problem in hashtable as it returns null instead of error.

e.g.

       //No strict type declaration
        Hashtable hash = new Hashtable();
        hash.Add(1, "One");
        hash.Add(2, "Two");
        hash.Add(3, "Three");
        hash.Add(4, "Four");
        hash.Add(5, "Five"); 
        hash.Add(6, "Six");
        hash.Add(7, "Seven");
        hash.Add(8, "Eight");
        hash.Add(9, "Nine");
        hash.Add("Ten", 10);// No error as no strict type

        for(int i=0;i<=hash.Count;i++)//=>No error for index 0
        {
            //Can be accessed through indexers
            Console.WriteLine(hash[i]);
        }
        Console.WriteLine(hash["Ten"]);//=> No error in Has Table

here no error for key 0 & also for key "ten"(note: t is small)

//Strict type declaration
        Dictionary<int,string> dictionary= new Dictionary<int, string>();
        dictionary.Add(1, "One");
        dictionary.Add(2, "Two");
        dictionary.Add(3, "Three");
        dictionary.Add(4, "Four");
        dictionary.Add(5, "Five");
        dictionary.Add(6, "Six");
        dictionary.Add(7, "Seven");
        dictionary.Add(8, "Eight");
        dictionary.Add(9, "Nine");
        //dictionary.Add("Ten", 10);// error as only key, value pair of type int, string can be added

        //for i=0, key doesn't  exist error
        for (int i = 1; i <= dictionary.Count; i++)
        {
            //Can be accessed through indexers
            Console.WriteLine(dictionary[i]);
        }
        //Error : The given key was not present in the dictionary.
        //Console.WriteLine(dictionary[10]);

here error for key 0 & also for key 10 as both are inexistent in dictionary, runtime error, while try to acess.

How to use Monitor (DDMS) tool to debug application

Go to

Tools > Android > Android Device Monitor

in v0.8.6. That will pull up the DDMS eclipse perspective.

how to open

Setting attribute disabled on a SPAN element does not prevent click events

The best method is to wrap the span inside a button and disable the button

_x000D_
_x000D_
$("#buttonD").click(function(){_x000D_
  alert("button clicked");_x000D_
})_x000D_
_x000D_
$("#buttonS").click(function(){_x000D_
  alert("span clicked");_x000D_
})
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<button class="btn btn-success" disabled="disabled" id="buttonD">_x000D_
    <span>Disabled button</span>_x000D_
</button>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
 <span class="btn btn-danger" disabled="disabled" id="buttonS">Disabled span</span>
_x000D_
_x000D_
_x000D_

What's the difference between JavaScript and Java?

Take a look at the Wikipedia link

JavaScript, despite the name, is essentially unrelated to the Java programming language, although both have the common C syntax, and JavaScript copies many Java names and naming conventions. The language was originally named "LiveScript" but was renamed in a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. The key design principles within JavaScript are inherited from the Self and Scheme programming languages.

How to redirect the output of print to a TXT file

Redirect sys.stdout to an open file handle and then all printed output goes to a file:

import sys
filename  = open("outputfile",'w')
sys.stdout = filename
print "Anything printed will go to the output file"

How to draw a graph in LaTeX?

I have used graphviz ( https://www.graphviz.org/gallery ) together with LaTeX using dot command to generate graphs in PDF and includegraphics to include those.

If graphviz produces what you are aiming at, this might be the best way to integrate: dot2tex: https://ctan.org/pkg/dot2tex?lang=en

Resize image with javascript canvas (smoothly)

I created a reusable Angular service to handle high quality resizing of images / canvases for anyone who's interested: https://gist.github.com/transitive-bullshit/37bac5e741eaec60e983

The service includes two solutions because they both have their own pros / cons. The lanczos convolution approach is higher quality at the cost of being slower, whereas the step-wise downscaling approach produces reasonably antialiased results and is significantly faster.

Example usage:

angular.module('demo').controller('ExampleCtrl', function (imageService) {
  // EXAMPLE USAGE
  // NOTE: it's bad practice to access the DOM inside a controller, 
  // but this is just to show the example usage.

  // resize by lanczos-sinc filter
  imageService.resize($('#myimg')[0], 256, 256)
    .then(function (resizedImage) {
      // do something with resized image
    })

  // resize by stepping down image size in increments of 2x
  imageService.resizeStep($('#myimg')[0], 256, 256)
    .then(function (resizedImage) {
      // do something with resized image
    })
})

Responsive table handling in Twitter Bootstrap

Bootstrap 3 now has Responsive tables out of the box. Hooray! :)

You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive

Add a <div class="table-responsive"> surrounding your table and you should be good to go:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

To make it work on all layouts you can do this:

.table-responsive
{
    overflow-x: auto;
}

Adding custom radio buttons in android

Best way to add custom drawable is:

<RadioButton
    android:id="@+id/radiocar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@android:color/transparent"
    android:button="@drawable/yourbuttonbackground"
    android:checked="true"
    android:drawableRight="@mipmap/car"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:text="yourtexthere"/>

Shadow overlay by custom drawable is removed here.

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

That's not the right way to set the permissions as you are overwriting them with each method call.

Replace this:

mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.setReadPermissions("public_profile");
mButtonLogin.setReadPermissions("email");
mButtonLogin.setReadPermissions("user_birthday");

With the following, as the method setReadPermissions() accepts an ArrayList:

loginButton.setReadPermissions(Arrays.asList(
        "public_profile", "email", "user_birthday", "user_friends"));

Also here is how to query extra data GraphRequest:

private LoginButton loginButton;
private CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setReadPermissions(Arrays.asList(
            "public_profile", "email", "user_birthday", "user_friends"));

    callbackManager = CallbackManager.Factory.create();

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("LoginActivity", response.toString());

                            // Application code
                            String email = object.getString("email");
                            String birthday = object.getString("birthday"); // 01/31/1980 format
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender,birthday");
            request.setParameters(parameters);
            request.executeAsync();


        }

        @Override
        public void onCancel() {
            // App code
            Log.v("LoginActivity", "cancel");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.v("LoginActivity", exception.getCause().toString());
        }
    });
}

EDIT:

One possible problem is that Facebook assumes that your email is invalid. To test it, use the Graph API Explorer and try to get it. If even there you can't get your email, change it in your profile settings and try again. This approach resolved this issue for some developers commenting my answer.

Using an Alias in a WHERE clause

Or you can have your alias in a HAVING clause

Create HTTP post request and receive response using C# console application

Insted of using System.Net.WebClient I would recommend to have a look on System.Net.Http.HttpClient which was introduced with net 4.5 and makes your life much easier.

Also microsoft recommends to use the HttpClient on this article

http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx

An example could look like this:

var client = new HttpClient();
var content = new MultipartFormDataContent
{
     { new StringContent("myUserId"), "userid"},
     { new StringContent("myFileName"), "filename"},
     { new StringContent("myPassword"), "password"},
     { new StringContent("myType"), "type"}
};

var responseMessage = await client.PostAsync("some url", content);        
var stream = await responseMessage.Content.ReadAsStreamAsync();

How to make a smaller RatingBar?

although answer of Farry works, for Samsung devices RatingBar took random blue color instead of the defined by me. So use

style="?attr/ratingBarStyleSmall"

instead.

Full code how to use it:

<android.support.v7.widget.AppCompatRatingBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="?attr/ratingBarStyleSmall" // use smaller version of icons
                android:theme="@style/RatingBar"
                android:rating="0"
                tools:rating="5"/>

<style name="RatingBar" parent="Theme.AppCompat">
        <item name="colorControlNormal">@color/grey</item>
        <item name="colorControlActivated">@color/yellow</item>
        <item name="android:numStars">5</item>
        <item name="android:stepSize">1</item>
    </style>

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

Try this:-

ALTER TABLE <TABLE NAME to be moved> MOVE TABLESPACE <destination TABLESPACE NAME>

Very nice suggestion from IVAN in comments so thought to add in my answer

Note: this will invalidate all table's indexes. So this command is usually followed by

alter index <owner>."<index_name>" rebuild;

How to write text on a image in windows using python opencv2

I had a similar problem. I would suggest using the PIL library in python as it draws the text in any given font, compared to limited fonts in OpenCV. With PIL you can choose any font installed on your system.

from PIL import ImageFont, ImageDraw, Image
import numpy as np
import cv2

image = cv2.imread("lena.png")

# Convert to PIL Image
cv2_im_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
pil_im = Image.fromarray(cv2_im_rgb)

draw = ImageDraw.Draw(pil_im)

# Choose a font
font = ImageFont.truetype("Roboto-Regular.ttf", 50)

# Draw the text
draw.text((0, 0), "Your Text Here", font=font)

# Save the image
cv2_im_processed = cv2.cvtColor(np.array(pil_im), cv2.COLOR_RGB2BGR)
cv2.imwrite("result.png", cv2_im_processed)

result.png

Running Windows batch file commands asynchronously

Create a batch file with the following lines:

start foo.exe
start bar.exe
start baz.exe 

The start command runs your command in a new window, so all 3 commands would run asynchronously.

How to set a string's color

Google aparently has a library for this sort of thing: http://code.google.com/p/jlibs/wiki/AnsiColoring

There's also a Javaworld article on this which solves your problem: http://www.javaworld.com/javaworld/javaqa/2002-12/02-qa-1220-console.html

How to add additional libraries to Visual Studio project?

Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:

  1. Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)

  2. Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.

  3. Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.

  4. Mash the build button.

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

How do I empty an input value with jQuery?

$('.reset').on('click',function(){
           $('#upload input, #upload select').each(
                function(index){  
                    var input = $(this);
                    if(input.attr('type')=='text'){
                        document.getElementById(input.attr('id')).value = null;
                    }else if(input.attr('type')=='checkbox'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else if(input.attr('type')=='radio'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else{
                        document.getElementById(input.attr('id')).value = '';
                        //alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
                    }
                }
            );
        });

how do I get eclipse to use a different compiler version for Java?

Just to clarify, do you have JAVA_HOME set as a system variable or set in Eclipse classpath variables? I'm pretty sure (but not totally sure!) that the system variable is used by the command line compiler (and Ant), but that Eclipse modifies this accroding to the JDK used

How to delete a specific line in a file?

I think if you read the file into a list, then do the you can iterate over the list to look for the nickname you want to get rid of. You can do it much efficiently without creating additional files, but you'll have to write the result back to the source file.

Here's how I might do this:

import, os, csv # and other imports you need
nicknames_to_delete = ['Nick', 'Stephen', 'Mark']

I'm assuming nicknames.csv contains data like:

Nick
Maria
James
Chris
Mario
Stephen
Isabella
Ahmed
Julia
Mark
...

Then load the file into the list:

 nicknames = None
 with open("nicknames.csv") as sourceFile:
     nicknames = sourceFile.read().splitlines()

Next, iterate over to list to match your inputs to delete:

for nick in nicknames_to_delete:
     try:
         if nick in nicknames:
             nicknames.pop(nicknames.index(nick))
         else:
             print(nick + " is not found in the file")
     except ValueError:
         pass

Lastly, write the result back to file:

with open("nicknames.csv", "a") as nicknamesFile:
    nicknamesFile.seek(0)
    nicknamesFile.truncate()
    nicknamesWriter = csv.writer(nicknamesFile)
    for name in nicknames:
        nicknamesWriter.writeRow([str(name)])
nicknamesFile.close()

Save bitmap to location

You should use the Bitmap.compress() method to save a Bitmap as a file. It will compress (if the format used allows it) your picture and push it into an OutputStream.

Here is an example of a Bitmap instance obtained through getImageBitmap(myurl) that can be compressed as a JPEG with a compression rate of 85% :

// Assume block needs to be inside a Try/Catch block.
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Integer counter = 0;
File file = new File(path, "FitnessGirl"+counter+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten.
fOut = new FileOutputStream(file);

Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush(); // Not really required
fOut.close(); // do not forget to close the stream

MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

How to use multiple databases in Laravel

Also you can use postgres fdw system

https://www.postgresql.org/docs/9.5/postgres-fdw.html

You will be able to connect different db in postgres. After that, in one query, you can access tables that are in different databases.

Linq on DataTable: select specific column into datatable, not whole table

Here I get only three specific columns from mainDataTable and use the filter

DataTable checkedParams = mainDataTable.Select("checked = true").CopyToDataTable()
.DefaultView.ToTable(false, "lagerID", "reservePeriod", "discount");

How to generate access token using refresh token through google drive API?

If you using Java then follow below code snippet :

GoogleCredential refreshTokenCredential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(HTTP_TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build().setRefreshToken(yourOldToken);
refreshTokenCredential.refreshToken(); //do not forget to call this
String newAccessToken = refreshTokenCredential.getAccessToken();

In the shell, what does " 2>&1 " mean?

This is just like passing the error to the stdout or the terminal.

That is, cmd is not a command:

$cmd 2>filename
cat filename

command not found

The error is sent to the file like this:

2>&1

Standard error is sent to the terminal.

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

I had a problem with this. I didn't use any clever $MyInvocation stuff to fix it though. If you open the ISE by right clicking a script file and selecting edit then open the second script from within the ISE you can invoke one from the other by just using the normal .\script.ps1 syntax. My guess is that the ISE has the notion of a current folder and opening it like this sets the current folder to the folder containing the scripts. When I invoke one script from another in normal use I just use .\script.ps1, IMO it's wrong to modify the script just to make it work in the ISE properly...

Where can I download mysql jdbc jar from?

If you have WL server installed, pick it up from under
\Oracle\Middleware\wlserver_10.3\server\lib\mysql-connector-java-commercial-5.1.17-bin.jar

Otherwise, download it from:
http://www.java2s.com/Code/JarDownload/mysql/mysql-connector-java-5.1.17-bin.jar.zip

What are the First and Second Level caches in (N)Hibernate?

Here some basic explanation of hibernate cache...

First level cache is associated with “session” object. The scope of cache objects is of session. Once session is closed, cached objects are gone forever. First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

Second level cache is apart from first level cache which is available to be used globally in session factory scope. second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory. It also means that once session factory is closed, all cache associated with it die and cache manager also closed down. Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session). If cached copy of entity is present in first level cache, it is returned as result of load method. If there is no cached entity in first level cache, then second level cache is looked up for cached entity. If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again. If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.

XML string to XML document

Using Linq to xml

Add a reference to System.Xml.Linq

and use

XDocument.Parse(string xmlString)

Edit: Sample follows, xml data (TestConfig.xml)..

<?xml version="1.0"?>
<Tests>
  <Test TestId="0001" TestType="CMD">
    <Name>Convert number to string</Name>
    <CommandLine>Examp1.EXE</CommandLine>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test TestId="0002" TestType="CMD">
    <Name>Find succeeding characters</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>abc</Input>
    <Output>def</Output>
  </Test>
  <Test TestId="0003" TestType="GUI">
    <Name>Convert multiple numbers to strings</Name>
    <CommandLine>Examp2.EXE /Verbose</CommandLine>
    <Input>123</Input>
    <Output>One Two Three</Output>
  </Test>
  <Test TestId="0004" TestType="GUI">
    <Name>Find correlated key</Name>
    <CommandLine>Examp3.EXE</CommandLine>
    <Input>a1</Input>
    <Output>b1</Output>
  </Test>
  <Test TestId="0005" TestType="GUI">
    <Name>Count characters</Name>
    <CommandLine>FinalExamp.EXE</CommandLine>
    <Input>This is a test</Input>
    <Output>14</Output>
  </Test>
  <Test TestId="0006" TestType="GUI">
    <Name>Another Test</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>Test Input</Input>
    <Output>10</Output>
  </Test>
</Tests>

C# usage...

XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
    from el in root.Elements("Test")
    where (string)el.Element("CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output: 0002 0006

How to implement a read only property

yet another way (my favorite), starting with C# 6

private readonly int MyVal = 5;

public int MyProp => MyVal;

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#expression-body-definitions

Delete worksheet in Excel using VBA

Try this code:

For Each aSheet In Worksheets

    Select Case aSheet.Name

        Case "ID Sheet", "Summary"
            Application.DisplayAlerts = False
            aSheet.Delete
            Application.DisplayAlerts = True

    End Select

Next aSheet

Pass arguments into C program from command line

Consider using getopt_long(). It allows both short and long options in any combination.

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

/* Flag set by `--verbose'. */
static int verbose_flag;

int
main (int argc, char *argv[])
{
  while (1)
    {
      static struct option long_options[] =
    {
      /* This option set a flag. */
      {"verbose", no_argument,       &verbose_flag, 1},
      /* These options don't set a flag.
         We distinguish them by their indices. */
      {"blip",    no_argument,       0, 'b'},
      {"slip",    no_argument,       0, 's'},
      {0,         0,                 0,  0}
    };
      /* getopt_long stores the option index here. */
      int option_index = 0;

      int c = getopt_long (argc, argv, "bs",
               long_options, &option_index);

      /* Detect the end of the options. */
      if (c == -1)
    break;

      switch (c)
    {
    case 0:
      /* If this option set a flag, do nothing else now. */
      if (long_options[option_index].flag != 0)
        break;
      printf ("option %s", long_options[option_index].name);
      if (optarg)
        printf (" with arg %s", optarg);
      printf ("\n");
      break;
    case 'b':
      puts ("option -b\n");
      break;
    case 's':
      puts ("option -s\n");
      break;
    case '?':
      /* getopt_long already printed an error message. */
      break;

    default:
      abort ();
    }
    }

  if (verbose_flag)
    puts ("verbose flag is set");

  /* Print any remaining command line arguments (not options). */
  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
    printf ("%s ", argv[optind++]);
      putchar ('\n');
    }

  return 0;
}

Related:

How to add hours to current date in SQL Server?

DATEADD (datepart , number , date )

declare @num_hours int; 
    set @num_hours = 5; 

select dateadd(HOUR, @num_hours, getdate()) as time_added, 
       getdate() as curr_date  

Increase heap size in Java

You can increase to 2GB on a 32 bit system. If you're on a 64 bit system you can go higher. No need to worry if you've chosen incorrectly, if you ask for 5g on a 32 bit system java will complain about an invalid value and quit.

As others have posted, use the cmd-line flags - e.g.

java -Xmx6g myprogram

You can get a full list (or a nearly full list, anyway) by typing java -X.

Skip over a value in the range function in python

It is time inefficient to compare each number, needlessly leading to a linear complexity. Having said that, this approach avoids any inequality checks:

import itertools

m, n = 5, 10
for i in itertools.chain(range(m), range(m + 1, n)):
    print(i)  # skips m = 5

As an aside, you woudn't want to use (*range(m), *range(m + 1, n)) even though it works because it will expand the iterables into a tuple and this is memory inefficient.


Credit: comment by njzk2, answer by Locke

Android Room - simple select query - Cannot access database on the main thread

You cannot run it on main thread instead use handlers, async or working threads . A sample code is available here and read article over room library here : Android's Room Library

/**
 *  Insert and get data using Database Async way
 */
AsyncTask.execute(new Runnable() {
    @Override
    public void run() {
        // Insert Data
        AppDatabase.getInstance(context).userDao().insert(new User(1,"James","Mathew"));

        // Get Data
        AppDatabase.getInstance(context).userDao().getAllUsers();
    }
});

If you want to run it on main thread which is not preferred way .

You can use this method to achieve on main thread Room.inMemoryDatabaseBuilder()

Setting PATH environment variable in OSX permanently

For a new path to be added to PATH environment variable in MacOS just create a new file under /etc/paths.d directory and add write path to be set in the file. Restart the terminal. You can check with echo $PATH at the prompt to confirm if the path was added to the environment variable.

For example: to add a new path /usr/local/sbin to the PATH variable:

cd /etc/paths.d
sudo vi newfile

Add the path to the newfile and save it.

Restart the terminal and type echo $PATH to confirm

C++ Remove new line from multiline string

 std::string some_str = SOME_VAL;
 if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' ) 
  some_str.resize( some_str.length()-1 );

or (removes several newlines at the end)

some_str.resize( some_str.find_last_not_of(L"\n")+1 );

How do I perform HTML decoding/encoding using Python/Django?

For html encoding, there's cgi.escape from the standard library:

>> help(cgi.escape)
cgi.escape = escape(s, quote=None)
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.

For html decoding, I use the following:

import re
from htmlentitydefs import name2codepoint
# for some reason, python 2.5.2 doesn't have this one (apostrophe)
name2codepoint['#39'] = 39

def unescape(s):
    "unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"
    return re.sub('&(%s);' % '|'.join(name2codepoint),
              lambda m: unichr(name2codepoint[m.group(1)]), s)

For anything more complicated, I use BeautifulSoup.

How to dismiss AlertDialog in android

Just set the view as null that will close the AlertDialog simple.

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

Bootstrap carousel width and height

I had the same problem.

My height changed to its original height while my slide was animating to the left, ( in a responsive website )

so I fixed it with CSS only :

.carousel .item.left img{
    width: 100% !important;
}

MySQL: @variable vs. variable. What's the difference?

MySQL has a concept of user-defined variables.

They are loosely typed variables that may be initialized somewhere in a session and keep their value until the session ends.

They are prepended with an @ sign, like this: @var

You can initialize this variable with a SET statement or inside a query:

SET @var = 1

SELECT @var2 := 2

When you develop a stored procedure in MySQL, you can pass the input parameters and declare the local variables:

DELIMITER //

CREATE PROCEDURE prc_test (var INT)
BEGIN
    DECLARE  var2 INT;
    SET var2 = 1;
    SELECT  var2;
END;
//

DELIMITER ;

These variables are not prepended with any prefixes.

The difference between a procedure variable and a session-specific user-defined variable is that a procedure variable is reinitialized to NULL each time the procedure is called, while the session-specific variable is not:

CREATE PROCEDURE prc_test ()
BEGIN
    DECLARE var2 INT DEFAULT 1;
    SET var2 = var2 + 1;
    SET @var2 = @var2 + 1;
    SELECT  var2, @var2;
END;

SET @var2 = 1;

CALL prc_test();

var2  @var2
---   ---
2     2


CALL prc_test();

var2  @var2
---   ---
2     3


CALL prc_test();

var2  @var2
---   ---
2     4

As you can see, var2 (procedure variable) is reinitialized each time the procedure is called, while @var2 (session-specific variable) is not.

(In addition to user-defined variables, MySQL also has some predefined "system variables", which may be "global variables" such as @@global.port or "session variables" such as @@session.sql_mode; these "session variables" are unrelated to session-specific user-defined variables.)

Else clause on Python while statement

The else clause is only executed when the while-condition becomes false.

Here are some examples:

Example 1: Initially the condition is false, so else-clause is executed.

i = 99999999

while i < 5:
    print(i)
    i += 1
else:
    print('this')

OUTPUT:

this

Example 2: The while-condition i < 5 never became false because i == 3 breaks the loop, so else-clause was not executed.

i = 0

while i < 5:
    print(i)
    if i == 3:
        break
    i += 1
else:
    print('this')

OUTPUT:

0
1
2
3

Example 3: The while-condition i < 5 became false when i was 5, so else-clause was executed.

i = 0

while i < 5:
    print(i)
    i += 1
else:
    print('this')

OUTPUT:

0
1
2
3
4
this

Abstraction VS Information Hiding VS Encapsulation

Please don't complicate simple concepts.

Encapsulation : Wrapping up of data and methods into a single unit is Encapsulation (e.g. Class)

Abstraction : It is an act of representing only the essential things without including background details. (e.g. Interface)

FOR EXAMPLES AND MORE INFO GOTO :

http://thecodekey.com/C_VB_Codes/Encapsulation.aspx

http://thecodekey.com/C_VB_Codes/Abstraction.aspx

Approved definitions here

P.S.: I also remember the definition from a book named C++ by Sumita Arora which we read in 11th class ;)

Elegant ways to support equivalence ("equality") in Python classes

From this answer: https://stackoverflow.com/a/30676267/541136 I have demonstrated that, while it's correct to define __ne__ in terms __eq__ - instead of

def __ne__(self, other):
    return not self.__eq__(other)

you should use:

def __ne__(self, other):
    return not self == other

What's the "average" requests per second for a production web application?

Not sure anyone is still interested, but this information was posted about Twitter (and here too):

The Stats

  • Over 350,000 users. The actual numbers are as always, very super super top secret.
  • 600 requests per second.
  • Average 200-300 connections per second. Spiking to 800 connections per second.
  • MySQL handled 2,400 requests per second.
  • 180 Rails instances. Uses Mongrel as the "web" server.
  • 1 MySQL Server (one big 8 core box) and 1 slave. Slave is read only for statistics and reporting.
  • 30+ processes for handling odd jobs.
  • 8 Sun X4100s.
  • Process a request in 200 milliseconds in Rails.
  • Average time spent in the database is 50-100 milliseconds.
  • Over 16 GB of memcached.

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

Passing data between view controllers

I recommend blocks/closures and custom constructors.

Suppose you have to pass string from FirstViewController to SecondViewController.

Your First View Controller.

class FirstViewController : UIViewController {

    func moveToViewControllerB() {

        let second_screen = SecondViewController.screen(string: "DATA TO PASS", call_back: {
            [weak self] (updated_data) in
            ///This closure will be called by second view controller when it updates something
        })
        self.navigationController?.pushViewController(second_screen, animated: true)
    }


}

Your Second View Controller

class SecondViewController : UIViewController {

    var incoming_string : String?
    var call_back : ((String) -> Void)?

    class func screen(string: String?, call_back : ((String) -> Void)?) -> SecondViewController {

        let me = SecondViewController(nibName: String(describing: self), bundle: Bundle.main);
        me.incoming_string = string
        me.call_back = call_back
        return me
    }

    // Suppose its called when you have to update FirstViewController with new data.
    func updatedSomething() {

        //Executing block that is implemented/assigned by the FirstViewController.
        self.call_back?("UPDATED DATA")
    }

}

Append an int to a std::string

You are casting ClientID to char* causing the function to assume its a null terinated char array, which it is not.

from cplusplus.com :

string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).

How to do scanf for single char in C

You have to use a valid variable. ch is not a valid variable for this program. Use char Aaa;

char aaa;
scanf("%c",&Aaa);

Tested and it works.

Text size and different android screen sizes

If you have API 26 then you might consider using autoSizeTextType:

<Button
  app:autoSizeTextType="uniform" />

Default setting lets the auto-sizing of TextView scale uniformly on horizontal and vertical axes.

https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The different methods are indications of priority. As you've listed them, they're going from least to most important. I think how you specifically map them to debug logs in your code depends on the component or app you're working on, as well as how Android treats them on different build flavors (eng, userdebug, and user). I have done a fair amount of work in the native daemons in Android, and this is how I do it. It may not apply directly to your app, but there may be some common ground. If my explanation sounds vague, it's because some of this is more of an art than a science. My basic rule is to be as efficient as possible, ensure you can reasonably debug your component without killing the performance of the system, and always check for errors and log them.

V - Printouts of state at different intervals, or upon any events occurring which my component processes. Also possibly very detailed printouts of the payloads of messages/events that my component receives or sends.

D - Details of minor events that occur within my component, as well as payloads of messages/events that my component receives or sends.

I - The header of any messages/events that my component receives or sends, as well as any important pieces of the payload which are critical to my component's operation.

W - Anything that happens that is unusual or suspicious, but not necessarily an error.

E - Errors, meaning things that aren't supposed to happen when things are working as they should.

The biggest mistake I see people make is that they overuse things like V, D, and I, but never use W or E. If an error is, by definition, not supposed to happen, or should only happen very rarely, then it's extremely cheap for you to log a message when it occurs. On the other hand, if every time somebody presses a key you do a Log.i(), you're abusing the shared logging resource. Of course, use common sense and be careful with error logs for things outside of your control (like network errors), or those contained in tight loops.

Maybe Bad

Log.i("I am here");

Good

Log.e("I shouldn't be here");

With all this in mind, the closer your code gets to "production ready", the more you can restrict the base logging level for your code (you need V in alpha, D in beta, I in production, or possibly even W in production). You should run through some simple use cases and view the logs to ensure that you can still mostly understand what's happening as you apply more restrictive filtering. If you run with the filter below, you should still be able to tell what your app is doing, but maybe not get all the details.

logcat -v threadtime MyApp:I *:S

Displaying unicode symbols in HTML

I know an answer has already been accepted, but wanted to point a few things out.

Setting the content-type and charset is obviously a good practice, doing it on the server is much better, because it ensures consistency across your application.

However, I would use UTF-8 only when the language of my application uses a lot of characters that are available only in the UTF-8 charset. If you want to show a unicode character or symbol in one of cases, you can do so without changing the charset of your page.

HTML renderers have always been able to display symbols which are not part of the encoding character set of the page, as long as you mention the symbol in its numeric character reference (NCR). Sounds weird but its true.

So, even if your html has a header that states it has an encoding of ansi or any of the iso charsets, you can display a check mark by using its html character reference, in decimal - &#10003; or in hex - &#x2713;

So its a little difficult to understand why you are facing this issue on your pages. Can you check if the NCR value is correct, this is a good reference http://www.fileformat.info/info/unicode/char/2713/index.htm

How to clear/remove observable bindings in Knockout.js?

I think it might be better to keep the binding the entire time, and simply update the data associated with it. I ran into this issue, and found that just calling using the .resetAll() method on the array in which I was keeping my data was the most effective way to do this.

Basically you can start with some global var which contains data to be rendered via the ViewModel:

var myLiveData = ko.observableArray();

It took me a while to realize I couldn't just make myLiveData a normal array -- the ko.oberservableArray part was important.

Then you can go ahead and do whatever you want to myLiveData. For instance, make a $.getJSON call:

$.getJSON("http://foo.bar/data.json?callback=?", function(data) {
    myLiveData.removeAll();
    /* parse the JSON data however you want, get it into myLiveData, as below */
    myLiveData.push(data[0].foo);
    myLiveData.push(data[4].bar);
});

Once you've done this, you can go ahead and apply bindings using your ViewModel as usual:

function MyViewModel() {
    var self = this;
    self.myData = myLiveData;
};
ko.applyBindings(new MyViewModel());

Then in the HTML just use myData as you normally would.

This way, you can just muck with myLiveData from whichever function. For instance, if you want to update every few seconds, just wrap that $.getJSON line in a function and call setInterval on it. You'll never need to remove the binding as long as you remember to keep the myLiveData.removeAll(); line in.

Unless your data is really huge, user's won't even be able to notice the time in between resetting the array and then adding the most-current data back in.

Check if string contains only whitespace

I used following:

if str and not str.isspace():
  print('not null and not empty nor whitespace')
else:
  print('null or empty or whitespace')

What are the rules for casting pointers in C?

char c = '5'

A char (1 byte) is allocated on stack at address 0x12345678.

char *d = &c;

You obtain the address of c and store it in d, so d = 0x12345678.

int *e = (int*)d;

You force the compiler to assume that 0x12345678 points to an int, but an int is not just one byte (sizeof(char) != sizeof(int)). It may be 4 or 8 bytes according to the architecture or even other values.

So when you print the value of the pointer, the integer is considered by taking the first byte (that was c) and other consecutive bytes which are on stack and that are just garbage for your intent.

Is it possible to sort a ES6 map object?

2 hours spent to get into details.

Note that the answer for question is already given at https://stackoverflow.com/a/31159284/984471

However, the question has keys that are not usual ones,
A clear & general example with explanation, is below that provides some more clarity:

.

let m1 = new Map();

m1.set(6,1); // key 6 is number and type is preserved (can be strings too)
m1.set(10,1);
m1.set(100,1);
m1.set(1,1);
console.log(m1);

// "string" sorted (even if keys are numbers) - default behaviour
let m2 = new Map( [...m1].sort() );
//      ...is destructuring into individual elements
//      then [] will catch elements in an array
//      then sort() sorts the array
//      since Map can take array as parameter to its constructor, a new Map is created
console.log('m2', m2);

// number sorted
let m3 = new Map([...m1].sort((a, b) => {
  if (a[0] > b[0]) return 1;
  if (a[0] == b[0]) return 0;
  if (a[0] < b[0]) return -1;
}));
console.log('m3', m3);

// Output
//    Map { 6 => 1, 10 => 1, 100 => 1, 1 => 1 }
// m2 Map { 1 => 1, 10 => 1, 100 => 1, 6 => 1 }
//           Note:  1,10,100,6  sorted as strings, default.
//           Note:  if the keys were string the sort behavior will be same as this
// m3 Map { 1 => 1, 6 => 1, 10 => 1, 100 => 1 }
//           Note:  1,6,10,100  sorted as number, looks correct for number keys

Hope that helps.

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

It's because your enum is not the standard library enum module. You probably have the package enum34 installed.

One way check if this is the case is to inspect the property enum.__file__

import enum
print(enum.__file__)  
# standard library location should be something like 
# /usr/local/lib/python3.6/enum.py

Since python 3.6 the enum34 library is no longer compatible with the standard library. The library is also unnecessary, so you can simply uninstall it.

pip uninstall -y enum34

If you need the code to run on python versions both <=3.4 and >3.4, you can try having enum-compat as a requirement. It only installs enum34 for older versions of python without the standard library enum.

How to empty a char array?

EDIT: Given the most recent edit to the question, this will no longer work as there is no null termination - if you tried to print the array, you would get your characters followed by a number of non-human-readable characters. However, I'm leaving this answer here as community wiki for posterity.

char members[255] = { 0 };

That should work. According to the C Programming Language:

If the array has fixed size, the number of initializers may not exceed the number of members of the array; if there are fewer, the remaining members are initialized with 0.

This means that every element of the array will have a value of 0. I'm not sure if that is what you would consider "empty" or not, since 0 is a valid value for a char.

installing python packages without internet and using source code as .tar.gz and .whl

We have a similar situation at work, where the production machines have no access to the Internet; therefore everything has to be managed offline and off-host.

Here is what I tried with varied amounts of success:

  1. basket which is a small utility that you run on your internet-connected host. Instead of trying to install a package, it will instead download it, and everything else it requires to be installed into a directory. You then move this directory onto your target machine. Pros: very easy and simple to use, no server headaches; no ports to configure. Cons: there aren't any real showstoppers, but the biggest one is that it doesn't respect any version pinning you may have; it will always download the latest version of a package.

  2. Run a local pypi server. Used pypiserver and devpi. pypiserver is super simple to install and setup; devpi takes a bit more finagling. They both do the same thing - act as a proxy/cache for the real pypi and as a local pypi server for any home-grown packages. localshop is a new one that wasn't around when I was looking, it also has the same idea. So how it works is your internet-restricted machine will connect to these servers, they are then connected to the Internet so that they can cache and proxy the actual repository.

The problem with the second approach is that although you get maximum compatibility and access to the entire repository of Python packages, you still need to make sure any/all dependencies are installed on your target machines (for example, any headers for database drivers and a build toolchain). Further, these solutions do not cater for non-pypi repositories (for example, packages that are hosted on github).

We got very far with the second option though, so I would definitely recommend it.

Eventually, getting tired of having to deal with compatibility issues and libraries, we migrated the entire circus of servers to commercially supported docker containers.

This means that we ship everything pre-configured, nothing actually needs to be installed on the production machines and it has been the most headache-free solution for us.

We replaced the pypi repositories with a local docker image server.

Creating Unicode character from its number

This one worked fine for me.

  String cc2 = "2202";
  String text2 = String.valueOf(Character.toChars(Integer.parseInt(cc2, 16)));

Now text2 will have ?.

Given URL is not allowed by the Application configuration

I faced the same issue. I had entered http://www.example.com in the App settings. When anybody accessed my website using the full URL, Facebook Login worked fine. But if somebody typed in the URL without www in the browser, Facebook Login failed with this error message. When I changed the App Setting to http://example.com everything started working fine.

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

Android: I am unable to have ViewPager WRAP_CONTENT

I based my answer on Daniel López Lacalle and this post http://www.henning.ms/2013/09/09/viewpager-that-simply-dont-measure-up/. The problem with Daniel's answer is that in some cases my children had a height of zero. The solution was to unfortunately measure twice.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int mode = MeasureSpec.getMode(heightMeasureSpec);
    // Unspecified means that the ViewPager is in a ScrollView WRAP_CONTENT.
    // At Most means that the ViewPager is not in a ScrollView WRAP_CONTENT.
    if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
        // super has to be called in the beginning so the child views can be initialized.
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            if (h > height) height = h;
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    }
    // super has to be called again so the new specs are treated as exact measurements
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

This also lets you set a height on the ViewPager if you so want to or just wrap_content.

The pipe ' ' could not be found angular2 custom pipe

import { Component, Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'timePipe'
})
export class TimeValuePipe implements PipeTransform {

  transform(value: any, args?: any): any {
   var hoursMinutes = value.split(/[.:]/);
  var hours = parseInt(hoursMinutes[0], 10);
  var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
  console.log('hours ', hours);
  console.log('minutes ', minutes/60);
  return (hours + minutes / 60).toFixed(2);
  }
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  order = [
    {
      "order_status": "Still at Shop",
      "order_id": "0:02"
    },
    {
      "order_status": "On the way",
      "order_id": "02:29"
    },
    {
      "order_status": "Delivered",
      "order_id": "16:14"
    },
     {
      "order_status": "Delivered",
      "order_id": "07:30"
    }
  ]
}

Invoke this module in App.Module.ts file.

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

The normal usage of static is to access the function directly with out any object creation. Same as in java main we could not create any object for that class to invoke the main method. It will execute automatically. If we want to execute manually we can call by using main() inside the class and ClassName.main from outside the class.

Angular checkbox and ng-click

You can use ng-change instead of ng-click:

<!doctype html>
<html>
<head>
  <script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
  <script>
        var app = angular.module('myapp', []);
        app.controller('mainController', function($scope) {
          $scope.vm = {};
          $scope.vm.myClick = function($event) {
                alert($event);
          }
        });     
  </script>  
</head>
<body ng-app="myapp">
  <div ng-controller="mainController">
    <input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
  </div>
</body>
</html>

React JS - Uncaught TypeError: this.props.data.map is not a function

More generally, you can also convert the new data into an array and use something like concat:

var newData = this.state.data.concat([data]);  
this.setState({data: newData})

This pattern is actually used in Facebook's ToDo demo app (see the section "An Application") at https://facebook.github.io/react/.

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

How to define an optional field in protobuf 3

Another way to encode the message you intend is to add another field to track "set" fields:

syntax="proto3";

package qtprotobuf.examples;

message SparseMessage {
    repeated uint32 fieldsUsed = 1;
    bool   attendedParty = 2;
    uint32 numberOfKids  = 3;
    string nickName      = 4;
}

message ExplicitMessage {
    enum PARTY_STATUS {ATTENDED=0; DIDNT_ATTEND=1; DIDNT_ASK=2;};
    PARTY_STATUS attendedParty = 1;
    bool   indicatedKids = 2;
    uint32 numberOfKids  = 3;
    enum NO_NICK_STATUS {HAS_NO_NICKNAME=0; WOULD_NOT_ADMIT_TO_HAVING_HAD_NICKNAME=1;};
    NO_NICK_STATUS noNickStatus = 4;
    string nickName      = 5;
}

This is especially appropriate if there is a large number of fields and only a small number of them have been assigned.

In python, usage would look like this:

import field_enum_example_pb2
m = field_enum_example_pb2.SparseMessage()
m.attendedParty = True
m.fieldsUsed.append(field_enum_example_pb2.SparseMessages.ATTENDEDPARTY_FIELD_NUMBER)

sudo: docker-compose: command not found

The output of dpkg -s ... demonstrates that docker-compose is not installed from a package. Without more information from you there are at least two possibilities:

  1. docker-compose simply isn't installed at all, and you need to install it.

    The solution here is simple: install docker-compose.

  2. docker-compose is installed in your $HOME directory (or other location not on root's $PATH).

    There are several solution in this case. The easiest is probably to replace:

    sudo docker-compose ...
    

    With:

    sudo `which docker-compose` ...
    

    This will call sudo with the full path to docker-compose.

    You could alternatively install docker-compose into a system-wide directory, such as /usr/local/bin.

How to remove certain characters from a string in C++?

If you have access to a compiler that supports variadic templates, you can use this:

#include <iostream>
#include <string>
#include <algorithm>

template<char ... CharacterList>
inline bool check_characters(char c) {
    char match_characters[sizeof...(CharacterList)] = { CharacterList... };
    for(int i = 0; i < sizeof...(CharacterList); ++i) {
        if(c == match_characters[i]) {
            return true;
        }
    }
    return false;
}

template<char ... CharacterList>
inline void strip_characters(std::string & str) {
    str.erase(std::remove_if(str.begin(), str.end(), &check_characters<CharacterList...>), str.end());
}

int main()
{
    std::string str("(555) 555-5555");
    strip_characters< '(',')','-' >(str);
    std::cout << str << std::endl;
}

Strings in C, how to get subString

You can use snprintf to get a substring of a char array with precision. Here is a file example called "substring.c":

#include <stdio.h>

int main()
{
    const char source[] = "This is a string array";
    char dest[17];

    // get first 16 characters using precision
    snprintf(dest, sizeof(dest), "%.16s", source);

    // print substring
    puts(dest);
} // end main

Output:

This is a string

Note:

For further information see printf man page.

SQL Server SELECT into existing table

select *
into existing table database..existingtable
from database..othertables....

If you have used select * into tablename from other tablenames already, next time, to append, you say select * into existing table tablename from other tablenames

How to check if a word is an English word with Python?

I find that there are 3 package-based solutions to solve the problem. They are pyenchant, wordnet and corpus(self-defined or from ntlk). Pyenchant couldn't installed easily in win64 with py3. Wordnet doesn't work very well because it's corpus isn't complete. So for me, I choose the solution answered by @Sadik, and use 'set(words.words())' to speed up.

First:

pip3 install nltk
python3

import nltk
nltk.download('words')

Then:

from nltk.corpus import words
setofwords = set(words.words())

print("hello" in setofwords)
>>True

Creating a List of Lists in C#

you should not use Nested List in List.

List<List<T>> 

is not legal, even if T were a defined type.

https://msdn.microsoft.com/en-us/library/ms182144.aspx

Pip freeze vs. pip list

Look at the pip documentation, which describes the functionality of both as:

pip list

List installed packages, including editables.

pip freeze

Output installed packages in requirements format.

So there are two differences:

  1. Output format, freeze gives us the standard requirement format that may be used later with pip install -r to install requirements from.

  2. Output content, pip list include editables which pip freeze does not.

Display / print all rows of a tibble (tbl_df)

The tibble vignette has an updated way to change its default printing behavior:

You can control the default appearance with options:

options(tibble.print_max = n, tibble.print_min = m): if there are more than n rows, print only the first m rows. Use options(tibble.print_max = Inf) to always show all rows.

options(tibble.width = Inf) will always print all columns, regardless of the width of the screen.

examples

This will always print all rows:

options(tibble.print_max = Inf)

This will not actually limit the printing to 50 lines:

options(tibble.print_max = 50)

But this will restrict printing to 50 lines:

options(tibble.print_max = 50, tibble.print_min = 50)

Reading and displaying data from a .txt file

Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).

import java.io.*;
import java.util.Scanner;
import java.io.*;

public class TestRead
{
public static void main(String[] input)
{
    String fname;
    Scanner scan = new Scanner(System.in);

    /* enter filename with extension to open and read its content */

    System.out.print("Enter File Name to Open (with extension like file.txt) : ");
    fname = scan.nextLine();

    /* this will reference only one line at a time */

    String line = null;
    try
    {
        /* FileReader reads text files in the default encoding */
        FileReader fileReader = new FileReader(fname);

        /* always wrap the FileReader in BufferedReader */
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null)
        {
            System.out.println(line);
        }

        /* always close the file after use */
        bufferedReader.close();
    }
    catch(IOException ex)
    {
        System.out.println("Error reading file named '" + fname + "'");
    }
}

}

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/

"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:

Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."

How to disable mouse scroll wheel scaling with Google Maps API

Daniel's code does the job (thanks a heap!). But I wanted to disable zooming completely. I found I had to use all four of these options to do so:

{
  zoom: 14,                        // Set the zoom level manually
  zoomControl: false,
  scaleControl: false,
  scrollwheel: false,
  disableDoubleClickZoom: true,
  ...
}

See: MapOptions object specification

HTML5 canvas ctx.fillText won't do line breaks?

This question isn't thinking in terms of how canvas works. If you want a line break just simply adjust the coordinates of your next ctx.fillText.

ctx.fillText("line1", w,x,y,z)
ctx.fillText("line2", w,x,y,z+20)

Setting an environment variable before a command in Bash is not working for the second command in a pipe

How about exporting the variable, but only inside the subshell?:

(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:

(export FOO=bar; somecommand someargs | somecommand2)

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

What's the difference between primitive and reference types?

Primitives vs. References

First :-

Primitive types are the basic types of data: byte, short, int, long, float, double, boolean, char. Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String, Scanner, Random, Die, int[], String[], etc. Reference variables store addresses to locations in memory for where the data is stored.

Second:-

Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.

Read more: http://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

How can I implement custom Action Bar with custom buttons in Android?

1 You can use a drawable

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_item1"
        android:icon="@drawable/my_item_drawable"
        android:title="@string/menu_item1"
        android:showAsAction="ifRoom" />
</menu>

2 Create a style for the action bar and use a custom background:

<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <!-- other activity and action bar styles here -->
    </style>
    <!-- style for the action bar backgrounds -->
    <style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
        <item name="android:background">@drawable/background</item>
        <item name="android:backgroundStacked">@drawable/background</item>
        <item name="android:backgroundSplit">@drawable/split_background</item>
    </style>
</resources>

3 Style again android:actionBarDivider

The android documentation is very usefull for that.

Find all elements on a page whose element ID contains a certain text using jQuery

This selects all DIVs with an ID containing 'foo' and that are visible

$("div:visible[id*='foo']");

java.io.IOException: Server returned HTTP response code: 500

The problem must be with the parameters you are passing(You must be passing blank parameters). For example : http://www.myurl.com?id=5&name= Check if you are handling this at the server you are calling.

When do items in HTML5 local storage expire?

You can use lscache. It handles this for you automatically, including instances where the storage size exceeds the limit. If that happens, it begins pruning items that are the closest to their specified expiration.

From the readme:

lscache.set

Stores the value in localStorage. Expires after specified number of minutes.

Arguments
key (string)
value (Object|string)
time (number: optional)

This is the only real difference between the regular storage methods. Get, remove, etc work the same.

If you don't need that much functionality, you can simply store a time stamp with the value (via JSON) and check it for expiry.

Noteworthy, there's a good reason why local storage is left up to the user. But, things like lscache do come in handy when you need to store extremely temporary data.

How to pass parameter to click event in Jquery

Better Approach:

<script type="text/javascript">
    $('#btn').click(function() {
      var id = $(this).attr('id');
      alert(id);
    });
</script>

<input id="btn" type="button" value="click" />

But, if you REALLY need to do the click handler inline, this will work:

<script type="text/javascript">
    function display(el) {
        var id = $(el).attr('id');
        alert(id);
    }
</script>

<input id="btn" type="button" value="click" OnClick="display(this);" />

Flutter - Layout a Grid

GridView is used for implementing material grid lists. If you know you have a fixed number of items and it's not very many (16 is fine), you can use GridView.count. However, you should note that a GridView is scrollable, and if that isn't what you want, you may be better off with just rows and columns.

screenshot

import 'dart:collection';
import 'package:flutter/scheduler.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Grid Demo'),
      ),
      body: new GridView.count(
        crossAxisCount: 4,
        children: new List<Widget>.generate(16, (index) {
          return new GridTile(
            child: new Card(
              color: Colors.blue.shade200,
              child: new Center(
                child: new Text('tile $index'),
              )
            ),
          );
        }),
      ),
    );
  }
}

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Just do this

<button OnClick=" location.href='link.html' ">Visit Page Now</button>

Although, it's been a while since I've touched JavaScript - maybe location.href is outdated? Anyways, that's how I would do it.

How do you completely remove the button border in wpf?

You may already know that putting your Button inside of a ToolBar gives you this behavior, but if you want something that will work across ALL current themes with any sort of predictability, you'll need to create a new ControlTemplate.

Prashant's solution does not work with a Button not in a toolbar when the Button has focus. It also doesn't work 100% with the default theme in XP -- you can still see faint gray borders when your container Background is white.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

error: member access into incomplete type : forward declaration of

Move doSomething definition outside of its class declaration and after B and also make add accessible to A by public-ing it or friend-ing it.

class B;

class A
{
    void doSomething(B * b);
};

class B
{
public:
    void add() {}
};

void A::doSomething(B * b)
{
    b->add();
}

Creating java date object from year,month,day

Make your life easy when working with dates, timestamps and durations. Use HalDateTime from

http://sourceforge.net/projects/haldatetime/?source=directory

For example you can just use it to parse your input like this:

HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate );   // will print in ISO format: 1988-12-25

You can also specify patterns for parsing and printing.

Streaming video from Android camera to server

I am able to send the live camera video from mobile to my server.using this link see the link

Refer the above link.there is a sample application in that link. Just you need to set your service url in RecordActivity.class.

Example as: ffmpeg_link="rtmp://yourserveripaddress:1935/live/venkat";

we can able to send H263 and H264 type videos using that link.

Posting raw image data as multipart/form-data in curl

CURL OPERATION BETWEEN SERVER TO SERVER WITHOUT HTML FORM IN PHP USING MULTIPART/FORM-DATA

// files to upload

$filename = "https://example.s3.amazonaws.com/0.jpg";       

// URL to upload to (Destination server)

$url = "https://otherserver/image";

AND

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        //CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => file_get_contents($filename),
        CURLOPT_HTTPHEADER => array(
            //"Authorization: Bearer $TOKEN",
            "Content-Type: multipart/form-data",
            "Content-Length: " . strlen(file_get_contents($filename)),
            "API-Key: abcdefghi" //Optional if required
        ),
    ));

   $response = curl_exec($curl);

    $info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";

//print_r($info['request_header']);

    var_dump($response);
    $err = curl_error($curl);

    echo "error";
    var_dump($err);
    curl_close($curl);

Having both a Created and Last Updated timestamp columns in MySQL 4.0

If you do decide to have MySQL handle the update of timestamps, you can set up a trigger to update the field on insert.

CREATE TRIGGER <trigger_name> BEFORE INSERT ON <table_name> FOR EACH ROW SET NEW.<timestamp_field> = CURRENT_TIMESTAMP;

MySQL Reference: http://dev.mysql.com/doc/refman/5.0/en/triggers.html

How to stop execution after a certain time in Java?

long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
    // run
}

How to turn on/off MySQL strict mode in localhost (xampp)?

I want to know how to check whether MySQL strict mode is on or off in localhost(xampp).

SHOW VARIABLES LIKE 'sql_mode';

If result has "STRICT_TRANS_TABLES", then it's ON. Otherwise, it's OFF.

If on then for what modes and how to off.

If off then how to on.

For Windows,

  1. Go to C:\Program Files\MariaDB XX.X\data
  2. Open the my.ini file.
  3. *On the line with "sql_mode", modify the value to turn strict mode ON/OFF.
  4. Save the file
  5. **Restart the MySQL service
  6. Run SHOW VARIABLES LIKE 'sql_mode' again to see if it worked;

*3.a. To turn it ON, add STRICT_TRANS_TABLES on that line like this: sql_mode=STRICT_TRANS_TABLES. *If there are other values already, add a comma after this then join with the rest of the value.

*3.b. To turn it OFF, simply remove STRICT_TRANS_TABLES from value. *Remove the additional comma too if there is one.

**6. To restart the MySQL service on your computer,

  1. Open the Run command window (press WINDOWS + R button).
  2. Type services.msc
  3. Click OK
  4. Right click on the Name MySQL
  5. Click Restart

Get Maven artifact version at runtime

A simple solution which is Maven compatible and works for any (thus also third party) class:

    private static Optional<String> getVersionFromManifest(Class<?> clazz) {
        try {
            File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
            if (file.isFile()) {
                JarFile jarFile = new JarFile(file);
                Manifest manifest = jarFile.getManifest();
                Attributes attributes = manifest.getMainAttributes();
                final String version = attributes.getValue("Bundle-Version");
                return Optional.of(version);
            }
        } catch (Exception e) {
            // ignore
        }
        return Optional.empty();
    }

Phone number validation Android

We can use pattern to validate it.

android.util.Patterns.PHONE

public class GeneralUtils {

    private static boolean isValidPhoneNumber(String phoneNumber) {
        return !TextUtils.isEmpty(phoneNumber) && android.util.Patterns.PHONE.matcher(phoneNumber).matches();
    }

}

How do I make a checkbox required on an ASP.NET form?

I typically perform the validation on the client side:

<asp:checkbox id="chkTerms" text=" I agree to the terms" ValidationGroup="vg" runat="Server"  />
<asp:CustomValidator id="vTerms"
                ClientValidationFunction="validateTerms" 
                ErrorMessage="<br/>Terms and Conditions are required." 
                ForeColor="Red"
                Display="Static"
                EnableClientScript="true"
                ValidationGroup="vg"
                runat="server"/>

<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" CausesValidation="true" Text="Submit" ValidationGroup="vg" runat="server" />

<script>
    function validateTerms(source, arguments) {
        var $c = $('#<%= chkTerms.ClientID %>');
        if($c.prop("checked")){
            arguments.IsValid = true;
        } else {
            arguments.IsValid = false;
        }
    }
</script>       

Cannot redeclare function php

Remove the function and check the output of:

var_dump(function_exists('parseDate'));

In which case, change the name of the function.

If you get false, you're including the file with that function twice, replace :

include

by

include_once

And replace :

require

by

require_once

EDIT : I'm just a little too late, post before beat me to it !

Evaluate list.contains string in JSTL

Sadly, I think that JSTL doesn't support anything but an iteration through all elements to figure this out. In the past, I've used the forEach method in the core tag library:

<c:set var="contains" value="false" />
<c:forEach var="item" items="${myList}">
  <c:if test="${item eq myValue}">
    <c:set var="contains" value="true" />
  </c:if>
</c:forEach>

After this runs, ${contains} will be equal to "true" if myList contained myValue.

Merge two HTML table cells

Add an attribute colspan (abbriviation for 'column span') in your top cell (<td>) and set its value to 2. Your table should resembles the following;

<table>
    <tr>
        <td colspan = "2">
            <!-- Merged Columns -->
        </td>
    </tr>

    <tr>
        <td>
            <!-- Column 1 -->
        </td>

        <td>
            <!-- Column 2 -->
        </td>
    </tr>
</table>

See also
     W3 official docs on HTML Tables

How do I get the title of the current active window using c#?

If you were talking about WPF then use:

 Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);

How to deserialize a list using GSON or another JSON library in Java?

With Gson, you'd just need to do something like:

List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());

You might also need to provide a no-arg constructor on the Video class you're deserializing to.

Change header background color of modal of twitter bootstrap

You can solve this by simply adding class to modal-header

<div class="modal-header bg-primary text-white">

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Both times when you write the package name : 1. When you create a new project in Android Studio and 2. When you create a Configuration File

YOU should write it with lowercase letters - after changing to lowercase it works. If you don't want to waste time just go to you .json file and replace com.myname.MyAPPlicationnamE with com.myname.myapplicationname (for every match in the json file).

Is there a way to follow redirects with command line cURL?

As said, to follow redirects you can use the flag -L or --location:

curl -L http://www.example.com

But, if you want limit the number of redirects, add the parameter --max-redirs

--max-redirs <num>

Set maximum number of redirection-followings allowed. If -L, --location is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.

Differences between ConstraintLayout and RelativeLayout

The only difference i've noted is that things set in a relative layout via drag and drop automatically have their dimensions relative to other elements inferred, so when you run the app what you see is what you get. However in the constraint layout even if you drag and drop an element in the design view, when you run the app things may be shifted around. This can easily be fixed by manually setting the constraints or, a more risky move being to right click the element in the component tree, selecting the constraint layout sub menu, then clicking 'infer constraints'. Hope this helps

Windows-1252 to UTF-8 encoding

You can change the encoding of a file with an editor such as notepad++. Just go to Encoding and select what you want.

I always prefer the Windows 1252

Finding first blank row, then writing to it

very old thread but .. i was lookin for an "easier"... a smaller code

i honestly dont understand any of the answers above :D - i´m a noob

but this should do the job. (for smaller sheets)

Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Add

reads every cell in col 1 from bottom up and stops at first empty cell

intRow = 1
Do until objExcel.Cells(intRow, 1).Value = ""
   intRow = intRow + 1
Loop

then you can write your info like this

objExcel.Cells(intRow, 1).Value = "first emtpy row, col 1"
objExcel.Cells(intRow, 2).Value = "first emtpy row, col 2"

etc...

and then i recognize its an vba thread ... lol

How can I add a hint or tooltip to a label in C# Winforms?

just another way to do it.

Label lbl = new Label();
new ToolTip().SetToolTip(lbl, "tooltip text here");

Convert row to column header for Pandas DataFrame,

To rename the header without reassign df:

df.rename(columns=df.iloc[0], inplace = True)

To drop the row without reassign df:

df.drop(df.index[0], inplace = True)

Convert Dictionary to JSON in Swift

Swift 3.0

With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.

let dic = ["2": "B", "1": "A", "3": "C"]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
    // here "decoded" is of type `Any`, decoded from JSON data

    // you can now cast it with the right type        
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch {
    print(error.localizedDescription)
}

Swift 2.x

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
    // here "decoded" is of type `AnyObject`, decoded from JSON data

    // you can now cast it with the right type 
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch let error as NSError {
    print(error)
}

Swift 1

var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
    if error != nil {
        println(error)
    } else {
        // here "jsonData" is the dictionary encoded in JSON data
    }
}

if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
    if error != nil {
        println(error)
    } else {
        // here "decoded" is the dictionary decoded from JSON data
    }
}

Request string without GET arguments

I know this is an old post but I am having the same problem and I solved it this way

$current_request = preg_replace("/\?.*$/","",$_SERVER["REQUEST_URI"]);

Or equivalently

$current_request = preg_replace("/\?.*/D","",$_SERVER["REQUEST_URI"]);

What's the best way to limit text length of EditText in Android

it simple way in xml:

android:maxLength="4"

if u require to set 4 character in xml edit-text so,use this

<EditText
    android:id="@+id/edtUserCode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLength="4"
    android:hint="Enter user code" />

Mapping over values in a python dictionary

To avoid doing indexing from inside lambda, like:

rval = dict(map(lambda kv : (kv[0], ' '.join(kv[1])), rval.iteritems()))

You can also do:

rval = dict(map(lambda(k,v) : (k, ' '.join(v)), rval.iteritems()))

Jquery : Refresh/Reload the page on clicking a button

You can also use window.location.href=window.location.href;

SVN Repository Search

A lot of SVN repos are "simply" HTTP sites, so you might consider looking at some off the shelf "web crawling" search app that you can point at the SVN root and it will give you basic functionality. Updating it will probably be a bit of a trick, perhaps some SVN check in hackery can tickle the index to discard or reindex changes as you go.

Just thinking out loud.

JFrame Maximize window

The way to set JFrame to full-screen, is to set MAXIMIZED_BOTH option which stands for MAXIMIZED_VERT | MAXIMIZED_HORIZ, which respectively set the frame to maximize vertically and horizontally

package Example;
import java.awt.GraphicsConfiguration;
import javax.swing.JFrame;
import javax.swing.JButton;

public class JFrameExample
{
    static JFrame frame;
    static GraphicsConfiguration gc;
    public static void main(String[] args)
    {
        frame = new JFrame(gc);
        frame.setTitle("Full Screen Example");
        frame.setExtendedState(MAXIMIZED_BOTH);

        JButton button = new JButton("exit");
        b.addActionListener(new ActionListener(){@Override
        public void actionPerformed(ActionEvent arg0){
            JFrameExample.frame.dispose();
            System.exit(0);
        }});

        frame.add(button);
        frame.setVisible(true);
    }
}

Highcharts - how to have a chart with dynamic height?

Just don't set the height property in HighCharts and it will handle it dynamically for you so long as you set a height on the chart's containing element. It can be a fixed number or a even a percent if position is absolute.

Highcharts docs:

By default the height is calculated from the offset height of the containing element

Example: http://jsfiddle.net/wkkAd/149/

#container {
    height:100%;
    width:100%;
    position:absolute;
}

Class Not Found Exception when running JUnit test

These steps worked for me.

  • Delete the content of local Maven repository.
  • run mvn clean install in the command line. (cd to the pom directory).
  • Build Project in Eclipse.

Git push rejected "non-fast-forward"

In Eclipse do the following:

GIT Repositories > Remotes > Origin > Right click and say fetch

GIT Repositories > Remote Tracking > Select your branch and say merge

Go to project, right click on your file and say Fetch from upstream.

How to install latest version of openssl Mac OS X El Capitan

To replace the old version with the new one, you need to change the link for it. Type that command to terminal.

brew link --force openssl

Check the version of openssl again. It should be changed.

Resolve absolute path from relative path and/or file name

I came across a similar need this morning: how to convert a relative path into an absolute path inside a Windows command script.

The following did the trick:

@echo off

set REL_PATH=..\..\
set ABS_PATH=

rem // Save current directory and change to target directory
pushd %REL_PATH%

rem // Save value of CD variable (current directory)
set ABS_PATH=%CD%

rem // Restore original directory
popd

echo Relative path: %REL_PATH%
echo Maps to path: %ABS_PATH%

Apply function to each column in a data frame observing each columns existing data type

df <- head(mtcars)
df$string <- c("a","b", "c", "d","e", "f"); df

my.min <- unlist(lapply(df, min))
my.max <- unlist(lapply(df, max))

How to set a default value with Html.TextBoxFor?

This should work for MVC3 & MVC4

 @Html.TextBoxFor(m => m.Age, new { @Value = "12" }) 

If you want it to be a hidden field

 @Html.TextBoxFor(m => m.Age, new { @Value = "12",@type="hidden" }) 

Event detect when css property changed using Jquery

Note

Mutation events have been deprecated since this post was written, and may not be supported by all browsers. Instead, use a mutation observer.

Yes you can. DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.

Try something along these lines:

document.documentElement.addEventListener('DOMAttrModified', function(e){
  if (e.attrName === 'style') {
    console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
  }
}, false);

document.documentElement.style.display = 'block';

You can also try utilizing IE's "propertychange" event as a replacement to DOMAttrModified. It should allow to detect style changes reliably.

Pass Multiple Parameters to jQuery ajax call

            data: JSON.stringify({ "objectnameOFcontroller": data, "Sel": $(th).val() }),

controller object name

How to create a zip archive of a directory in Python?

Use shutil, which is part of python standard library set. Using shutil is so simple(see code below):

  • 1st arg: Filename of resultant zip/tar file,
  • 2nd arg: zip/tar,
  • 3rd arg: dir_name

Code:

import shutil
shutil.make_archive('/home/user/Desktop/Filename','zip','/home/username/Desktop/Directory')

How to upload files to server using JSP/Servlet?

Here's an example using apache commons-fileupload:

// apache commons-fileupload to handle file upload
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(DataSources.TORRENTS_DIR()));
ServletFileUpload fileUpload = new ServletFileUpload(factory);

List<FileItem> items = fileUpload.parseRequest(req.raw());
FileItem item = items.stream()
  .filter(e ->
  "the_upload_name".equals(e.getFieldName()))
  .findFirst().get();
String fileName = item.getName();

item.write(new File(dir, fileName));
log.info(fileName);

Failed to decode downloaded font

In my case, this was caused by creating a SVN patch file that encompassed the addition of the font files. Like so:

  1. Add font files from local file system to subversioned trunk
  2. Trunk works as expected
  3. Create SVN patch of trunk changes, to include addition of font files
  4. Apply patch to another branch
  5. Font files are added to subversioned branch (and can be committed), but are corrupted, yielding error in OP.

The solution was to upload the font files directly into the branch from my local file system. I assume this happened because SVN patch files must convert everything to ASCII format, and don't necessarily retain binary for font files. But that's only a guess.

Adding attribute in jQuery

You can do this with jQuery's .attr function, which will set attributes. Removing them is done via the .removeAttr function.

//.attr()
$("element").attr("id", "newId");
$("element").attr("disabled", true);

//.removeAttr()
$("element").removeAttr("id");
$("element").removeAttr("disabled");

Enterprise app deployment doesn't work on iOS 7.1

Some nice guy handled the issue by using the Class 1 StartSSL certificate and shared Apache config that adds certificate support (will work with any certificate) and code for changing links in existing *.plist files automatically. Too long to copy, so here is the link: http://cases.azoft.com/how-to-fix-certificate-is-not-valid-error-on-ios-7/

Prevent form submission on Enter key press

Cross Browser Solution

Some older browsers implemented keydown events in a non-standard way.

KeyBoardEvent.key is the way it is supposed to be implemented in modern browsers.

which and keyCode are deprecated nowadays, but it doesn't hurt to check for these events nonetheless so that the code works for users that still use older browsers like IE.

The isKeyPressed function checks if the pressed key was enter and event.preventDefault() hinders the form from submitting.

  if (isKeyPressed(event, 'Enter', 13)) {
    event.preventDefault();
    console.log('enter was pressed and is prevented');
  }

Minimal working example

JS

function isKeyPressed(event, expectedKey, expectedCode) {
  const code = event.which || event.keyCode;

  if (expectedKey === event.key || code === expectedCode) {
    return true;
  }
  return false;
}

document.getElementById('myInput').addEventListener('keydown', function(event) {
  if (isKeyPressed(event, 'Enter', 13)) {
    event.preventDefault();
    console.log('enter was pressed and is prevented');
  }
});

HTML

<form>
  <input id="myInput">
</form>

https://jsfiddle.net/tobiobeck/z13dh5r2/

no match for ‘operator<<’ in ‘std::operator

You need to overload operator << for mystruct class

Something like :-

friend ostream& operator << (ostream& os, const mystruct& m)
{
    os << m.m_a <<" " << m.m_b << endl;
    return os ;
}

See here

SyntaxError: unexpected EOF while parsing

Maybe this is what you mean to do:

import random

x = 0
z = input('Please Enter an integer: ')
z = int(z) # you need to capture the result of the expressioin: int(z) and assign it backk to z

def main():
    for i in range(x,z):
        n1 = random.randrange(1,3)
        n2 = random.randrange(1,3)
        t1 = n1+n2
        print('{0}+{1}={2}'.format(n1,n2,t1))

main()
  1. do z = int(z)
  2. Add the missing closing parenthesis on the last line of code in your listing.
  3. And have a for-loop that will iterate from x to z-1

Here's a link on the range() function: http://docs.python.org/release/1.5.1p1/tut/range.html

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.

Open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox.

Stack Memory vs Heap Memory

In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.

The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)

The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.

Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.

Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

I wanted Git to use the updated certificate bundle without replacing the one my entire system uses. Here's how to have Git use a specific file in my home directory:

mkdir ~/certs
curl https://curl.haxx.se/ca/cacert.pem -o ~/certs/cacert.pem

Now update .gitconfig to use this for peer verification:

[http]
sslCAinfo = /home/radium/certs/cacert.pem

Note I'm using an absolute path. Git does no path expansion here, so you can't use ~ without an ugly kludge. Alternatively, you can skip the config file and set the path via the environment variable GIT_SSL_CAINFO instead.

To troubleshoot this, set GIT_CURL_VERBOSE=1. The path of the CA file Git is using will be shown on lines starting with "CAfile:" in the output.

Edited to change from http to https.

How to select top n rows from a datatable/dataview in ASP.NET

You could modify the query. If you are using SQL Server at the back, you can use Select top n query for such need. The current implements fetch the whole data from database. Selecting only the required number of rows will give you a performance boost as well.

How to import a bak file into SQL Server Express

Using management studio the procedure can be done as follows

  1. right click on the Databases container within object explorer
  2. from context menu select Restore database
  3. Specify To Database as either a new or existing database
  4. Specify Source for restore as from device
  5. Select Backup media as File
  6. Click the Add button and browse to the location of the BAK file

refer

You'll need to specify the WITH REPLACE option to overwrite the existing adventure_second database with a backup taken from a different database.

Click option menu and tick Overwrite the existing database(With replace)

Reference

Angular2 - Input Field To Accept Only Numbers

Just Create a directive and add below hostlistener:

@HostListener('input', ['$event'])
    onInput(event: Event) {
        this.elementRef.nativeElement.value = (<HTMLInputElement>event.currentTarget).value.replace(/[^0-9]/g, '');
    }

Replace invalid text with empty. All keys and key combinations will now work across all browsers till IE9.

How to return a struct from a function in C++?

studentType newStudent() // studentType doesn't exist here
{   
    struct studentType // it only exists within the function
    {
        string studentID;
        string firstName;
        string lastName;
        string subjectName;
        string courseGrade;

        int arrayMarks[4];

        double avgMarks;

    } newStudent;
...

Move it outside the function:

struct studentType
{
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;

    int arrayMarks[4];

    double avgMarks;

};

studentType newStudent()
{
    studentType newStudent
    ...
    return newStudent;
}

Select all child elements recursively in CSS

Use a white space to match all descendants of an element:

div.dropdown * {
    color: red;
}

x y matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.

The asterisk * matches any element.

Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors

How to move an element into another element?

I just used:

$('#source').prependTo('#destination');

Which I grabbed from here.

Merging two arrays in .NET

I think you can use Array.Copy for this. It takes a source index and destination index so you should be able to append the one array to the other. If you need to go more complex than just appending one to the other, this may not be the right tool for you.

How to get a jqGrid cell value when editing

In my case the contents of my cell is HTML as result of a formatter. I want the value inside anchor tag. By fetching the cell contents and then creating an element out of the html via jQuery I am able to then access the raw value by calling .text() on my newly created element.

var cellContents = grid.getCell(rowid, 'ColNameHere');
console.log($(cellContents)); 
//in my case logs <h3><a href="#">The Value I'm After</a></h3>

var cellRawValue = $(cellContents).text();
console.log(cellRawValue); //outputs "The Value I'm After!"

my answer is based on @LLQ answer, but since in my case my cellContents isn't an input I needed to use .text() instead of .val() to access the raw value so I thought I'd post this in case anyone else is looking for a way to access the raw value of a formatted jqGrid cell.

make bootstrap twitter dialog modal draggable

In my own case, i had to set backdrop and set the top and left properties before i could apply draggable function on the modal dialog. Maybe it might help someone ;)

if (!($('.modal.in').length)) {       
$('.modal-dialog').css({
     top: 0,
     left: 0
   });
}
$('#myModal').modal({
  backdrop: false,
   show: true
});

$('.modal-dialog').draggable({
  handle: ".modal-header"
});

How can I get the current class of a div with jQuery?

var classname=$('#div1').attr('class')

How to implement a queue using two stacks?

Below is the solution in javascript language using ES6 syntax.

Stack.js

//stack using array
class Stack {
  constructor() {
    this.data = [];
  }

  push(data) {
    this.data.push(data);
  }

  pop() {
    return this.data.pop();
  }

  peek() {
    return this.data[this.data.length - 1];
  }

  size(){
    return this.data.length;
  }
}

export { Stack };

QueueUsingTwoStacks.js

import { Stack } from "./Stack";

class QueueUsingTwoStacks {
  constructor() {
    this.stack1 = new Stack();
    this.stack2 = new Stack();
  }

  enqueue(data) {
    this.stack1.push(data);
  }

  dequeue() {
    //if both stacks are empty, return undefined
    if (this.stack1.size() === 0 && this.stack2.size() === 0)
      return undefined;

    //if stack2 is empty, pop all elements from stack1 to stack2 till stack1 is empty
    if (this.stack2.size() === 0) {
      while (this.stack1.size() !== 0) {
        this.stack2.push(this.stack1.pop());
      }
    }

    //pop and return the element from stack 2
    return this.stack2.pop();
  }
}

export { QueueUsingTwoStacks };

Below is the usage:

index.js

import { StackUsingTwoQueues } from './StackUsingTwoQueues';

let que = new QueueUsingTwoStacks();
que.enqueue("A");
que.enqueue("B");
que.enqueue("C");

console.log(que.dequeue());  //output: "A"

How to get the cell value by column name not by index in GridView in asp.net

A little bug with indexcolumn in alexander's answer: We need to take care of "not found" column:

int GetColumnIndexByName(GridViewRow row, string columnName)
{
    int columnIndex = 0;
    int foundIndex=-1;
    foreach (DataControlFieldCell cell in row.Cells)
    {
        if (cell.ContainingField is BoundField)
        {
            if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
            {
                foundIndex=columnIndex;
                break;
            }
        }
        columnIndex++; // keep adding 1 while we don't have the correct name
    }
    return foundIndex;
}

and

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int index = GetColumnIndexByName(e.Row, "myDataField");
        if( index>0)
        {
            string columnValue = e.Row.Cells[index].Text;
        }
    }
}

git am error: "patch does not apply"

git format-patch also has the -B flag.

The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).

This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.

An example:

git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch

When should I use UNSIGNED and SIGNED INT in MySQL?

I think, UNSIGNED would be the best option to store something like time_duration(Eg: resolved_call_time = resolved_time(DateTime)-creation_time(DateTime)) value in minutes or hours or seconds format which will definitely be a non-negative number

Call PHP function from Twig template

This worked for me (using Slim Twig-View):

$twig->getEnvironment()->addFilter(
   new \Twig_Filter('md5', function($arg){ return md5($arg); })
);

This creates a new filter named md5 which returns the MD5 checksum of the argument.

adding comment in .properties files

The property file task is for editing properties files. It contains all sorts of nice features that allow you to modify entries. For example:

<propertyfile file="build.properties">
    <entry key="build_number"
        type="int"
        operation="+"
        value="1"/>
</propertyfile>

I've incremented my build_number by one. I have no idea what the value was, but it's now one greater than what it was before.

  • Use the <echo> task to build a property file instead of <propertyfile>. You can easily layout the content and then use <propertyfile> to edit that content later on.

Example:

<echo file="build.properties">
# Default Configuration
source.dir=1
dir.publish=1
# Source Configuration
dir.publish.html=1
</echo>
  • Create separate properties files for each section. You're allowed a comment header for each type. Then, use to batch them together into one single file:

Example:

<propertyfile file="default.properties"
    comment="Default Configuration">
    <entry key="source.dir" value="1"/>
    <entry key="dir.publish" value="1"/>
<propertyfile>

<propertyfile file="source.properties"
    comment="Source Configuration">
    <entry key="dir.publish.html" value="1"/>
<propertyfile>
<concat destfile="build.properties">
    <fileset dir="${basedir}">
        <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</concat>

<delete>
    <fileset dir="${basedir}">
         <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</delete>      

PHP: How can I determine if a variable has a value that is between two distinct constant values?

You can do this:

if(in_array($value, range(1, 10)) || in_array($value, range(20, 40))) {
   # enter code here
}

How to use <md-icon> in Angular Material?

The simplest way today would be to simply request the Material Icons font from Google Fonts, for example in your HTML header tag:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

or in your stylesheet:

@import url(https://fonts.googleapis.com/icon?family=Material+Icons);

and then use as font icon with ligatures as explained in the md-icon directive. For example:

<md-icon aria-label="Menu" class="material-icons">menu</md-icon>

The complete list of icons/ligatures is at https://www.google.com/design/icons/

open() in Python does not create a file if it doesn't exist

For Python 3+, I will do:

import os

os.makedirs('path/to/the/directory', exist_ok=True)

with open('path/to/the/directory/filename', 'w') as f:
    f.write(...)

So, the problem is with open cannot create a file before the target directory exists. We need to create it and then w mode is enough in this case.

grep from tar.gz without extracting [faster one]

You can use the --to-command option to pipe files to an arbitrary script. Using this you can process the archive in a single pass (and without a temporary file). See also this question, and the manual. Armed with the above information, you could try something like:

$ tar xf file.tar.gz --to-command "awk '/bar/ { print ENVIRON[\"TAR_FILENAME\"]; exit }'"
bfe2/.bferc
bfe2/CHANGELOG
bfe2/README.bferc