Programs & Examples On #Portals bridge

How can I check if my Element ID has focus?

Compare document.activeElement with the element you want to check for focus. If they are the same, the element is focused; otherwise, it isn't.

// dummy element
var dummyEl = document.getElementById('myID');

// check for focus
var isFocused = (document.activeElement === dummyEl);

hasFocus is part of the document; there's no such method for DOM elements.

Also, document.getElementById doesn't use a # at the beginning of myID. Change this:

var dummyEl = document.getElementById('#myID');

to this:

var dummyEl = document.getElementById('myID');

If you'd like to use a CSS query instead you can use querySelector (and querySelectorAll).

Adding elements to a C# array

You can use this snippet:

static void Main(string[] args)
{



        Console.WriteLine("Enter number:");
        int fnum = 0;
        bool chek = Int32.TryParse(Console.ReadLine(),out fnum);            


        Console.WriteLine("Enter number:");
        int snum = 0;
        chek = Int32.TryParse(Console.ReadLine(),out snum);


        Console.WriteLine("Enter number:");
        int thnum = 0;
        chek = Int32.TryParse(Console.ReadLine(),out thnum);


        int[] arr = AddToArr(fnum,snum,thnum);

        IOrderedEnumerable<int> oarr = arr.OrderBy(delegate(int s)
        {  
            return s;
        });


        Console.WriteLine("Here your result:");


        oarr.ToList().FindAll(delegate(int num) {

            Console.WriteLine(num);

            return num > 0;

        });



}



public static int[] AddToArr(params int[] arr) {

    return arr;
}

I hope this will help to you, just change the type

Write to .txt file?

FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
    printf("Error opening file!\n");
    exit(1);
}

/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);

/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);

/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);

fclose(f);

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

How to count the number of files in a directory using Python

For all kind of files, subdirectories included:

import os

list = os.listdir(dir) # dir is your directory path
number_files = len(list)
print number_files

Only files (avoiding subdirectories):

import os

onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string
print len(onlyfiles)

What does %~dp0 mean, and how does it work?

Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.

Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0 will change both the drive and directory :)

Hope this helps someone.

Angular ng-if="" with multiple arguments

Just to clarify, be aware bracket placement is important!

These can be added to any HTML tags... span, div, table, p, tr, td etc.

AngularJS

ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

Angular2+

*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.

boolean check1 = Your conditional check here...
...

How to use radio on change event?

$(document).ready(function () {
    $('input:radio[name=bedStatus]:checked').change(function () {
        if ($("input:radio[name='bedStatus']:checked").val() == 'allot') {
            alert("Allot Thai Gayo Bhai");
        }
        if ($("input:radio[name='bedStatus']:checked").val() == 'transfer') {
            alert("Transfer Thai Gayo");
        }
    });
});

What is the difference between syntax and semantics in programming languages?

  • You need correct syntax to compile.
  • You need correct semantics to make it work.

Create view with primary key?

This worked for me..

select ROW_NUMBER() over (order by column_name_of your choice ) as pri_key, the other columns of the view

How to add items to array in nodejs

Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:

var array = [];
calendars.forEach(function(item) {
    array.push(item.id);
});

console.log(array);

You can also use the map() method to generate an Array filled with the results of calling the specified function on each element. Something like:

var array = calendars.map(function(item) {
    return item.id;
});

console.log(array);

And, since ECMAScript 2015 has been released, you may start seeing examples using let or const instead of var and the => syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):

let array = calendars.map(item => item.id);
console.log(array);

How to scroll the window using JQuery $.scrollTo() function

$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);

Android SQLite Example

Sqlite helper class helps us to manage database creation and version management. SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade() methods of SQLiteOpenHelper. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete() to create, read, update and delete rows of your table.

Example to create a MyEmployees table and to select and insert records:

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "DBName";

    private static final int DATABASE_VERSION = 2;

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table MyEmployees
                                 ( _id integer primary key,name text not null);";

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    // Method is called during an upgrade of the database,
    @Override
    public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
        Log.w(MyDatabaseHelper.class.getName(),
                         "Upgrading database from version " + oldVersion + " to "
                         + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS MyEmployees");
        onCreate(database);
    }
}

Now you can use this class as below,

public class MyDB{  

    private MyDatabaseHelper dbHelper;  

    private SQLiteDatabase database;  

    public final static String EMP_TABLE="MyEmployees"; // name of table 

    public final static String EMP_ID="_id"; // id value for employee
    public final static String EMP_NAME="name";  // name of employee

    /** 
     * 
     * @param context 
     */  
    public MyDB(Context context){  
        dbHelper = new MyDatabaseHelper(context);  
        database = dbHelper.getWritableDatabase();  
    }


    public long createRecords(String id, String name){  
        ContentValues values = new ContentValues();  
        values.put(EMP_ID, id);  
        values.put(EMP_NAME, name);  
        return database.insert(EMP_TABLE, null, values);  
    }    

    public Cursor selectRecords() {
        String[] cols = new String[] {EMP_ID, EMP_NAME};  
        Cursor mCursor = database.query(true, EMP_TABLE,cols,null  
            , null, null, null, null, null);  
        if (mCursor != null) {  
            mCursor.moveToFirst();  
        }  
        return mCursor; // iterate to get each value.
    }
}

Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.

Can you run GUI applications in a Docker container?

You can also use subuser: https://github.com/timthelion/subuser

This allows you to package many gui apps in docker. Firefox and emacs have been tested so far. With firefox, webGL doesn't work though. Chromium doesn't work at all.

EDIT: Sound works!

EDIT2: In the time since I first posted this, subuser has progressed greatly. I now have a website up subuser.org, and a new security model for connecting to X11 via XPRA bridging.

What is the difference between required and ng-required?

The HTML attribute required="required" is a statement telling the browser that this field is required in order for the form to be valid. (required="required" is the XHTML form, just using required is equivalent)

The Angular attribute ng-required="yourCondition" means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.

Also note that the HTML version is confusing, it is not possible to write something conditional like required="true" or required="false", only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required.

Adding additional data to select options using jQuery

I made two examples from what I think your question might be:

http://jsfiddle.net/grdn4/

Check this out for storing additional values. It uses data attributes to store the other value:

http://jsfiddle.net/27qJP/1/

SQL Server - In clause with a declared variable

Try this:

CREATE PROCEDURE MyProc @excludedlist integer_list_tbltype READONLY AS
  SELECT * FROM A WHERE ID NOT IN (@excludedlist)

And then call it like this:

DECLARE @ExcludedList integer_list_tbltype
INSERT @ExcludedList(n) VALUES(3, 4, 22)
exec MyProc @ExcludedList

Java Object Null Check for method

If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]); - to check if the parameter is null. To check if each element is not null just use

if(null != books[i]){/*do stuff*/}

Example:

public static double calculateInventoryTotal(Book[] books){
    Objects.requireNotNull(books, "Books must not be null");

    double total = 0;

    for (int i = 0; i < books.length; i++){
        if(null != book[i]){
            total += books[i].getPrice();
        }
    }

    return total;
}

What is a stack pointer used for in microprocessors?

The stack pointer stores the address of the most recent entry that was pushed onto the stack.

To push a value onto the stack, the stack pointer is incremented to point to the next physical memory address, and the new value is copied to that address in memory.

To pop a value from the stack, the value is copied from the address of the stack pointer, and the stack pointer is decremented, pointing it to the next available item in the stack.

The most typical use of a hardware stack is to store the return address of a subroutine call. When the subroutine is finished executing, the return address is popped off the top of the stack and placed in the Program Counter register, causing the processor to resume execution at the next instruction following the call to the subroutine.

http://en.wikipedia.org/wiki/Stack_%28data_structure%29#Hardware_stacks

What is the difference between ports 465 and 587?

Port 465: IANA has reassigned a new service to this port, and it should no longer be used for SMTP communications.

However, because it was once recognized by IANA as valid, there may be legacy systems that are only capable of using this connection method. Typically, you will use this port only if your application demands it. A quick Google search, and you'll find many consumer ISP articles that suggest port 465 as the recommended setup. Hopefully this ends soon! It is not RFC compliant.

Port 587: This is the default mail submission port. When a mail client or server is submitting an email to be routed by a proper mail server, it should always use this port.

Everyone should consider using this port as default, unless you're explicitly blocked by your upstream network or hosting provider. This port, coupled with TLS encryption, will ensure that email is submitted securely and following the guidelines set out by the IETF.

Port 25: This port continues to be used primarily for SMTP relaying. SMTP relaying is the transmittal of email from email server to email server.

In most cases, modern SMTP clients (Outlook, Mail, Thunderbird, etc) shouldn't use this port. It is traditionally blocked, by residential ISPs and Cloud Hosting Providers, to curb the amount of spam that is relayed from compromised computers or servers. Unless you're specifically managing a mail server, you should have no traffic traversing this port on your computer or server.

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

500 internal server error at GetResponse()

For me the error was misleading. I discovered the true error by testing the errant web service with SoapUI.

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

How do I get the path of a process in Unix / Linux

I use:

ps -ef | grep 786

Replace 786 with your PID or process name.

How do I convert from a string to an integer in Visual Basic?

Please try this, VB.NET 2010:

  1. Integer.TryParse(txtPrice.Text, decPrice)
  2. decPrice = Convert.ToInt32(txtPrice.Text)

From Mola Tshepo Kingsley (WWW.TUT.AC.ZA)

Multi-select dropdown list in ASP.NET

Here's a cool ASP.NET Web control called Multi-Select List Field at http://www.xnodesystems.com/. It's capable of:

(1) Multi-select; (2) Auto-complete; (3) Validation.

How to use absolute path in twig functions

For Symfony 2.7 and newer

See this answer here.

1st working option

{{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset('bundles/acmedemo/images/search.png') }}

2nd working option - preferred

Just made a quick test with a clean new Symfony copy. There is also another option which combines scheme and httpHost:

{{ app.request.getSchemeAndHttpHost() ~ asset('bundles/acmedemo/images/search.png') }}
{# outputs #}
{# http://localhost/Symfony/web/bundles/acmedemo/css/demo.css  #}

Push existing project into Github

Follow below gitbash commands to push the folder files on github repository :-
1.) $ git init
2.) $ git cd D:\FileFolderName
3.) $ git status
4.) If needed to switch the git branch, use this command : 
    $ git checkout -b DesiredBranch
5.) $ git add .
6.) $ git commit -m "added a new folder"
7.) $ git push -f https://github.com/username/MyTestApp.git TestBranch
    (i.e git push origin branch)

Detect IF hovering over element with jQuery

Couple updates to add after working on this subject for a while:

  1. all solutions with .is(":hover") break on jQuery 1.9.1
  2. The most likely reason to check if the mouse is still over an element is to attempt to prevent events firing over each other. For example, we were having issues with our mouseleave being triggered and completed before our mouseenter event even completed. Of course this was because of a quick mouse movement.

We used hoverIntent https://github.com/briancherne/jquery-hoverIntent to solve the issue for us. Essentially it triggers if the mouse movement is more deliberate. (one thing to note is that it will trigger on both mouse entering an element and leaving - if you only want to use one pass the constructor an empty function )

How can I add an image file into json object?

You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.

You must load the image and read the bytes from it. Then put these bytes into the JSON object.

vertical divider between two columns in bootstrap

To fix the ugly look of a divider being too short when the content of one column is taller, add borders to all columns. Give every other column a negative margin to compensate for position differences.

For example, my three column classes:

.border-right {
    border-right: 1px solid #ddd;
}
.borders {
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
    margin: -1px;
}
.border-left {
    border-left: 1px solid #ddd;
}

And the HTML:

<div class="col-sm-4 border-right">First</div>
<div class="col-sm-4 borders">Second</div>
<div class="col-sm-4 border-left">Third</div>

Make sure you use #ddd if you want the same color as Bootstrap's horizontal dividers.

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

IE8 support for CSS Media Query

IE didn't add media query support until IE9. So with IE8 you're out of luck.

Extracting date from a string in Python

For extracting the date from a string in Python; the best module available is the datefinder module.

You can use it in your Python project by following the easy steps given below.

Step 1: Install datefinder Package

pip install datefinder

Step 2: Use It In Your Project

import datefinder

input_string = "monkey 2010-07-10 love banana"
# a generator will be returned by the datefinder module. I'm typecasting it to a list. Please read the note of caution provided at the bottom.
matches = list(datefinder.find_dates(input_string))

if len(matches) > 0:
    # date returned will be a datetime.datetime object. here we are only using the first match.
    date = matches[0]
    print date
else:
    print 'No dates found'

note: if you are expecting a large number of matches; then typecasting to list won't be a recommended way as it will be having a big performance overhead.

Database corruption with MariaDB : Table doesn't exist in engine

Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.

UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE

click or change event on radio using jquery

You can specify the name attribute as below:

$( 'input[name="testGroup"]:radio' ).change(

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

This is very simple, you just need to add a background image to the select element and position it where you need to, but don't forget to add:

-webkit-appearance: none;
-moz-appearance: none;
appearance: none;

According to http://shouldiprefix.com/#appearance

Microsoft Edge and IE mobile support this property with the -webkit- prefix rather than -ms- for interop reasons.

I just made this fiddle http://jsfiddle.net/drjorgepolanco/uxxvayqe/

How do I find out what keystore my JVM is using?

Keystore Location

Each keytool command has a -keystore option for specifying the name and location of the persistent keystore file for the keystore managed by keytool. The keystore is by default stored in a file named .keystore in the user's home directory, as determined by the "user.home" system property. Given user name uName, the "user.home" property value defaults to

C:\Users\uName on Windows 7 systems
C:\Winnt\Profiles\uName on multi-user Windows NT systems
C:\Windows\Profiles\uName on multi-user Windows 95 systems
C:\Windows on single-user Windows 95 systems

Thus, if the user name is "cathy", "user.home" defaults to

C:\Users\cathy on Windows 7 systems
C:\Winnt\Profiles\cathy on multi-user Windows NT systems
C:\Windows\Profiles\cathy on multi-user Windows 95 systems

http://docs.oracle.com/javase/1.5/docs/tooldocs/windows/keytool.html

OperationalError: database is locked

As others have told, there is another process that is using the SQLite file and has not closed the connection. In case you are using Linux, you can see which processes are using the file (for example db.sqlite3) using the fuser command as follows:

$ sudo fuser -v db.sqlite3
                     USER        PID ACCESS COMMAND
/path/to/db.sqlite3:
                     user        955 F....  apache2

If you want to stop the processes to release the lock, use fuser -k which sends the KILL signal to all processes accessing the file:

sudo fuser -k db.sqlite3

Note that this is dangerous as it might stop the web server process in a production server.

Thanks to @cz-game for pointing out fuser!

How to get an Instagram Access Token

go to manage clinet page in :

http://www.instagram.com/developer/

set a redirect url

then :

use this code to get access token :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>tst</title>
<script src="../jq.js"></script>
<script type="text/javascript">
       $.ajax({
            type: 'GET',
            url: 'https://api.instagram.com/oauth/authorize/?client_id=CLIENT-??ID&redirect_uri=REDI?RECT-URI&response_ty?pe=code'
            dataType: 'jsonp'}).done(function(response){
                var access = window.location.hash.substring(14);
                //you have access token in access var   
            });
</script>
</head>
<body>  
</body>
</html>

Where do I find the line number in the Xcode editor?

For Xcode 4 and higher, open the preferences (command+,) and check "Show: Line numbers" in the "Text Editing" section.

Xcode 9 enter image description here

Xcode 8 and below Xcode Text Editing Preferences screen capture with Text Editing and Line Numbers highlighted

Convert array values from string to int?

PHP 7.4 style:

$ids = array_map(fn(string $x): int => (int) $x, explode(',', $string));

XML element with attribute and content using JAXB

Annotate type and gender properties with @XmlAttribute and the description property with @XmlValue:

package org.example.sport;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Sport {

    @XmlAttribute
    protected String type;

    @XmlAttribute
    protected String gender;

    @XmlValue;
    protected String description;

}

For More Information

Python method for reading keypress?

Figured it out by testing all the stuff by myself. Couldn't find any topics about it tho, so I'll just leave the solution here. This might not be the only or even the best solution, but it works for my purposes (within getch's limits) and is better than nothing.

Note: proper keyDown() which would recognize all the keys and actual key presses, is still valued.

Solution: using ord()-function to first turn the getch() into an integer (I guess they're virtual key codes, but not too sure) works fine, and then comparing the result to the actual number representing the wanted key. Also, if I needed to, I could add an extra chr() around the number returned so that it would convert it to a character. However, I'm using mostly down arrow, esc, etc. so converting those to a character would be stupid. Here's the final code:

from msvcrt import getch
while True:
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        select()
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            moveDown()
        elif key == 72: #Up arrow
            moveUp()

Also if someone else needs to, you can easily find out the keycodes from google, or by using python and just pressing the key:

from msvcrt import getch
while True:
    print(ord(getch()))

Can Linux apps be run in Android?

Short answer, no. Long answer, you can run Linux application if you install some software.

To avoid rooting your device, you can try the GnuRoot and XSDL combo to get a minimal chrooted environment, (Actually, it use proot to enable a rootless chrooted jail), or get the Debian Noroot application, which combine the former two application in a single virtual machine environment. Both can be fetch from Google Play.

However, there is a few drawbacks: first, the X11 Server bundled by XSDL and DNR is a compatibility layer wrapped around a Android port of SDL library and SurfaceFlinger. This means, hardware accelerated OpenGL graphics are not avaliable, and even the sound support requires some hacks. So, the author choose a simple Desktop Environment: XFCE4 suitable to low memmory and no 3D support. The second problem is the incompatibility from the DNR Virtual Machine of direct hardware acess, since it requires real root privileges. So you can't burn DVD, print using USB cables,... even the author's projects may promise a workaround in a future. Finally, this solution enables to install user-space programs like LibreOffice, Gimp, Samba,... not kernel-space modules.

Even with this limitations, the DNR is a very powerfull program.

How to get all selected values from <select multiple=multiple>?

If you have multiple select boxes with multiple='multiple' and you want to select all selected options from every dropdown then use this HTML:

<select id='Alphabets'>
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
</select>

<select id='Alphabets' multiple='multiple'>
    <option value="4">D</option>
    <option value="5">E</option>
    <option value="6">F</option>
</select>
<select id='Alphabets'>
    <option value="7">G</option>
    <option value="8">H</option>
    <option value="9">I</option>
</select>
<select id='Alphabets' multiple='multiple'>
    <option value="10">J</option>
    <option value="11">K</option>
    <option value="12">L</option>
</select>

JavaScript for above UI:

function show_Alphebets()
{
        var tag =document.querySelectorAll("select");        
        var values="";
        for(var i=1; i<4; i++) {
            if(tag[i].options.length>0)
            for (var option of tag[i].selectedOptions) {                  
                  values+= i+"(multiple)="+option.value+",";
            }
            else values+= i+"="+tag[i].value+",";
        }
        alert(values);
}

Get Value of a Edit Text field

Try this code

final EditText editText = findViewById(R.id.name); // your edittext id in xml
Button submit = findViewById(R.id.submit_button); // your button id in xml
submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) 
    {
        String string = editText.getText().toString();
        Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
    }
});

How to remove Firefox's dotted outline on BUTTONS as well as links?

It looks like the only way to achieve this is by setting

browser.display.focus_ring_width = 0

in about:config on a per browser basis.

Check if a string contains another string

You wouldn't really want to do this given the existing Instr/InstrRev functions but there are times when it is handy to use EVALUATE to return the result of Excel worksheet functions within VBA

Option Explicit

Public Sub test()

    Debug.Print ContainsSubString("bc", "abc,d")

End Sub
Public Function ContainsSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'substring = string to test for; testString = string to search
    ContainsSubString = Evaluate("=ISNUMBER(FIND(" & Chr$(34) & substring & Chr$(34) & ", " & Chr$(34) & testString & Chr$(34) & "))")

End Function

How to round the double value to 2 decimal points?

you can also use this code

public static double roundToDecimals(double d, int c)  
{   
   int temp = (int)(d * Math.pow(10 , c));  
   return ((double)temp)/Math.pow(10 , c);  
}

It gives you control of how many numbers after the point are needed.

d = number to round;   
c = number of decimal places  

think it will be helpful

How do I link to part of a page? (hash?)

Here is how:

<a href="#go_middle">Go Middle</a>

<div id="go_middle">Hello There</div>

Row count with PDO

As it often happens, this question is confusing as hell. People are coming here having two different tasks in mind:

  1. They need to know how many rows in the table
  2. They need to know whether a query returned any rows

That's two absolutely different tasks that have nothing in common and cannot be solved by the same function. Ironically, for neither of them the actual PDOStatement::rowCount() function has to be used.

Let's see why

Counting rows in the table

Before using PDO I just simply used mysql_num_rows().

Means you already did it wrong. Using mysql_num_rows() or rowCount() to count the number of rows in the table is a real disaster in terms of consuming the server resources. A database has to read all the rows from the disk, consume the memory on the database server, then send all this heap of data to PHP, consuming PHP process' memory as well, burdening your server with absolute no reason.
Besides, selecting rows only to count them simply makes no sense. A count(*) query has to be run instead. The database will count the records out of the index, without reading the actual rows and then only one row returned.

For this purpose the code suggested in the accepted answer is fair, save for the fact it won't be an "extra" query but the only query to run.

Counting the number rows returned.

The second use case is not as disastrous as rather pointless: in case you need to know whether your query returned any data, you always have the data itself!

Say, if you are selecting only one row. All right, you can use the fetched row as a flag:

$stmt->execute();
$row = $stmt->fetch();
if (!$row) { // here! as simple as that
    echo 'No data found';
}

In case you need to get many rows, then you can use fetchAll().

fetchAll() is something I won't want as I may sometimes be dealing with large datasets

Yes of course, for the first use case it would be twice as bad. But as we learned already, just don't select the rows only to count them, neither with rowCount() nor fetchAll().

But in case you are going to actually use the rows selected, there is nothing wrong in using fetchAll(). Remember that in a web application you should never select a huge amount of rows. Only rows that will be actually used on a web page should be selected, hence you've got to use LIMIT, WHERE or a similar clause in your SQL. And for such a moderate amount of data it's all right to use fetchAll(). And again, just use this function's result in the condition:

$stmt->execute();
$data = $stmt->fetchAll();
if (!$data) { // again, no rowCount() is needed!
    echo 'No data found';
}

And of course it will be absolute madness to run an extra query only to tell whether your other query returned any rows, as it suggested in the two top answers.

Counting the number of rows in a large resultset

In such a rare case when you need to select a real huge amount of rows (in a console application for example), you have to use an unbuffered query, in order to reduce the amount of memory used. But this is the actual case when rowCount() won't be available, thus there is no use for this function as well.

Hence, that's the only use case when you may possibly need to run an extra query, in case you'd need to know a close estimate for the number of rows selected.

Java Error: "Your security settings have blocked a local application from running"

Java applets do create a security risk, hence are disabled in most modern browsers. You have to lower the security to run it. There is a guide by Oracle for that.

How do I set a ViewModel on a window in XAML using DataContext property?

Try this instead.

<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:VM="clr-namespace:BuildAssistantUI.ViewModels">
    <Window.DataContext>
        <VM:MainViewModel />
    </Window.DataContext>
</Window>

How do I clone a single branch in Git?

There are ample answers here which mention:

# (We'll refer to this as "the 1st command" below.)
git clone -b branch_name --single-branch \
https://github.com/some_project/some_project.git

...or some version of that, and a few which mention just:

# (We'll refer to this as "the 2nd command" below.)
git clone -b branch_name https://github.com/some_project/some_project.git

...withOUT the --single-branch part.

But, I'd like to expound upon these two things a bit and show a more familiar set of equivalent commands so we can see what is happening with each under-the-hood.

Let's assume that you have a remote repo on GitHub at https://github.com/micronucleus/micronucleus.git, with remote branches master and version_2.5 (this is a real example you can actually run right now).

Breakdown of the 2nd command from above:

The 2nd command (git clone -b version_2.5 https://github.com/micronucleus/micronucleus.git) clones ALL REMOTE BRANCHES to your local PC, but then checks out the version_2.5 branch instead of the master branch. That one command is the equivalent of doing this:

git clone https://github.com/micronucleus/micronucleus.git
cd micronucleus  # cd into the repo you just cloned
git checkout version_2.5
# To be pedantic, also delete the local `master` branch since
# technically it won't exist yet since you haven't yet checked
# it out with `git checkout master`, which would create it from
# your locally-stored remote-tracking branch, `origin/master`
git branch -d master

The -b version_2.5 part automatically checked out the version_2.5 branch for us instead of master.

git branch -a shows us that ALL branches, however, were cloned to our local PC. Here you can see our local branch version_2.5, which we are on, plus the locally-stored remote-tracking branches origin/HEAD (which points to origin/master), plus origin/master, and origin/version_2.5:

$ git branch -a
* version_2.5
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
  remotes/origin/version_2.5

We can also look at what our fetch references are. You can either open up the .git/config file to see them directly, or just run git config remote.origin.fetch:

$ git config remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*

You can see above that our git fetch command (which is also triggered by git pull since that is equivalent to git fetch && git merge) is configured to fetch ALL heads for ALL branches in the origin remote. I'm not an expert on this part, but I believe that's what +refs/heads/*:refs/remotes/origin/* means.

Breakdown of the 1st command from above:

The 1st command (git clone -b version_2.5 --single-branch https://github.com/micronucleus/micronucleus.git) clones ONLY the version_2.5 branch to your local PC, and it also checks it out. That one command is the equivalent of doing this (in the end result at least, except that it also downloads much less data in the beginning since it only clones ONE branch NOT all of them):

git clone https://github.com/micronucleus/micronucleus.git
cd micronucleus  # cd into the repo you just cloned
git checkout version_2.5

# Delete ALL other branches, including remote-tracking ones, which are not the 
# `version_2.5` branch:
# One local branch
git branch -d master
# ALL other locally-stored remote-tracking branches
git branch -dr origin/HEAD 
git branch -dr origin/master

# Fix your `.git/config` file so that `git fetch` does the right thing, fetching
# ONLY the `version_2.5` branch head from the `origin/version_2.5` remote branch:
git config remote.origin.fetch \
"+refs/heads/version_2.5:refs/remotes/origin/version_2.5"

The -b version_2.5 part caused the version_2.5 branch to be checked out instead of the master branch by default (as previously explained above), and the --single-branch part caused:

  1. NONE of the other branches to be cloned to our PC, and
  2. git fetch to be configured such that NONE of the other branches will ever be fetched when we call git fetch or git pull!

This command truly cloned and will fetch only the one branch we wanted, and that's it!

git branch -a shows us that ONLY the version_2.5 branch was cloned and checked out. Here we see by the * which branch is checked-out, and we see also that we have a locally-stored remote-tracking branch for origin/version_2.5:

$ git branch -a
* version_2.5
  remotes/origin/version_2.5

We can also look at what our fetch references are. You can either open up the .git/config file to see them directly, or just run git config remote.origin.fetch:

$ git config remote.origin.fetch
+refs/heads/version_2.5:refs/remotes/origin/version_2.5

You can see above that our git fetch command will only fetch the version_2.5 branch head from the origin/version_2.5 remote branch. That's it! Beware that no other remote branches will ever be fetched.

Summary:

So, now you see that using -b branch_name basically just ensures the branch_name branch is checked-out after the clone, but still clones ALL remote branches, whereas adding also --single-branch ensures that ONLY branch_name is cloned, fetched, pulled, and tracked. No other remote branches will be cloned to your PC whatsoever.

Personally, I prefer the -b branch_name option alone, because I want all branches cloned to my local PC. The one exception might be on a huge, shared mono-repo which has dozens, or even hundreds or thousands of remote branches. In that case, just use -b branch_name --single-branch to clone just the one main branch you care about and be done. Better to download 50 GiB of data for the master branch in a huge mono-repo, for instance, than to download 200 GiB of data so you can have 2000 of your peers' branches they are working on too!

References:

  1. Clone only one branch
  2. How do you stop tracking a remote branch in Git?

Convert PEM to PPK file format

I had the same issue with PuttyGen not wanting to import an openSSH private key. I tried everything and what I found out was the old version of PuttyGen did not support importing OpenSSH. Once I downloaded the latest Putty, puttygen then allowed it to import the openssh private key just fine. I now have a hole in the side of my desk for pounding my head against it for the past hour.

Run jar file in command prompt

java [any other JVM options you need to give it] -jar foo.jar

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

if anyone is getting error like SEVERE: Error filterStart Apr 29, 2013 4:49:20 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Context [/TraceMW] startup failed due to previous errors

then please check whether your tomcat/lib directory contains cors-filter-1.5.jar or not. if you dot have u will get above error and ur application will not be available.

So, i just managed to copy the jar file from other tomcat folder and i didnt get the above mentioned error later.

date format yyyy-MM-ddTHH:mm:ssZ

Using UTC

ISO 8601 (MSDN datetime formats)

Console.WriteLine(DateTime.UtcNow.ToString("s") + "Z");

2009-11-13T10:39:35Z

The Z is there because

If the time is in UTC, add a 'Z' directly after the time without a space. 'Z' is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".

If you want to include an offset

int hours = TimeZoneInfo.Local.BaseUtcOffset.Hours;
string offset = string.Format("{0}{1}",((hours >0)? "+" :""),hours.ToString("00"));
string isoformat = DateTime.Now.ToString("s") + offset;
Console.WriteLine(isoformat);

Two things to note: + or - is needed after the time but obviously + doesn't show on positive numbers. According to wikipedia the offset can be in +hh format or +hh:mm. I've kept to just hours.

As far as I know, RFC1123 (HTTP date, the "u" formatter) isn't meant to give time zone offsets. All times are intended to be GMT/UTC.

How can I make directory writable?

chmod 777 <directory>

this not change all ,just one file

chmod -R a+w <directory>

this ok

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

There is also someone who managed to modify CR for VS.NET 2010 to install on 2012, using MS ORCA in this thread: http://scn.sap.com/thread/3235515 . I couldn't get it to work myself, though.

Initialize a string in C to empty string

calloc allocates the requested memory and returns a pointer to it. It also sets allocated memory to zero.

In case you are planning to use your string as empty string all the time:

char *string = NULL;
string = (char*)calloc(1, sizeof(char));

In case you are planning to store some value in your string later:

char *string = NULL;
int numberOfChars = 50; // you can use as many as you need
string = (char*)calloc(numberOfChars + 1, sizeof(char));

What does the CSS rule "clear: both" do?

CSS float and clear

Sample Fiddle

Just try to remove clear:both property from the div with class sample and see how it follows floating divs.

Make HTML5 video poster be same size as video itself

Or you can use simply preload="none" attribute to make VIDEO background visible. And you can use background-size: cover; here.

 video {
   background: transparent url('video-image.jpg') 50% 50% / cover no-repeat ;
 }

 <video preload="none" controls>
   <source src="movie.mp4" type="video/mp4">
   <source src="movie.ogg" type="video/ogg">
 </video>

Git SSH error: "Connect to host: Bad file number"

Creating the config file to use port 443 didn't work for me. Finally I tried to turn off my wifi connection, turn it on again and the problem disappeared. Weird. Silly solution but it may help someone :)

Bind failed: Address already in use

Address already in use means that the port you are trying to allocate for your current execution is already occupied/allocated to some other process.

If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)

So if you encounter this error, just see which application/process is using the port.

In linux try using netstat -tulpn. This command will list down a process list with all running processes.

Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.

Anyway you can stop the process which uses your port and let your application take it.

If you are in linux environment try,

  • Use netstat -tulpn to display the processes
  • kill <pid> This will terminate the process

If you are using windows,

  • Use netstat -a -o -n to check for the port usages
  • Use taskkill /F /PID <pid> to kill that process

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

java.io.StreamCorruptedException: invalid stream header: 7371007E

when I send only one object from the client to server all works well.

when I attempt to send several objects one after another on the same stream I get StreamCorruptedException.

Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.

Blue and Purple Default links, how to remove?

REMOVE DEFAULT LINK SOLVED that :visited thing is css.... you just go to your HTML and add a simple

< a href="" style="text-decoration: none" > < /a>

... thats the way html pages used to be

@selector() in Swift?

It may be useful to note where you setup the control that triggers the action matters.

For example, I have found that when setting up a UIBarButtonItem, I had to create the button within viewDidLoad or else I would get an unrecognized selector exception.

override func viewDidLoad() {
    super.viewDidLoad() 

    // add button
    let addButton = UIBarButtonItem(image: UIImage(named: "746-plus-circle.png"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("addAction:"))
    self.navigationItem.rightBarButtonItem = addButton
}

func addAction(send: AnyObject?) {     
    NSLog("addAction")
}

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

i was trying the same, so i downloaded the .7zip version of XAMPP with php 5.6.33 from https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/5.6.33/

then followed the steps below: 1. rename c:\xampp\php to c:\xampp\php7 2. raname C:\xampp\apache\conf\extra\httpd-xampp.conf to httpd-xampp7.OLD 3. copy php folder from XAMPP_5.6 7zip archive to c:\xampp\ 4. copy file httpd-xampp.conf from XAMPP_5.6 7zip archive to C:\xampp\apache\conf\extra\

open xampp control panel and start Apache and then visit ( i am using port 82 instead of default 80) http://localhost and then click PHPInfo to see if it is working as expected.

Opening localhost shows dashboard

Opening phpinfo shows version 5.6

Picasso v/s Imageloader v/s Fresco vs Glide

I want to share with you a benchmark I have done among Picasso, Universal Image Loader and Glide: https://bit.ly/1kQs3QN

Fresco was out of the benchmark because for the project I was running the test, we didn't want to refactor our layouts (because of the Drawee view).

What I recommend is Universal Image Loader because of its customization, memory consumption and balance between size and methods.

If you have a small project, I would go for Glide (or give Fresco a try).

Using PHP with Socket.io

If you want to use socket.io together with php this may be your answer!

project website:

elephant.io

they are also on github:

https://github.com/wisembly/elephant.io

Elephant.io provides a socket.io client fully written in PHP that should be usable everywhere in your project.

It is a light and easy to use library that aims to bring some real-time functionality to a PHP application through socket.io and websockets for actions that could not be done in full javascript.

example from the project website (communicate with websocket server through php)

php server

use ElephantIO\Client as Elephant;

$elephant = new Elephant('http://localhost:8000', 'socket.io', 1, false, true, true);

$elephant->init();
$elephant->send(
    ElephantIOClient::TYPE_EVENT,
    null,
    null,
    json_encode(array('name' => 'foo', 'args' => 'bar'))
);
$elephant->close();

echo 'tryin to send `bar` to the event `foo`';

socket io server

var io = require('socket.io').listen(8000);

io.sockets.on('connection', function (socket) {
  console.log('user connected!');

  socket.on('foo', function (data) {
    console.log('here we are in action event and data is: ' + data);
  });
});

Display all dataframe columns in a Jupyter Python Notebook

If you want to show all the rows set like bellow

pd.options.display.max_rows = None

If you want to show all columns set like bellow

pd.options.display.max_columns = None

Warning: A non-numeric value encountered

In my case it was because of me used + as in other language but in PHP strings concatenation operator is ..

What is the difference between XML and XSD?

XML has a much wider application than f.ex. HTML. It doesn't have an intrinsic, or default "application". So, while you might not really care that web pages are also governed by what's allowed, from the author's side, you'll probably want to precisely define what an XML document may and may not contain.

It's like designing a database.

The thing about XML technologies is that they are textual in nature. With XSD, it means you have a data structure definition framework that can be "plugged in" to text processing tools like PHP. So not only can you manipulate the data itself, but also very easily change and document the structure, and even auto-generate front-ends.

Viewed like this, XSD is the "glue" or "middleware" between data (XML) and data-processing tools.

List files ONLY in the current directory

You can use os.listdir for this purpose. If you only want files and not directories, you can filter the results using os.path.isfile.

example:

files = os.listdir(os.curdir)  #files and directories

or

files = filter(os.path.isfile, os.listdir( os.curdir ) )  # files only
files = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ] #list comprehension version.

Create a new file in git bash

If you are using the Git Bash shell, you can use the following trick:

> webpage.html

This is actually the same as:

echo "" > webpage.html

Then, you can use git add webpage.html to stage the file.

Is it possible to move/rename files in Git and maintain their history?

git log --follow [file]

will show you the history through renames.

How to define hash tables in Bash?

Just use the file system

The file system is a tree structure that can be used as a hash map. Your hash table will be a temporary directory, your keys will be filenames, and your values will be file contents. The advantage is that it can handle huge hashmaps, and doesn't require a specific shell.

Hashtable creation

hashtable=$(mktemp -d)

Add an element

echo $value > $hashtable/$key

Read an element

value=$(< $hashtable/$key)

Performance

Of course, its slow, but not that slow. I tested it on my machine, with an SSD and btrfs, and it does around 3000 element read/write per second.

Verifying a specific parameter with Moq

I believe that the problem in the fact that Moq will check for equality. And, since XmlElement does not override Equals, it's implementation will check for reference equality.

Can't you use a custom object, so you can override equals?

Attach a file from MemoryStream to a MailMessage in C#

A bit of a late entry - but hopefully still useful to someone out there:-

Here's a simplified snippet for sending an in-memory string as an email attachment (a CSV file in this particular case).

using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))    // using UTF-8 encoding by default
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("[email protected]", "[email protected]", "Just testing", "See attachment..."))
{
    writer.WriteLine("Comma,Seperated,Values,...");
    writer.Flush();
    stream.Position = 0;     // read from the start of what was written

    message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));

    mailClient.Send(message);
}

The StreamWriter and underlying stream should not be disposed until after the message has been sent (to avoid ObjectDisposedException: Cannot access a closed Stream).

How to shutdown my Jenkins safely?

The full list of commands is available at http://your-jenkins/cli

The command for a clean shutdown is http://your-jenkins/safe-shutdown

You may also want to use http://your-jenkins/safe-restart

Setting a minimum/maximum character count for any character using a regular expression

It's usually the metacharacter . when not inside a character class.

So use ^.{1,35}$. However, dot does not include newlines unless the dot-all modifier is applied against it.

You can use ^[\S\s]{1,35}$ without any modifiers, and this includes newlines as well.

How to parse a String containing XML in Java and retrieve the value of the root node?

There is doing XML reading right, or doing the dodgy just to get by. Doing it right would be using proper document parsing.

Or... dodgy would be using custom text parsing with either wisuzu's response or using regular expressions with matchers.

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

  • The NVARCHAR2 stores variable-length character data. When you create a table with the NVARCHAR2 column, the maximum size is always in character length semantics, which is also the default and only length semantics for the NVARCHAR2 data type.

    The NVARCHAR2data type uses AL16UTF16character set which encodes Unicode data in the UTF-16 encoding. The AL16UTF16 use 2 bytes to store a character. In addition, the maximum byte length of an NVARCHAR2 depends on the configured national character set.

  • VARCHAR2 The maximum size of VARCHAR2 can be in either bytes or characters. Its column only can store characters in the default character set while the NVARCHAR2 can store virtually any characters. A single character may require up to 4 bytes.

By defining the field as:

  • VARCHAR2(10 CHAR) you tell Oracle it can use enough space to store 10 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
  • NVARCHAR2(10) you tell Oracle it can store 10 characters with 2 bytes per character

In Summary:

  • VARCHAR2(10 CHAR) can store maximum of 10 characters and maximum of 40 bytes (depends on the configured national character set).

  • NVARCHAR2(10) can store maximum of 10 characters and maximum of 20 bytes (depends on the configured national character set).

Note: Character set can be UTF-8, UTF-16,....

Please have a look at this tutorial for more detail.

Have a good day!

How to write UTF-8 in a CSV file

A very simple hack is to use the json import instead of csv. For example instead of csv.writer just do the following:

    fd = codecs.open(tempfilename, 'wb', 'utf-8')  
    for c in whatever :
        fd.write( json.dumps(c) [1:-1] )   # json dumps writes ["a",..]
        fd.write('\n')
    fd.close()

Basically, given the list of fields in correct order, the json formatted string is identical to a csv line except for [ and ] at the start and end respectively. And json seems to be robust to utf-8 in python 2.*

Check if certain value is contained in a dataframe column in pandas

You can simply use this:

'07311954' in df.date.values which returns True or False


Here is the further explanation:

In pandas, using in check directly with DataFrame and Series (e.g. val in df or val in series ) will check whether the val is contained in the Index.

BUT you can still use in check for their values too (instead of Index)! Just using val in df.col_name.values or val in series.values. In this way, you are actually checking the val with a Numpy array.

And .isin(vals) is the other way around, it checks whether the DataFrame/Series values are in the vals. Here vals must be set or list-like. So this is not the natural way to go for the question.

"Line contains NULL byte" in CSV reader (Python)

This is long settled, but I ran across this answer because I was experiencing an unexpected error while reading a CSV to process as training data in Keras and TensorFlow.

In my case, the issue was much simpler, and is worth being conscious of. The data being produced into the CSV wasn't consistent, resulting in some columns being completely missing, which seems to end up throwing this error as well.

The lesson: If you're seeing this error, verify that your data looks the way that you think it does!

How to convert Excel values into buckets?

Here is a solution which:

  • Is self contained
  • Does not require VBA
  • Is not limited in the same way as IF regarding bucket maximums
  • Does not require precise values as LOOKUP does

 

=INDEX({"Small","Medium","Large"},LARGE(IF([INPUT_VALUE]>{0,11,21},{1,2,3}),1))

 

Replace [INPUT_VALUE] with the appropriate cell reference and make sure to press Ctrl+Shift+Enter as this is an array formula.

Each of the array constants can be expanded to be arbitrarily long; as long as the formula does not exceed Excel's maximum of 8,192 characters. The first constant should contain the return values, the second should contain ordered thresholds,and the third should simply be ascending integers.

Cannot open output file, permission denied

Try restarting your IDE. It worked for me. Although I tried to end the process in the task manager, the process never got killed.

PowerShell Script to Find and Replace for all Files with a Specific Extension

I have written a little helper function to replace text in a file:

function Replace-TextInFile
{
    Param(
        [string]$FilePath,
        [string]$Pattern,
        [string]$Replacement
    )

    [System.IO.File]::WriteAllText(
        $FilePath,
        ([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
    )
}

Example:

Get-ChildItem . *.config -rec | ForEach-Object { 
    Replace-TextInFile -FilePath $_ -Pattern 'old' -Replacement 'new' 
}

expected assignment or function call: no-unused-expressions ReactJS

Instead of

 return 
 (
  <div>
    <h1>The Score is {this.state.speed};</h1>
  </div>
 )

Use Below Code

 return(
   <div>
     <h1>The Score is {this.state.speed};</h1>
   </div>
  )

Basically use brace "(" in the same line of return like "return(". It will fix this issue. Thanks.

Display/Print one column from a DataFrame of Series in Pandas

By using to_string

print(df.Name.to_string(index=False))


 Adam
  Bob
Cathy

How do I find duplicates across multiple columns?

Duplicated id for pairs name and city:

select s.id, t.* 
from [stuff] s
join (
    select name, city, count(*) as qty
    from [stuff]
    group by name, city
    having count(*) > 1
) t on s.name = t.name and s.city = t.city

Firebase FCM notifications click_action payload

If your app is in background, Firebase will not trigger onMessageReceived(). Why.....? I have no idea. In this situation, I do not see any point in implementing FirebaseMessagingService.

According to docs, if you want to process background message arrival, you have to send 'click_action' with your message. But it is not possible if you send message from Firebase console, only via Firebase API. It means you will have to build your own "console" in order to enable marketing people to use it. So, this makes Firebase console also quite useless!

There is really good, promising, idea behind this new tool, but executed badly.

I suppose we will have to wait for new versions and improvements/fixes!

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

Can we pass model as a parameter in RedirectToAction?

Yes you can pass the model that you have shown using

return RedirectToAction("GetStudent", "Student", student1 );

assuming student1 is an instance of Student

which will generate the following url (assuming your using the default routes and the value of student1 are ID=4 and Name="Amit")

.../Student/GetStudent/4?Name=Amit

Internally the RedirectToAction() method builds a RouteValueDictionary by using the .ToString() value of each property in the model. However, binding will only work if all the properties in the model are simple properties and it fails if any properties are complex objects or collections because the method does not use recursion. If for example, Student contained a property List<string> Subjects, then that property would result in a query string value of

....&Subjects=System.Collections.Generic.List'1[System.String]

and binding would fail and that property would be null

How to change the height of a div dynamically based on another div using css?

I don't believe you can accomplish that with css. Originally javascript was designed for this. Try this:

<div class="div1" id="div1">
  <div class="div2">
    Div2 starts <br /><br /><br /><br /><br /><br /><br />
    Div2 ends
  </div>
  <div class="div3" id="div3">
    Div3
  </div>
</div>

and javascript function:

function adjustHeight() {
    document.getElementById('div3').style.height = document.defaultView.getComputedStyle(document.getElementById('div1'), "").getPropertyValue("height");
}

call the javascript after the div1 (or whole page) is loaded.

You can also replace document.getElementById('div3').style.height with code manipulating class div3 since my code only add / change style attribute of an element.

Hope this helps.

C++ Convert string (or char*) to wstring (or wchar_t*)

From char* to wstring:

char* str = "hello worlddd";
wstring wstr (str, str+strlen(str));

From string to wstring:

string str = "hello worlddd";
wstring wstr (str.begin(), str.end());

Note this only works well if the string being converted contains only ASCII characters.

Is there a program to decompile Delphi?

You can use IDR it is a great program to decompile Delphi, it is updated to the current Delphi versions and it has a lot of features.

Python convert csv to xlsx

With my library pyexcel,

 $ pip install pyexcel pyexcel-xlsx

you can do it in one command line:

from pyexcel.cookbook import merge_all_to_a_book
# import pyexcel.ext.xlsx # no longer required if you use pyexcel >= 0.2.2 
import glob


merge_all_to_a_book(glob.glob("your_csv_directory/*.csv"), "output.xlsx")

Each csv will have its own sheet and the name will be their file name.

Best way to get identity of inserted row?

After Your Insert Statement you need to add this. And Make sure about the table name where data is inserting.You will get current row no where row affected just now by your insert statement.

IDENT_CURRENT('tableName')

How can I programmatically determine if my app is running in the iphone simulator?

Already asked, but with a very different title.

What #defines are set up by Xcode when compiling for iPhone

I'll repeat my answer from there:

It's in the SDK docs under "Compiling source code conditionally"

The relevant definition is TARGET_OS_SIMULATOR, which is defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:

#include "TargetConditionals.h"

but this is no longer necessary on the current (Xcode 6/iOS8) toolchain.

So, for example, if you want to check that you are running on device, you should do

#if TARGET_OS_SIMULATOR
    // Simulator-specific code
#else
    // Device-specific code
#endif

depending on which is appropriate for your use-case.

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

Edit: Documented by Apple although I couldn't actually get it to work: WKWebView Behavior with Keyboard Displays: "In iOS 10, WKWebView objects match Safari’s native behavior by updating their window.innerHeight property when the keyboard is shown, and do not call resize events" (perhaps can use focus or focus plus delay to detect keyboard instead of using resize).

Edit: code presumes onscreen keyboard, not external keyboard. Leaving it because info may be useful to others that only care about onscreen keyboards. Use http://jsbin.com/AbimiQup/4 to view page params.

We test to see if the document.activeElement is an element which shows the keyboard (input type=text, textarea, etc).

The following code fudges things for our purposes (although not generally correct).

function getViewport() {
    if (window.visualViewport && /Android/.test(navigator.userAgent)) {
        // https://developers.google.com/web/updates/2017/09/visual-viewport-api    Note on desktop Chrome the viewport subtracts scrollbar widths so is not same as window.innerWidth/innerHeight
        return {
            left: visualViewport.pageLeft,
            top: visualViewport.pageTop,
            width: visualViewport.width,
            height: visualViewport.height
        };
    }
    var viewport = {
            left: window.pageXOffset,   // http://www.quirksmode.org/mobile/tableViewport.html
            top: window.pageYOffset,
            width: window.innerWidth || documentElement.clientWidth,
            height: window.innerHeight || documentElement.clientHeight
    };
    if (/iPod|iPhone|iPad/.test(navigator.platform) && isInput(document.activeElement)) {       // iOS *lies* about viewport size when keyboard is visible. See http://stackoverflow.com/questions/2593139/ipad-web-app-detect-virtual-keyboard-using-javascript-in-safari Input focus/blur can indicate, also scrollTop: 
        return {
            left: viewport.left,
            top: viewport.top,
            width: viewport.width,
            height: viewport.height * (viewport.height > viewport.width ? 0.66 : 0.45)  // Fudge factor to allow for keyboard on iPad
        };
    }
    return viewport;
}


function isInput(el) {
    var tagName = el && el.tagName && el.tagName.toLowerCase();
    return (tagName == 'input' && el.type != 'button' && el.type != 'radio' && el.type != 'checkbox') || (tagName == 'textarea');
};

The above code is only approximate: It is wrong for split keyboard, undocked keyboard, physical keyboard. As per comment at top, you may be able to do a better job than the given code on Safari (since iOS8?) or WKWebView (since iOS10) using window.innerHeight property.

I have found failures under other circumstances: e.g. give focus to input then go to home screen then come back to page; iPad shouldnt make viewport smaller; old IE browsers won't work, Opera didnt work because Opera kept focus on element after keyboard closed.

However the tagged answer (changing scrolltop to measure height) has nasty UI side effects if viewport zoomable (or force-zoom enabled in preferences). I don't use the other suggested solution (changing scrolltop) because on iOS, when viewport is zoomable and scrolling to focused input, there are buggy interactions between scrolling & zoom & focus (that can leave a just focused input outside of viewport - not visible).

SVN 405 Method Not Allowed

My "disappeared" folder was libraries/fof.

If I deleted it, then ran an update, it wouldn't show up.

cd libaries
svn up

(nothing happens).

But updating with the actual name:

svn update fof

did the trick and it was updated. So I exploded my (manually tar-archived) working copy over it and recommitted. Easiest solution.

JavaScript Editor Plugin for Eclipse

Think that JavaScriptDevelopmentTools might do it. Although, I have eclipse indigo, and I'm pretty sure it does that kind of thing automatically.

Declare variable MySQL trigger

All DECLAREs need to be at the top. ie.

delimiter //

CREATE TRIGGER pgl_new_user 
AFTER INSERT ON users FOR EACH ROW
BEGIN
    DECLARE m_user_team_id integer;
    DECLARE m_projects_id integer;
    DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;

    SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");

    OPEN cur;
        ins_loop: LOOP
            FETCH cur INTO m_projects_id;
            IF done THEN
                LEAVE ins_loop;
            END IF;
            INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access) 
            VALUES (NEW.id, m_projects_id, now(), now(), 20);
        END LOOP;
    CLOSE cur;
END//

Passing Multiple route params in Angular2

OK realized a mistake .. it has to be /:id/:id2

Anyway didn't find this in any tutorial or other StackOverflow question.

@RouteConfig([{path: '/component/:id/:id2',name: 'MyCompB', component:MyCompB}])
export class MyCompA {
    onClick(){
        this._router.navigate( ['MyCompB', {id: "someId", id2: "another ID"}]);
    }
}

What is the difference between a static and a non-static initialization code block

The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

You must write onActivityResult() in your FirstActivity.Java as follows

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }
}

This will trigger onActivityResult method of fragments on FirstActivity.java

How can I set the default value for an HTML <select> element?

HTML snippet:

<select data-selected="public" class="form-control" name="role">
    <option value="public">
        Pubblica
    </option>
    <option value="user">
        Utenti
    </option>
    <option value="admin">
        Admin
    </option>
</select>

Native JavaScript snippet:

document.querySelectorAll('[data-selected]').forEach(e => {
   e.value = e.dataset.selected
});

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

Another possible solution...

def gather_requirements(top_path=None):
    """Captures requirements from repo.

    Expected file format is: requirements[-_]<optional-extras>.txt

    For example:

        pip install -e .[foo]

    Would require:

        requirements-foo.txt

        or

        requirements_foo.txt

    """
    from pip.download import PipSession
    from pip.req import parse_requirements
    import re

    session = PipSession()
    top_path = top_path or os.path.realpath(os.getcwd())
    extras = {}
    for filepath in tree(top_path):
        filename = os.path.basename(filepath)
        basename, ext = os.path.splitext(filename)
        if ext == '.txt' and basename.startswith('requirements'):
            if filename == 'requirements.txt':
                extra_name = 'requirements'
            else:
                _, extra_name = re.split(r'[-_]', basename, 1)
            if extra_name:
                reqs = [str(ir.req) for ir in parse_requirements(filepath, session=session)]
                extras.setdefault(extra_name, []).extend(reqs)
    all_reqs = set()
    for key, values in extras.items():
        all_reqs.update(values)
    extras['all'] = list(all_reqs)
    return extras

and then to use...

reqs = gather_requirements()
install_reqs = reqs.pop('requirements', [])
test_reqs = reqs.pop('test', [])
...
setup(
    ...
    'install_requires': install_reqs,
    'test_requires': test_reqs,
    'extras_require': reqs,
    ...
)

call a function in success of datatable ajax call

Try Following Code.

       var oTable = $('#app-config').dataTable(
        {
            "bAutoWidth": false,                                                
            "bDestroy":true,
            "bProcessing" : true,
            "bServerSide" : true,
            "sPaginationType" : "full_numbers",
            "sAjaxSource" : url,                    
            "fnServerData" : function(sSource, aoData, fnCallback) {
                alert("sSource"+ sSource);
                alert("aoData"+ aoData);
                $.ajax({
                    "dataType" : 'json',
                    "type" : "GET",
                    "url" : sSource,
                    "data" : aoData,
                    "success" : fnCallback
                }).success( function(){  alert("This Function will execute after data table loaded");   });
            }

How do I center align horizontal <UL> menu?

Try this:

div.topmenu-design ul
{
  display:block;
  width:600px; /* or whatever width value */
  margin:0px auto;
}

How do I do a not equal in Django queryset filtering?

This will give your desired result.

from django.db.models import Q
results = Model.objects.exclude(Q(a=True) & ~Q(x=5))

for not equal you can use ~ on an equal query. obviously, Q can be used to reach the equal query.

Limit String Length

You can use something similar to the below:

if (strlen($str) > 10)
   $str = substr($str, 0, 7) . '...';

How to reload or re-render the entire page using AngularJS

Try one of the following:

$route.reload(); // don't forget to inject $route in your controller
$window.location.reload();
location.reload();

Center content vertically on Vuetify

In Vuetify 2.x, v-layout and v-flex are replaced by v-row and v-col respectively. To center the content both vertically and horizontally, we have to instruct the v-row component to do it:

<v-container fill-height>
    <v-row justify="center" align="center">
        <v-col cols="12" sm="4">
            Centered both vertically and horizontally
        </v-col>
    </v-row>
</v-container>
  • align="center" will center the content vertically inside the row
  • justify="center" will center the content horizontally inside the row
  • fill-height will center the whole content compared to the page.

Which maven dependencies to include for spring 3.0?

What classes are missing? The class name itself should be a good clue to the missing module.

FYI, I know its really convenient to include the uber spring jar but this really causes issues when integrating with other projects. One of the benefits behind the dependency system is that it will resolve version conflicts among the dependencies.

If my library depends on spring-core:2.5 and you depend on my library and uber-spring:3.0, you now have 2 versions of spring on your classpath.

You can get around this with exclusions but its much easier to list the dependencies correctly and not have to worry about it.

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

Virtual Memory Usage from Java under Linux, too much memory used

No, you can't configure memory amount needed by VM. However, note that this is virtual memory, not resident, so it just stays there without harm if not actually used.

Alernatively, you can try some other JVM then Sun one, with smaller memory footprint, but I can't advise here.

Selecting specific rows and columns from NumPy array

Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:

>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

That is of course a pain to write, so you can let broadcasting help you:

>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

This is much simpler to do if you index with arrays, not lists:

>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

How to print formatted BigDecimal values?

 BigDecimal pi = new BigDecimal(3.14);
 BigDecimal pi4 = new BigDecimal(12.56);

 System.out.printf("%.2f",pi);

// prints 3.14

System.out.printf("%.0f",pi4);

// prints 13

List files in local git repo?

Try this command:

git ls-files 

This lists all of the files in the repository, including those that are only staged but not yet committed.

http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html

Vue Js - Loop via v-for X times (in a range)

You can use an index in a range and then access the array via its index:

<ul>
  <li v-for="index in 10" :key="index">
    {{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
  </li>
</ul>

You can also check the Official Documentation for more information.

How to run an awk commands in Windows?

Quoting is an issue if you're running awk from the command line. You'll sometimes need to use \, e.g. to quote ", but most of the time you'll use ^:

w:\srv>dir | grep ".txt" | awk "{ printf(\"echo %s@%s ^> %s.tstamp^\n\", $1, $2, $4); }"
echo 2014-09-07@22:21 > requirements-dev.txt.tstamp
echo 2014-11-28@18:14 > syncspec.txt.tstamp

How can I get argv[] as int?

argv[1] is a pointer to a string.

You can print the string it points to using printf("%s\n", argv[1]);

To get an integer from a string you have first to convert it. Use strtol to convert a string to an int.

#include <errno.h>   // for errno
#include <limits.h>  // for INT_MAX
#include <stdlib.h>  // for strtol
 
char *p;
int num;

errno = 0;
long conv = strtol(argv[1], &p, 10);

// Check for errors: e.g., the string does not represent an integer
// or the integer is larger than int
if (errno != 0 || *p != '\0' || conv > INT_MAX) {
    // Put here the handling of the error, like exiting the program with
    // an error message
} else {
    // No error
    num = conv;    
    printf("%d\n", num);
}

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

TypeError: 'module' object is not callable

Assume that the content of YourClass.py is:

class YourClass:
    # ......

If you use:

from YourClassParentDir import YourClass  # means YourClass.py

In this way, I got TypeError: 'module' object is not callable if you then tried to use YourClass().

But, if you use:

from YourClassParentDir.YourClass import YourClass   # means Class YourClass

or use YourClass.YourClass(), it works for me.

How to concat a string to xsl:value-of select="...?

Easiest method is

  <TD>
    <xsl:value-of select="concat(//author/first-name,' ',//author/last-name)"/>
  </TD>

when the XML Structure is

<title>The Confidence Man</title>
<author>
  <first-name>Herman</first-name>
  <last-name>Melville</last-name>
</author>
<price>11.99</price>

What is the use of "assert"?

Watch out for the parentheses. As has been pointed out above, in Python 3, assert is still a statement, so by analogy with print(..), one may extrapolate the same to assert(..) or raise(..) but you shouldn't.

This is important because:

assert(2 + 2 == 5, "Houston we've got a problem")

won't work, unlike

assert 2 + 2 == 5, "Houston we've got a problem"

The reason the first one will not work is that bool( (False, "Houston we've got a problem") ) evaluates to True.

In the statement assert(False), these are just redundant parentheses around False, which evaluate to their contents. But with assert(False,) the parentheses are now a tuple, and a non-empty tuple evaluates to True in a boolean context.

Dynamic tabs with user-click chosen components

there is component ready to use (rc5 compatible) ng2-steps which uses Compiler to inject component to step container and service for wiring everything together (data sync)

    import { Directive , Input, OnInit, Compiler , ViewContainerRef } from '@angular/core';

import { StepsService } from './ng2-steps';

@Directive({
  selector:'[ng2-step]'
})
export class StepDirective implements OnInit{

  @Input('content') content:any;
  @Input('index') index:string;
  public instance;

  constructor(
    private compiler:Compiler,
    private viewContainerRef:ViewContainerRef,
    private sds:StepsService
  ){}

  ngOnInit(){
    //Magic!
    this.compiler.compileComponentAsync(this.content).then((cmpFactory)=>{
      const injector = this.viewContainerRef.injector;
      this.viewContainerRef.createComponent(cmpFactory, 0,  injector);
    });
  }

}

Generate war file from tomcat webapp folder

You can create .war file back from your existing folder.

Using this command

cd /to/your/folder/location
jar -cvf my_web_app.war *

How to extract one column of a csv file

yes. cat mycsv.csv | cut -d ',' -f3 will print 3rd column.

How can I check if string contains characters & whitespace, not just whitespace?

I've used the following method to detect if a string contains only whitespace. It also matches empty strings.

if (/^\s*$/.test(myStr)) {
  // the string contains only whitespace
}

How can I set NODE_ENV=production on Windows?

It seems that

{
   "start_windows": "set NODE_ENV=test"
}

is not working for me. I'm currently trying this on my Windows machine. When I hit:

npm run start_windows

it would execute on the console without errors but when I try to echo

echo %NODE_ENV%

nothing comes out of it, meaning it does not exist and it wasn't set at all...

ActiveModel::ForbiddenAttributesError when creating new user

I guess you are using Rails 4. If so, the needed parameters must be marked as required.

You might want to do it like this:

class UsersController < ApplicationController

  def create
    @user = User.new(user_params)
    # ...
  end

  private

  def user_params
    params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password)
  end
end

Change image source with JavaScript

Under the TODOs, i am trying to implement your code in this posting. I am trying to take the large div on the left and make it change to reflect selections on the right. there are two selections, Ambient Temperature and Body Temperature

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title> Temperature Selection </title>_x000D_
<!-- css -->_x000D_
 <link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">_x000D_
 <link rel="stylesheet" href="css/main.css">_x000D_
_x000D_
<!-- end css -->_x000D_
<!-- Java script files -->_x000D_
<!-- Date.js date os javascript helper -->_x000D_
    <script src="js/date.js"> </script>_x000D_
_x000D_
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
 <script src="js/jquery-2.1.1.min.js"></script>_x000D_
_x000D_
<!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
 <script src="bootstrap-3/js/bootstrap.min.js"> </script>_x000D_
 <script src="js/library.js"> </script>_x000D_
 <script src="js/sfds.js"> </script>_x000D_
_x000D_
 <script src="js/main.js"> </script>_x000D_
_x000D_
<!-- End Java script files -->_x000D_
_x000D_
<!--TODO: need to integrate this code into the project:-->_x000D_
<script type="text/javascript">_x000D_
    function changeImage(a) {_x000D_
        document.getElementById("img").src=a;_x000D_
    }_x000D_
</script>_x000D_
 <script>_x000D_
 _x000D_
 _x000D_
 $(document).ready(function() {_x000D_
 _x000D_
  $("#ambient").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setTemperatureType(0);_x000D_
    $this.find('h2').text('Select Ambient Temperature 21 Degrees C');_x000D_
    <!--added on 05/20/2015-->_x000D_
   }else{_x000D_
    SFDS.setTemperatureType(1);_x000D_
    $this.addClass('clicked');_x000D_
    $this.find('h2').text('Ambient Temperature 21 Degrees C Selected');_x000D_
_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  $("#body").click(function(event){_x000D_
   var $this= $(this);_x000D_
   if($this.hasClass('clicked')){_x000D_
    $this.removeClass('clicked');_x000D_
    SFDS.setTemperatureType(0);_x000D_
    $this.find('h2').text('Select Body Temperature 37 Degrees C');_x000D_
    <!--added on 05/20/2015-->_x000D_
   }else{_x000D_
    SFDS.setTemperatureType(1);_x000D_
    $this.addClass('clicked');_x000D_
    $this.find('h2').text('Body Temperature 37 Degrees C Selected');_x000D_
_x000D_
_x000D_
   }_x000D_
  });_x000D_
  _x000D_
  _x000D_
  _x000D_
 });_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="container-fluid">_x000D_
 <header>_x000D_
  <div class="row">_x000D_
   <div class="col-xs-6">_x000D_
    <div id="date"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
   <div class="col-xs-6">_x000D_
    <div id="time" class="text-right"><span class="date_time"></span></div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </header>_x000D_
 <div class="row">_x000D_
  <div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">_x000D_
   <div id="temperature" class="main_button center-block">_x000D_
    <div class="large_circle_button"> _x000D_
     <h2>Select<br/>Temperature</h2>_x000D_
     <img class="center-block large_button_image" src="images/thermometer.png" alt=""> _x000D_
                    <!-- TODO <img src='images/dropsterilewater.png'  onclick='changeImage("images/dropsterilewater.png");'>_x000D_
                                <img src='images/imagecansterilesaline.png'  onclick='changeImage("images/imagecansterilesaline.png");'>-->_x000D_
    </div>_x000D_
    <h1></h1>_x000D_
   </div>_x000D_
  </div>_x000D_
  <div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">_x000D_
   <div class="row">_x000D_
    <div class="col-xs-12">_x000D_
     <div id="ambient" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h2>Ambient<br/>Temperature<br/>21<sup>o</sup>C</h2>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/house.png" alt="" class="ambient_temp_image">_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
    <div class="col-xs-12">_x000D_
     <div id="body" class="large_rectangle_button">_x000D_
      <div class="label_wrapper">_x000D_
       <h2>Body<br/>Temperature<br/>37<sup>o</sup>C</h2>_x000D_
      </div>_x000D_
      <div class="image_wrapper">_x000D_
       <img src="images/bodytempman.png" alt="" class="body_temp_image">_x000D_
      </div>_x000D_
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
     </div>_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
_x000D_
    _x000D_
</div>_x000D_
<footer class="footer navbar-fixed-bottom">_x000D_
 <div class="container-fluid">_x000D_
  <div class="row cols-bottom">_x000D_
   <div class="col-sm-3">_x000D_
    <a href="main.html">_x000D_
    <div class="small_circle_button">     _x000D_
     <img src="images/buttonback.png" alt="back to home" class="settings"/> <!--  width="49" height="48" -->_x000D_
    </div>_x000D_
   </div></a><div class=" col-sm-6">_x000D_
    <div id="stop_button" >_x000D_
     <img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->_x000D_
    </div>_x000D_
     _x000D_
   </div><div class="col-sm-3">_x000D_
    <div id="parker" class="pull-right">_x000D_
     <img src="images/#" alt="logo" /> <!-- width="131" height="65" -->_x000D_
    </div>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</footer>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Get a filtered list of files in a directory

Another option:

>>> import os, fnmatch
>>> fnmatch.filter(os.listdir('.'), '*.py')
['manage.py']

https://docs.python.org/3/library/fnmatch.html

How to vertically center content with variable height within a div?

This is my awesome solution for a div with a dynamic (percentaged) height.

CSS

.vertical_placer{
  background:red;
  position:absolute; 
  height:43%; 
  width:100%;
  display: table;
}

.inner_placer{  
  display: table-cell;
  vertical-align: middle;
  text-align:center;
}

.inner_placer svg{
  position:relative;
  color:#fff;
  background:blue;
  width:30%;
  min-height:20px;
  max-height:60px;
  height:20%;
}

HTML

<div class="footer">
    <div class="vertical_placer">
        <div class="inner_placer">
            <svg> some Text here</svg>
        </div>
    </div>
</div>  

Try this by yourself.

blur vs focusout -- any real differences?

As stated in the JQuery documentation

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

Performance of FOR vs FOREACH in PHP

I'm not sure this is so surprising. Most people who code in PHP are not well versed in what PHP is actually doing at the bare metal. I'll state a few things, which will be true most of the time:

  1. If you're not modifying the variable, by-value is faster in PHP. This is because it's reference counted anyway and by-value gives it less to do. It knows the second you modify that ZVAL (PHP's internal data structure for most types), it will have to break it off in a straightforward way (copy it and forget about the other ZVAL). But you never modify it, so it doesn't matter. References make that more complicated with more bookkeeping it has to do to know what to do when you modify the variable. So if you're read-only, paradoxically it's better not the point that out with the &. I know, it's counter intuitive, but it's also true.

  2. Foreach isn't slow. And for simple iteration, the condition it's testing against — "am I at the end of this array" — is done using native code, not PHP opcodes. Even if it's APC cached opcodes, it's still slower than a bunch of native operations done at the bare metal.

  3. Using a for loop "for ($i=0; $i < count($x); $i++) is slow because of the count(), and the lack of PHP's ability (or really any interpreted language) to evaluate at parse time whether anything modifies the array. This prevents it from evaluating the count once.

  4. But even once you fix it with "$c=count($x); for ($i=0; $i<$c; $i++) the $i<$c is a bunch of Zend opcodes at best, as is the $i++. In the course of 100000 iterations, this can matter. Foreach knows at the native level what to do. No PHP opcodes needed to test the "am I at the end of this array" condition.

  5. What about the old school "while(list(" stuff? Well, using each(), current(), etc. are all going to involve at least 1 function call, which isn't slow, but not free. Yes, those are PHP opcodes again! So while + list + each has its costs as well.

For these reasons foreach is understandably the best option for simple iteration.

And don't forget, it's also the easiest to read, so it's win-win.

How to push JSON object in to array using javascript

You need to have the 'data' array outside of the loop, otherwise it will get reset in every loop and also you can directly push the json. Find the solution below:-

var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
    console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
    my_json = feed;
    console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
    data.push(my_json);
     //["2017-03-14T01:00:32Z", 33358, "4", "4", "0"]
}); 
console.log(data);

The requested URL /about was not found on this server

Here is another version for Wordpress, original one did not work as intended.

# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^index\.php$ - [END]
    RewriteCond $1 ^(index\.php)?$ [OR]
    RewriteCond $1 \.(gif|jpg|png|ico|css|js)$ [NC,OR]
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ - [END]
    RewriteRule ^ /index.php [L]
</IfModule>
# END WordPress

Reference from this Github repository, modified a bit. After excessive testing this rule does not solve all problems. We have a Wordpress webshop, which has 40 plugins and somewhere is there a rewrite clash. I sincerely hope next version of Wordpress has no URL rewrites.


RewriteRule ^index\.php$ - [L]

Syntax Rewrite Rule

The ^ signifies start of the string, \ escapes . or it would mean any character, and $ signifies end of the string.

^index\.php$ if http(s)://hostname/index.php - do nothing [END] flag can be used to terminate not only the current round of rewrite processing but prevent any subsequent rewrite processing.


RewriteCond $1 ^(index\.php)?$ [OR]

Syntax Rewrite Condition

In RewriteCond using $1 as a test string references to captured contents of everything from the start to the end of the url http(s)://hostname/bla/bla.php. If used in substitution or condition it references to captured backreference. RewriteRule (bla)/(ble\.php)$ - for http(s)://hostname/bla/ble.php captures bla into $1 and ble.php into $2. Multiple capture groups can be accessed via $3..N.

( ) groups several characters into single unit, ? forces the match optional. [OR] flag allows you to combine rewrite conditions with a logical OR relationship as opposed to the default AND.

In short, if bla/bla.php contains index.php OR next condition


RewriteCond $1 \.(gif|jpg|png|ico|css|js)$ [NC,OR]

( ) groups several characters into single unit, | separates characters to subgroups and conditions them if any one of. [NC] flag causes the RewriteRule to be matched in case-insensitive manner.

In short, if bla/bla.php ends with any of the filetypes OR next condition


RewriteCond %{REQUEST_FILENAME} -f [OR]

Server-Variables are variables of the form %{ NAME_OF_VARIABLE } where NAME_OF_VARIABLE can be a string taken from the following list:

enter image description here

%{REQUEST_FILENAME} is full local filesystem path to the file or script matching the request, if this has already been determined by the server at the time REQUEST_FILENAME is referenced. Otherwise, such as when used in virtual host context, the same value as REQUEST_URI. Depending on the value of AcceptPathInfo, the server may have only used some leading components of the REQUEST_URI to map the request to a file.

-f check for regular file. Treats the test string as pathname and tests whether or not it exists.

In short, if bla/bla.php is a file OR next condition


RewriteCond %{REQUEST_FILENAME} -d

-d check for directory. Treats the test string as a pathname and tests whether or not it exists.

In short, if bla/bla.php is a directory


RewriteRule ^(.*)$ - [END] not as in Github [S=1]

This statement is only executed when one of the condition returned true.

. match any character * zero or more times.

The [S] flag is used to skip rules that you don't want to run. The syntax of the skip flag is [S=N], where N signifies the number of rules to skip (provided the RewriteRule matches). This can be thought of as a goto statement in your rewrite ruleset. In the following example, we only want to run the RewriteRule if the requested URI doesn't correspond with an actual file.

In short, do nothing


RewriteRule ^ /index.php [L]

The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.

In short, rewrite every path as http(s)://hostname/index.php


I fetched this little doc together from apaches.org documentation. Links below.

NoClassDefFoundError on Maven dependency

For some reason, the lib is present while compiling, but missing while running.

My situation is, two versions of one lib conflict.

For example, A depends on B and C, while B depends on D:1.0, C depends on D:1.1, maven may just import D:1.0. If A uses one class which is in D:1.1 but not in D:1.0, a NoClassDefFoundError will be throwed.

If you are in this situation too, you need to resolve the dependency conflict.

Smooth scrolling when clicking an anchor link

Here is the solution I implemented for multiple links and anchors, for a smooth scroll:

http://www.adriantomic.se/development/jquery-localscroll-tutorial/ if you have your navigation links set up in a navigation div and declared with this structure:

<a href = "#destinationA">

and your corresponding anchor tag destinations as so:

<a id = "destinationA">

Then just load this into the head of the document:

    <!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>

<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>

<script type = "text/javascript">
 $(document).ready(function()
    {
        // Scroll the whole document
        $('#menuBox').localScroll({
           target:'#content'
        });
    });
</script>

Thanks to @Adriantomic

How to include route handlers in multiple files in Express?

index.js

const express = require("express");
const app = express();
const http = require('http');
const server = http.createServer(app).listen(3000);
const router = (global.router = (express.Router()));
app.use('/books', require('./routes/books'))
app.use('/users', require('./routes/users'))
app.use(router);

routes/users.js

const router = global.router
router.get('/', (req, res) => {
    res.jsonp({name: 'John Smith'})
}

module.exports = router

routes/books.js

const router = global.router
router.get('/', (req, res) => {
    res.jsonp({name: 'Dreams from My Father by Barack Obama'})
}

module.exports = router

if you have your server running local (http://localhost:3000) then

// Users
curl --request GET 'localhost:3000/users' => {name: 'John Smith'}

// Books
curl --request GET 'localhost:3000/users' => {name: 'Dreams from My Father by Barack Obama'}

Rendering HTML in a WebView with custom CSS

If you have your CSS in the internal file storage you can use

//Get a reference to your webview
WebView web = (WebView)findViewById(R.id.webby);

// Prepare some html, it is formated with css loaded from the file style.css
String webContent = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><link rel=\"stylesheet\" href=\"style.css\"></head>"
                      + "<body><div class=\"running\">I am a text rendered with INDIGO</div></body></html>";

//get and format the path pointing to the internal storage
String internalFilePath = "file://" + getFilesDir().getAbsolutePath() + "/";

//load the html with the baseURL, all files relative to the baseURL will be found 
web.loadDataWithBaseURL(internalFilePath, webContent, "text/html", "UTF-8", "");

for each inside a for each - Java

Your syntax is not correct. It should be like that:

for (Tweet tweet : tweets) {              
    for(long forId : idFromArray){
        long tweetId = tweet.getId();
        if(forId != tweetId){
            String twitterString = tweet.getText();
            db.insertTwitter(twitterString);
        }
    }
}

EDIT

This answer no longer really answers the question since it was updated ;)

How to set a default Value of a UIPickerView

In normal case, you can do something like this in viewDidLoad method;

[_picker selectRow:1 inComponent:0 animated:YES];

In my case, I'd like to fetch data from api server and display them onto UIPickerView then I want the picker to select the first item by default.

The UIPickerView will look like it selected the first item after it was created, but when you try to get the selected index by using selectedRowInComponent, you will get NSNull. That's because it detected nothing changed by the user (select 0 from 0 ).

Following is my solution (in viewWillAppear, after I fetched the data)

[_picker selectRow:1 inComponent:0 animated:NO];
[_picker selectRow:0 inComponent:0 animated:NO];

Its a bit dirty, but dont worry, the UI rendering in iOS is very fast ;)

How to change collation of database, table, column?

I am contributing here, as the OP asked:

How to change collation of database, table, column?

The selected answer just states it on table level.


Changing it database wide:

ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Changing it per table:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Good practice is to change it at table level as it'll change it for columns as well. Changing for specific column is for any specific case.

Changing collation for a specific column:

ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Bulk Insert Correctly Quoted CSV File in SQL Server

You could also look at using OpenRowSet with the CSV text file data provider.

This should be possible with any version of SQL Server >= 2005 although you need to enable the feature.

http://social.msdn.microsoft.com/forums/en-US/sqldataaccess/thread/5869d247-f0a0-4224-80b3-ff2e414be402

How to print like printf in Python3?

Simple printf() function from O'Reilly's Python Cookbook.

import sys
def printf(format, *args):
    sys.stdout.write(format % args)

Example output:

i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

right click on your project and run as maven install then again run your application. if this didnt work go to the folder of your project directly start command line and run 'mvn install'enter image description here

Uninstall old versions of Ruby gems

Try something like gem uninstall rjb --version 1.3.4.

How to set cornerRadius for only top-left and top-right corner of a UIView?

Here is a Swift version of @JohnnyRockex answer

extension UIView {

    func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
         let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
         let mask = CAShapeLayer()
         mask.path = path.cgPath
         self.layer.mask = mask
    }

}

view.roundCorners([.topLeft, .bottomRight], radius: 10)

Note

If you're using Auto Layout, you'll need to subclass your UIView and call roundCorners in the view's layoutSubviews for optimal effect.

class View: UIView {
    override func layoutSubviews() {
        super.layoutSubviews()

        self.roundCorners([.topLeft, .bottomLeft], radius: 10)
    }
}

Laravel: Get base url

This:

echo url('/');

And this:

echo asset('/');

both displayed the home url in my case :)

Html.EditorFor Set Default Value

Shouldn't the @Html.EditorFor() make use of the Attributes you put in your model?

[DefaultValue(false)]
public bool TestAccount { get; set; }

Android: How to stretch an image to the screen width while maintaining aspect ratio?

Setting adjustViewBounds to true and using a LinearLayout view group worked very well for me. No need to subclass or ask for device metrics:

//NOTE: "this" is a subclass of LinearLayout
ImageView splashImageView = new ImageView(context);
splashImageView.setImageResource(R.drawable.splash);
splashImageView.setAdjustViewBounds(true);
addView(splashImageView);

Where does Visual Studio look for C++ header files?

Actually On my windows 10 with visual studio 2017 community, the C++ headers path are:

  1. C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include

  2. C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\ucrt

The 1st contains standard C++ headers such as <iostream>, <algorithm>. The 2nd contains old C headers such as <stdio.h>, <string.h>. The version number can be different based on your software.

Hope this would help.

Delete all rows in an HTML table

If you do not want to remove th and just want to remove the rows inside, this is working perfectly.

var tb = document.getElementById('tableId');
  while(tb.rows.length > 1) {
  tb.deleteRow(1);
}

Easy way to password-protect php page

A simple way to protect a file with no requirement for a separate login page - just add this to the top of the page:

Change secretuser and secretpassword to your user/password.

$user = $_POST['user'];
$pass = $_POST['pass'];

if(!($user == "secretuser" && $pass == "secretpassword"))
{
    echo '<html><body><form method="POST" action="'.$_SERVER['REQUEST_URI'].'">
            Username: <input type="text" name="user"></input><br/>
            Password: <input type="password" name="pass"></input><br/>
            <input type="submit" name="submit" value="Login"></input>
            </form></body></html>';
    exit();
}

spring data jpa @query and pageable

Please reference :Spring Data JPA @Query, if you are using Spring Data JPA version 2.0.4 and later. Sample like below:

@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);

How can I add NSAppTransportSecurity to my info.plist file?

Xcode 9.2, Swift 4, this works for me.

<key>App Transport Security Settings</key>
<dict>
    <key>Allow Arbitrary Loads</key>
    <true/>
</dict>

Mask for an Input to allow phone numbers?

I Think the simplest solutions is to add ngx-mask

npm i --save ngx-mask

then you can do

<input type='text' mask='(000) 000-0000' >

OR

<p>{{ phoneVar | mask: '(000) 000-0000' }} </p>

How can I split a string with a string delimiter?

Try this function instead.

string source = "My name is Marco and I'm from Italy";
string[] stringSeparators = new string[] {"is Marco and"};
var result = source.Split(stringSeparators, StringSplitOptions.None);

Laravel 5 - redirect to HTTPS

The answers above didn't work for me, but it appears that Deniz Turan rewrote the .htaccess in a way that works with Heroku's load balancer here: https://www.jcore.com/2017/01/29/force-https-on-heroku-using-htaccess/

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

How to define multiple CSS attributes in jQuery?

$('#message').css({ width: 550, height: 300, 'font-size': '8pt' });

How to find the kafka version in linux

go to kafka/libs folder we can see multiple jars search for something similar kafka_2.11-0.10.1.1.jar.asc in this case the kafka version is 0.10.1.1

Concatenate a vector of strings/character

Matt Turner's answer is definitely the right answer. However, in the spirit of Ken Williams' answer, you could also do:

capture.output(cat(sdata, sep="")) 

Changing ImageView source

You're supposed to use setImageResource instead of setBackgroundResource.

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Vue js error: Component template should contain exactly one root element

You need to wrap all the html into one single element.

<template>
   <div>
        <div class="form-group">
            <label for="avatar" class="control-label">Avatar</label>
            <input type="file" v-on:change="fileChange" id="avatar">
            <div class="help-block">
                Help block here updated 4  ...
            </div>
        </div>

        <div class="col-md-6">
            <input type="hidden" name="avatar_id">
            <img class="avatar" title="Current avatar">
        </div>
   </div>

</template>

<script>
    export default{
        methods: {
            fileChange(){
                console.log('Test of file input change')
            }
        }
    }
</script>

Is there a vr (vertical rule) in html?

HTML has little to no vertical positioning due to typographic nature of content layout. Vertical Rule just doesn't fit its semantics.

Is it possible to save HTML page as PDF using JavaScript or jquery?

I used jsPDF and dom-to-image library to export HTML to PDF.

I post here as reference to whom concern.

$('#downloadPDF').click(function () {
    domtoimage.toPng(document.getElementById('content2'))
      .then(function (blob) {
          var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
          pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
          pdf.save("test.pdf");
      });
});

Demo: https://jsfiddle.net/viethien/md03wb21/27/

filtering a list using LINQ

Based on http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b,

EqualAll is the approach that best meets your needs.

public void Linq96() 
{ 
    var wordsA = new string[] { "cherry", "apple", "blueberry" }; 
    var wordsB = new string[] { "cherry", "apple", "blueberry" }; 

    bool match = wordsA.SequenceEqual(wordsB); 

    Console.WriteLine("The sequences match: {0}", match); 
} 

Where should my npm modules be installed on Mac OS X?

/usr/local/lib/node_modules is the correct directory for globally installed node modules.

/usr/local/share/npm/lib/node_modules makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:

/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules

The latter seems to be node modules that came with Node, e.g., lodash, when the former is Node modules that I installed using npm.

How to add google-services.json in Android?

Above asked question has been solved as according to documentation at developer.google.com https://developers.google.com/cloud-messaging/android/client#get-config

2018 Edit : GCM Deprecated, use FCM

The file google-services.json should be pasted in the app/ directory. After this is when I sync the project with gradle file the unexpected Top level exception error comes. This is occurring because:

Project-Level Gradle File having

dependencies {
    classpath 'com.android.tools.build:gradle:1.0.0'
    classpath 'com.google.gms:google-services:1.3.0-beta1'
}

and App-Level Gradle File having:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    compile 'com.google.android.gms:play-services:7.5.0' // commenting this lineworks for me
}

The top line is creating a conflict between this and classpath 'com.google.gms:google-services:1.3.0-beta1' So I make comment it now it works Fine and no error of File google-services.json is missing from module root folder. The Google Quickstart Plugin cannot function without it.

npm ERR! Error: EPERM: operation not permitted, rename

This is a typical error caused by Antivirus. There is a workaround for cases like mine, where I can't disable A/V (Company Policy).

You have to change the polyfills.js inside Npm package:

[NODE_HOME]/node_modules/npm/node_modules/graceful_fs/polyfills.js

Look for this statement:

if (process.platform === "win32") {

Inside of this statement, there is a timeout making a retry in case of error. The problem is that in some cases, after the timeout, the file is still locked by the A/V. The solution is rip out the timeout and let this statement in loop. The change with the previous code commented:

if (platform === "win32") {

fs.rename = (function (fs$rename) { return function (from, to, cb) {
  var start = Date.now()
  var backoff = 0;
  fs$rename(from, to, function CB (er) {
    if (er
        && (er.code === "EACCES" || er.code === "EPERM")
        /*&& Date.now() - start < 60000*/) {
            console.log("Retrying rename file: " + from + " <> " + to)
            fs$rename(from, to, CB);
      /*setTimeout(function() {
        fs.stat(to, function (stater, st) {
          if (stater && stater.code === "ENOENT")
            fs$rename(from, to, CB);
          else
            cb(er)
        })
      }, backoff)*/
      if (backoff < 100)
        backoff += 10;
      return;
    }
    if (cb) cb(er)
  })
}})(fs.rename)
}

How can you use php in a javascript function

In the above given code

assign the php value to javascript variable.

<html>
<?php
 $num = 1;
 echo $num;
?>
  <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
  <br>
  <script>
   var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var             numeric 
  function Inc()
   {
     numeric = eVal(numeric) + 1;
     alert("Increamented value: "+numeric);
   }
  </script>
</html>

One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.

Using 'make' on OS X

If you've installed Xcode 4.3 and its Command Line Tools, just open Terminal and type the following: On Xcode 4.3, type the following in Terminal:

export PATH=$PATH:/Applications/Xcode.app/Contents/Developer/usr/bin

How can I add additional PHP versions to MAMP

Additional Version of PHP can be installed directly from the APP (using MAMP PRO v5 at least).

Here's how (All Steps):

MAMP PRO --> Preferences --> click [Check Now] to check for updates (even if you have automatic updates enabled!) --> click [Show PHP Versions] --> Install as needed!

Step-by-step screenshots:

MAMP PRO --> Preferences

enter image description here

enter image description here

enter image description here

List comprehension vs. lambda + filter

This is a somewhat religious issue in Python. Even though Guido considered removing map, filter and reduce from Python 3, there was enough of a backlash that in the end only reduce was moved from built-ins to functools.reduce.

Personally I find list comprehensions easier to read. It is more explicit what is happening from the expression [i for i in list if i.attribute == value] as all the behaviour is on the surface not inside the filter function.

I would not worry too much about the performance difference between the two approaches as it is marginal. I would really only optimise this if it proved to be the bottleneck in your application which is unlikely.

Also since the BDFL wanted filter gone from the language then surely that automatically makes list comprehensions more Pythonic ;-)

How to convert an integer to a string in any base?

Here is an example of how to convert a number of any base to another base.

from collections import namedtuple

Test = namedtuple("Test", ["n", "from_base", "to_base", "expected"])


def convert(n: int, from_base: int, to_base: int) -> int:
    digits = []
    while n:
        (n, r) = divmod(n, to_base)
        digits.append(r)    
    return sum(from_base ** i * v for i, v in enumerate(digits))


if __name__ == "__main__":
    tests = [
        Test(32, 16, 10, 50),
        Test(32, 20, 10, 62),
        Test(1010, 2, 10, 10),
        Test(8, 10, 8, 10),
        Test(150, 100, 1000, 150),
        Test(1500, 100, 10, 1050000),
    ]

    for test in tests:
        result = convert(*test[:-1])
        assert result == test.expected, f"{test=}, {result=}"
    print("PASSED!!!")

Concatenating bits in VHDL

The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only

How do I determine if my python shell is executing in 32bit or 64bit?

For 32 bit it will return 32 and for 64 bit it will return 64

import struct
print(struct.calcsize("P") * 8)

Import CSV to mysql table

if you have the ability to install phpadmin there is a import section where you can import csv files to your database there is even a checkbox to set the header to the first line of the file contains the table column names (if this is unchecked, the first line will become part of the data

Appending the same string to a list of strings in Python

Just in case

list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
for i in range(len(list)):
    list[i] += string
print(list)

How to create a unique index on a NULL column?

The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:

CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X  int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)

Global variables in Java

To define Global Variable you can make use of static Keyword

public final class Tools {
  public static int a;
  public static int b;
}

now you can access a and b from anywhere by calling

Tools.a;
Tools.b;

Yoy are right...specially in J2ME... You can avoid NullPointerException by putting inside your MidLet constructor (proggy initialization) this line of code:

new Tools();

This ensures that Tools will be allocated before any instruction that uses it.

That's it!

Create a folder inside documents folder in iOS apps

This works fine for me,

NSFileManager *fm = [NSFileManager defaultManager];
NSArray *appSupportDir = [fm URLsForDirectory:NSDocumentsDirectory inDomains:NSUserDomainMask];
NSURL* dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:@"YourFolderName"];

NSError*    theError = nil; //error setting
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
                           attributes:nil error:&theError])
{
   NSLog(@"not created");
}

Undefined reference to `sin`

You need to link with the math library, libm:

$ gcc -Wall foo.c -o foo -lm 

Detecting Back Button/Hash Change in URL

HTML5 has included a much better solution than using hashchange which is the HTML5 State Management APIs - https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history - they allow you to change the url of the page, without needing to use hashes!

Though the HTML5 State Functionality is only available to HTML5 Browsers. So you probably want to use something like History.js which provides a backwards compatible experience to HTML4 Browsers (via hashes, but still supports data and titles as well as the replaceState functionality).

You can read more about it here: https://github.com/browserstate/History.js

How do I format a date with Dart?

 String dateConverter(String date) {
    // Input date Format
    final format = DateFormat("dd-MM-yyyy");
    DateTime gettingDate = format.parse(date);
    final DateFormat formatter = DateFormat('yyyy-MM-dd');
    // Output Date Format
    final String formatted = formatter.format(gettingDate);
    return date;
  }

How to use Lambda in LINQ select statement

You appear to be trying to mix query expression syntax and "normal" lambda expression syntax. You can either use:

IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID};
ViewBag.storeSelector = stores;

Or:

IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(s => new SelectListItem { Value = s.Name, Text = s.ID});
ViewBag.storeSelector = stores;

You can't mix the two like you're trying to.

Ruby on Rails - Import Data from a CSV file

This can help. It has code examples too:

http://csv-mapper.rubyforge.org/

Or for a rake task for doing the same:

http://erikonrails.snowedin.net/?p=212

Handlebars.js Else If

Hello I have only a MINOR classname edit, and so far this is how iv divulged it. i think i need to pass in multpile parameters to the helper,

server.js

app.engine('handlebars', ViewEngine({
        "helpers":{
                isActive: (val, options)=>{
                    if (val === 3 || val === 0){
                        return options.fn(this)
                    }
                } 
        }
}));

header.handlebars

<ul class="navlist">
          <li   class="navitem navlink {{#isActive 0}}active{{/isActive}}"
                ><a href="#">Home</a></li>
          <li   class="navitem navlink {{#isActive 1}}active{{/isActive}}"
                ><a href="#">Trending</a></li>
          <li   class="navitem navlink {{#isActive 2}}active{{/isActive}}"
                ><a href="#">People</a></li>
          <li   class="navitem navlink {{#isActive 3}}active{{/isActive}}"
                ><a href="#">Mystery</a></li>
          <li class="navitem navbar-search">
            <input type="text" id="navbar-search-input" placeholder="Search...">
            <button type="button" id="navbar-search-button"><i class="fas fa-search"></i></button>
          </li>
        </ul>