Programs & Examples On #Litespeed

Keeping session alive with Curl and PHP

This is how you do CURL with sessions

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

I've seen this on ImpressPages

Using the rJava package on Win7 64 bit with R

I think this is an update. I was unable to install rJava (on Windows) until I installed the JDK, as per Javac is not found and javac not working in windows command prompt. The message I was getting was

'javac' is not recognized as an internal or external command, operable program or batch file.

The JDK includes the JRE, and according to https://cran.r-project.org/web/packages/rJava/index.html the current version (0.9-7 published 2015-Jul-29) of rJava

SystemRequirements:     Java JDK 1.2 or higher (for JRI/REngine JDK 1.4 or higher), GNU make

So there you are: if rJava won't install because it can't find javac, and you have the JRE installed, then try the JDK. Also, make sure that JAVA_HOME points to the JDK and not the JRE.

How can I check if a Perl array contains a particular value?

Simply turn the array into a hash:

my %params = map { $_ => 1 } @badparams;

if(exists($params{$someparam})) { ... }

You can also add more (unique) params to the list:

$params{$newparam} = 1;

And later get a list of (unique) params back:

@badparams = keys %params;

How can I search Git branches for a file or directory?

git ls-tree might help. To search across all existing branches:

for branch in `git for-each-ref --format="%(refname)" refs/heads`; do
  echo $branch :; git ls-tree -r --name-only $branch | grep '<foo>'
done

The advantage of this is that you can also search with regular expressions for the file name.

Bootstrap 3 Glyphicons are not working

I was looking through this old question of mine and since what was supposed to be the correct answer up until now, was given by me in the comments, I think I also deserve the credit for it.

The problem lied in the fact that the glyphicon font files downloaded from bootstrap's customizer tool were not the same with the ones that are downloaded from the redirection found at bootstrap's homepage. The ones that are working as they should are the ones that can be downloaded from the following link:

http://getbootstrap.com/getting-started/#download

Anyone having problems with old bad customizer files should overwrite the fonts from the link above.

How do I generate a stream from a string?

Another solution:

public static MemoryStream GenerateStreamFromString(string value)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

you will also need to have a asp:ScriptManager control on every page that you want to use ajax controls on. you should be able to just drag the scriptmanager over from your toolbox one the toolkit is installed following Zack's instructions.

How to check if a line is blank using regex

Here Blank mean what you are meaning.
A line contains full of whitespaces or a line contains nothing.
If you want to match a line which contains nothing then use '/^$/'.

An invalid form control with name='' is not focusable

For Select2 Jquery problem

The problem is due to the HTML5 validation cannot focus a hidden invalid element. I came across this issue when I was dealing with jQuery Select2 plugin.

Solution You could inject an event listener on and 'invalid' event of every element of a form so that you can manipulate just before the HTML5 validate event.

$('form select').each(function(i){
this.addEventListener('invalid', function(e){            
        var _s2Id = 's2id_'+e.target.id; //s2 autosuggest html ul li element id
        var _posS2 = $('#'+_s2Id).position();
        //get the current position of respective select2
        $('#'+_s2Id+' ul').addClass('_invalid'); //add this class with border:1px solid red;
        //this will reposition the hidden select2 just behind the actual select2 autosuggest field with z-index = -1
        $('#'+e.target.id).attr('style','display:block !important;position:absolute;z-index:-1;top:'+(_posS2.top-$('#'+_s2Id).outerHeight()-24)+'px;left:'+(_posS2.left-($('#'+_s2Id).width()/2))+'px;');
        /*
        //Adjust the left and top position accordingly 
        */
        //remove invalid class after 3 seconds
        setTimeout(function(){
            $('#'+_s2Id+' ul').removeClass('_invalid');
        },3000);            
        return true;
}, false);          
});

How to find sitemap.xml path on websites?

Use Google Search Operators to find it for you

search google with the below code..

inurl:domain.com filetype:xml click on this to view sitemap search example

change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)

JavaScript pattern for multiple constructors

How do you find this one?

function Foobar(foobar) {
    this.foobar = foobar;
}

Foobar.prototype = {
    foobar: null
};

Foobar.fromComponents = function(foo, bar) {
    var foobar = foo + bar;
    return new Foobar(foobar);
};

//usage: the following two lines give the same result
var x = Foobar.fromComponents('Abc', 'Cde');
var y = new Foobar('AbcDef')

How to check if a file exists from a url

You don't need CURL for that... Too much overhead for just wanting to check if a file exists or not...

Use PHP's get_header.

$headers=get_headers($url);

Then check if $result[0] contains 200 OK (which means the file is there)

A function to check if a URL works could be this:

function UR_exists($url){
   $headers=get_headers($url);
   return stripos($headers[0],"200 OK")?true:false;
}

/* You can test a URL like this (sample) */
if(UR_exists("http://www.amazingjokes.com/"))
   echo "This page exists";
else
   echo "This page does not exist";

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

This problem occurs because the Web site does not have the Directory Browsing feature enabled, and the default document is not configured. To resolve this problem, use one of the following methods. To resolve this problem, I followed the steps in Method 1 as mentioned in the MS Support page and its the recommended method.

Method 1: Enable the Directory Browsing feature in IIS (Recommended)

  1. Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.

  2. In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.

  3. In the Features view, double-click Directory Browsing.

  4. In the Actions pane, click Enable.

If that does not work for, you might be having different problem than just a Directory listing issue. So follow the below step,

Method 2: Add a default document

To resolve this problem, follow these steps:

  • Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
  • In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
  • In the Features view, double-click Default Document.
  • In the Actions pane, click Enable.
  • In the File Name box, type the name of the default document, and then click OK.

Method 3: Enable the Directory Browsing feature in IIS Express

Note This method is for the web developers who experience the issue when they use IIS Express.

Follow these steps:

  • Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt: C:\Program Files\IIS Express

  • Type the following command, and then press Enter:

    appcmd set config /section:system.webServer/directoryBrowse /enabled:true

What is PostgreSQL equivalent of SYSDATE from Oracle?

NOW() is the replacement of Oracle Sysdate in Postgres.

Try "Select now()", it will give you the system timestamp.

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

What is an undefined reference/unresolved external symbol error and how do I fix it?

An “Undefined Reference” error occurs when we have a reference to object name (class, function, variable, etc.) in our program and the linker cannot find its definition when it tries to search for it in all the linked object files and libraries.

Thus when the linker cannot find the definition of a linked object, it issues an “undefined reference” error. As clear from definition, this error occurs in the later stages of the linking process. There are various reasons that cause an “undefined reference” error.

Some possible reason(more frequent):

#1) No Definition Provided For Object

This is the simplest reason for causing an “undefined reference” error. The programmer has simply forgotten to define the object.

Consider the following C++ program. Here we have only specified the prototype of function and then used it in the main function.

#include <iostream>
int func1();
int main()
{
     
    func1();
}

Output:

main.cpp:(.text+0x5): undefined reference to 'func1()'
collect2: error ld returned 1 exit status

So when we compile this program, the linker error that says “undefined reference to ‘func1()’” is issued.

In order to get rid of this error, we correct the program as follows by providing the definition of the function func1. Now the program gives the appropriate output.

#include <iostream>
using namespace std;
int func1();
 
int main()
{
     
    func1();
}
int func1(){
    cout<<"hello, world!!";
}

Output:

hello, world!!

#2) Wrong Definition (signatures don’t match) Of Objects Used

Yet another cause for “undefined reference” error is when we specify wrong definitions. We use any object in our program and its definition is something different.

Consider the following C++ program. Here we have made a call to func1 (). Its prototype is int func1 (). But its definition does not match with its prototype. As we see, the definition of the function contains a parameter to the function.

Thus when the program is compiled, the compilation is successful because of the prototype and function call match. But when the linker is trying to link the function call with its definition, it finds the problem and issues the error as “undefined reference”.

#include <iostream>
using namespace std;
int func1();
int main()
{
     
    func1();
}
int func1(int n){
    cout<<"hello, world!!";
}

Output:

main.cpp:(.text+0x5): undefined reference to 'func1()'
collect2: error ld returned 1 exit status

Thus to prevent such errors, we simply cross-check if the definitions and usage of all the objects are matching in our program.

#3) Object Files Not Linked Properly

This issue can also give rise to the “undefined reference” error. Here, we may have more than one source files and we might compile them independently. When this is done, the objects are not linked properly and it results in “undefined reference”.

Consider the following two C++ programs. In the first file, we make use of the “print ()” function which is defined in the second file. When we compile these files separately, the first file gives “undefined reference” for the print function, while the second file gives “undefined reference” for the main function.

int print();
int main()
{
    print();
}

Output:

main.cpp:(.text+0x5): undefined reference to 'print()'
collect2: error ld returned 1 exit status

int print() {
    return 42;
}

Output:

(.text+0x20): undefined reference to 'main'
collect2: error ld returned 1 exit status

The way to resolve this error is to compile both the files simultaneously (For example, by using g++).

Apart from the causes already discussed, “undefined reference” may also occur because of the following reasons.

#4) Wrong Project Type

When we specify wrong project types in C++ IDEs like the visual studio and try to do things that the project does not expect, then, we get “undefined reference”.

#5) No Library

If a programmer has not specified the library path properly or completely forgotten to specify it, then we get an “undefined reference” for all the references the program uses from the library.

#6) Dependent Files Are Not Compiled

A programmer has to ensure that we compile all the dependencies of the project beforehand so that when we compile the project, the compiler finds all the dependencies and compiles successfully. If any of the dependencies are missing then the compiler gives “undefined reference”.

Apart from the causes discussed above, the “undefined reference” error can occur in many other situations. But the bottom line is that the programmer has got the things wrong and in order to prevent this error they should be corrected.

Validating file types by regular expression

Are you just looking to verify that the file is of a given extension? You can simplify what you are trying to do with something like this:

(.*?)\.(jpg|gif|doc|pdf)$

Then, when you call IsMatch() make sure to pass RegexOptions.IgnoreCase as your second parameter. There is no reason to have to list out the variations for casing.

Edit: As Dario mentions, this is not going to work for the RegularExpressionValidator, as it does not support casing options.

Java - how do I write a file to a specified directory

You should use the secondary constructor for File to specify the directory in which it is to be symbolically created. This is important because the answers that say to create a file by prepending the directory name to original name, are not as system independent as this method.

Sample code:

String dirName = /* something to pull specified dir from input */;

String fileName = "test.txt";
File dir = new File (dirName);
File actualFile = new File (dir, fileName);

/* rest is the same */

Hope it helps.

Reading Excel file using node.js

install exceljs and use the following code,

var Excel = require('exceljs');

var wb = new Excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'sample.xlsx');

wb.xlsx.readFile(filePath).then(function(){

    var sh = wb.getWorksheet("Sheet1");

    sh.getRow(1).getCell(2).value = 32;
    wb.xlsx.writeFile("sample2.xlsx");
    console.log("Row-3 | Cell-2 - "+sh.getRow(3).getCell(2).value);

    console.log(sh.rowCount);
    //Get all the rows data [1st and 2nd column]
    for (i = 1; i <= sh.rowCount; i++) {
        console.log(sh.getRow(i).getCell(1).value);
        console.log(sh.getRow(i).getCell(2).value);
    }
});

Limit String Length

$value = str_limit('This string is really really long.', 7);

// This st...

Changing password with Oracle SQL Developer

you can find the user in DBA_USERS table like

SELECT profile
FROM dba_users
WHERE username = 'MacsP'

Now go to the sys/system (administrator) and use query

ALTER USER PRATEEK
IDENTIFIED BY "new_password"
REPLACE "old_password"

To verify the account status just go through

SELECT * FROM DBA_USERS.

and you can see status of your user.

Where to find extensions installed folder for Google Chrome on Mac?

You can find all Chrome extensions in below location.

/Users/{mac_user}/Library/Application Support/Google/Chrome/Default/Extensions

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

How to apply `git diff` patch without Git installed?

Use

git apply patchfile

if possible.

patch -p1 < patchfile 

has potential side-effect.

git apply also handles file adds, deletes, and renames if they're described in the git diff format, which patch won't do. Finally, git apply is an "apply all or abort all" model where either everything is applied or nothing is, whereas patch can partially apply patch files, leaving your working directory in a weird state.

ASP.Net 2012 Unobtrusive Validation with jQuery

Other than the required "jquery" ScriptResourceDefinition in Global.asax (use your own paths):

    protected void Application_Start(object sender, EventArgs e)
    {            
        ScriptManager.ScriptResourceMapping.AddDefinition(
            "jquery",
            new ScriptResourceDefinition
            {
                Path = "/static/scripts/jquery-1.8.3.min.js",
                DebugPath = "/static/scripts/jquery-1.8.3.js",
                CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js",
                CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.js",
                CdnSupportsSecureConnection = true,
                LoadSuccessExpression = "jQuery"
            });
    }

You additionally only need to explicitly add "WebUIValidation.js" after "jquery" ScriptReference in ScriptManager (the most important part):

       <asp:ScriptManager runat="server" EnableScriptGlobalization="True" EnableCdn="True">
            <Scripts>
                <asp:ScriptReference Name="jquery" />
                <asp:ScriptReference Name="WebUIValidation.js" Assembly="System.Web" />
            </Scripts>
        </asp:ScriptManager>

If you add it before "jquery", or if you don't add any or both of them at all (ASP.Net will then automatically add it before "jquery") - the client validation will be completely broken:

http://connect.microsoft.com/VisualStudio/feedback/details/748064/unobtrusive-validation-breaks-with-a-script-manager-on-the-page

You don't need any of those NuGet packages at all, nor any additional ScriptReference (some of which are just duplicates, or even a completely unnecessary bloat - as they are added automatically by ASP.Net if needed) mentioned in your blog.

EDIT: you don't need to explicitly add "WebForms.js" as well (removed it from the example) - and if you do, its LoadSuccessExpression will be ignored for some reason

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

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

Alternatively you could add an endpoint to return your variable:

@app.route("/api/geocode")
def geo_code():
    return jsonify(geocode)

Then do an XHR to retrieve it:

fetch('/api/geocode')
  .then((res)=>{ console.log(res) })

Split string into individual words Java

See my other answer if your phrase contains accentuated characters :

String[] listeMots = phrase.split("\\P{L}+");

Connecting to MySQL from Android with JDBC

public void testDB() {
        TextView tv = (TextView) this.findViewById(R.id.tv_data);
        try {

            Class.forName("com.mysql.jdbc.Driver");

            // perfect

            // localhost

            /*
             * Connection con = DriverManager .getConnection(
             * "jdbc:mysql://192.168.1.5:3306/databasename?user=root&password=123"
             * );
             */

            // online testing

            Connection con = DriverManager
                    .getConnection("jdbc:mysql://173.5.128.104:3306/vokyak_heyou?user=viowryk_hiweser&password=123");

            String result = "Database connection success\n";
            Statement st = con.createStatement();

            ResultSet rs = st.executeQuery("select * from tablename ");
            ResultSetMetaData rsmd = rs.getMetaData();

            while (rs.next()) {

                result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";

            }
            tv.setText(result);
        } catch (Exception e) {
            e.printStackTrace();
            tv.setText(e.toString());
        }

    }

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

Android: Center an image

You can also use this,

android:layout_centerHorizontal="true"

The image will be placed at the center of the screen

PHP regular expression - filter number only

You can try that one:

$string = preg_replace('/[^0-9]/', '', $string);

Cheers.

Check/Uncheck a checkbox on datagridview

I had the same problem, and even with the solutions provided here it did not work. The checkboxes would simply not change, their Value would remain null. It took me ages to realize my dumbness:

Turns out, I called the form1.PopulateDataGridView(my data) on the Form derived class Form1 before I called form1.Show(). When I changed up the order, that is to call Show() first, and then read the data and fill in the checkboxes, the value did not stay null.

What online brokers offer APIs?

I've been using parts of the marketcetera platform. They support all kinds of marketdata sources and brokers and you should easily be able to add more brokers and/or data providers. This is not a direct broker API of course, but that helps you avoid vendor lock-in so that might be a good thing. And of course all the tools they use are open source.

Add event handler for body.onload by javascript within <body> part

As @epascarello mentioned for W3C standard browsers, you should use:

body.addEventListener("load", init, false);

However, if you want it to work on IE<9 as well you can use:

var prefix = window.addEventListener ? "" : "on";
var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
document.body[eventName](prefix + "load", init, false);

Or if you want it in a single line:

document.body[window.addEventListener ? 'addEventListener' : 'attachEvent'](
    window.addEventListener ? "load" : "onload", init, false);

Note: here I get a straight reference to the body element via the document, saving the need for the first line.

Also, if you're using jQuery, and you want to use the DOM ready event rather than when the body loads, the answer can be even shorter...

$(init);

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.

On other servers, where the same services are consumed, the certificates were configured as follows:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"

As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"

Once that change was made, all was well. Thanks to everyone who offered assistance.

How to reload apache configuration for a site without restarting apache?

Updated for Apache 2.4, for non-systemd (e.g., CentOS 6.x, Amazon Linux AMI) and for systemd (e.g., CentOS 7.x):

There are two ways of having the apache process reload the configuration, depending on what you want done with its current threads, either advise to exit when idle, or killing them directly.

Note that Apache recommends using apachectl -k as the command, and for systemd, the command is replaced by httpd -k

apachectl -k graceful or httpd -k graceful

Apache will advise its threads to exit when idle, and then apache reloads the configuration (it doesn't exit itself), this means statistics are not reset.

apachectl -k restart or httpd -k restart

This is similar to stop, in that the process kills off its threads, but then the process reloads the configuration file, rather than killing itself.

Source: https://httpd.apache.org/docs/2.4/stopping.html

How to search for a part of a word with ElasticSearch

Nevermind.

I had to look at the Lucene documentation. Seems I can use wildcards! :-)

curl http://localhost:9200/my_idx/my_type/_search?q=*Doe*

does the trick!

How to draw text using only OpenGL methods?

enter image description here

Use glutStrokeCharacter(GLUT_STROKE_ROMAN, myCharString).

An example: A STAR WARS SCROLLER.

#include <windows.h>
#include <string.h>
#include <GL\glut.h>
#include <iostream.h>
#include <fstream.h>

GLfloat UpwardsScrollVelocity = -10.0;
float view=20.0;

char quote[6][80];
int numberOfQuotes=0,i;

//*********************************************
//*  glutIdleFunc(timeTick);                  *
//*********************************************

void timeTick(void)
{
    if (UpwardsScrollVelocity< -600)
        view-=0.000011;
    if(view < 0) {view=20; UpwardsScrollVelocity = -10.0;}
    //  exit(0);
    UpwardsScrollVelocity -= 0.015;
  glutPostRedisplay();

}


//*********************************************
//* printToConsoleWindow()                *
//*********************************************

void printToConsoleWindow()
{
    int l,lenghOfQuote, i;

    for(  l=0;l<numberOfQuotes;l++)
    {
        lenghOfQuote = (int)strlen(quote[l]);

        for (i = 0; i < lenghOfQuote; i++)
        {
          //cout<<quote[l][i];
        }
          //out<<endl;
    }

}

//*********************************************
//* RenderToDisplay()                       *
//*********************************************

void RenderToDisplay()
{
    int l,lenghOfQuote, i;

    glTranslatef(0.0, -100, UpwardsScrollVelocity);
    glRotatef(-20, 1.0, 0.0, 0.0);
    glScalef(0.1, 0.1, 0.1);



    for(  l=0;l<numberOfQuotes;l++)
    {
        lenghOfQuote = (int)strlen(quote[l]);
        glPushMatrix();
        glTranslatef(-(lenghOfQuote*37), -(l*200), 0.0);
        for (i = 0; i < lenghOfQuote; i++)
        {
            glColor3f((UpwardsScrollVelocity/10)+300+(l*10),(UpwardsScrollVelocity/10)+300+(l*10),0.0);
            glutStrokeCharacter(GLUT_STROKE_ROMAN, quote[l][i]);
        }
        glPopMatrix();
    }

}
//*********************************************
//* glutDisplayFunc(myDisplayFunction);       *
//*********************************************

void myDisplayFunction(void)
{
  glClear(GL_COLOR_BUFFER_BIT);
  glLoadIdentity();
  gluLookAt(0.0, 30.0, 100.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
  RenderToDisplay();
  glutSwapBuffers();
}
//*********************************************
//* glutReshapeFunc(reshape);               *
//*********************************************

void reshape(int w, int h)
{
  glViewport(0, 0, w, h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(60, 1.0, 1.0, 3200);
  glMatrixMode(GL_MODELVIEW);
}

//*********************************************
//* int main()                                *
//*********************************************


int main()
{
    strcpy(quote[0],"Luke, I am your father!.");
    strcpy(quote[1],"Obi-Wan has taught you well. ");
    strcpy(quote[2],"The force is strong with this one. ");
    strcpy(quote[3],"Alert all commands. Calculate every possible destination along their last known trajectory. ");
    strcpy(quote[4],"The force is with you, young Skywalker, but you are not a Jedi yet.");
    numberOfQuotes=5;

    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(800, 400);
    glutCreateWindow("StarWars scroller");
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glLineWidth(3);

    glutDisplayFunc(myDisplayFunction);
    glutReshapeFunc(reshape);
    glutIdleFunc(timeTick);
    glutMainLoop();

    return 0;
}

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

I was facing a similar issue. Actually the command is :

java -version and not java --version.

You will get output something like this:

java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

add new element in laravel collection object

If you want to add item to the beginning of the collection you can use prepend:

$item->prepend($product, 'key');

Scale image to fit a bounding box

This helped me:

.img-class {
  width: <img width>;
  height: <img height>;
  content: url('/path/to/img.png');
}

Then on the element (you can use javascript or media queries to add responsiveness):

<div class='img-class' style='transform: scale(X);'></div>

Hope this helps!

npm install won't install devDependencies

So the way I got around this was in the command where i would normally run npm install or npm ci, i added NODE_ENV=build, and then NODE_ENV=production after the command, so my entire command came out to:

RUN NODE_ENV=build && npm ci && NODE_ENV=production

So far I haven't had any bad reactions, and my development dependencies which are used for building the application all worked / loaded correctly.

I find this to be a better solution than adding an additional command like npm install --only=dev because it takes less time, and enables me to use the npm ci command, which is faster and specifically designed to be run inside CI tools / build scripts. (See npi-ci documentation for more information on it)

How To Make Circle Custom Progress Bar in Android

Rest of code

Code of utils methods:

public static int[] resourcesIDsToColors(Context context, int[] resIDs){
            int[] colors = new int[resIDs.length];
            for(int i=0; i < resIDs.length; i++){
                colors[i] = ActivityCompat.getColor(context, resIDs[i]);
            }
            return colors;
        }
    
    public static void setSubClassFieldIntValue(Object objField, Class<?> superClass, String subName, String fieldName, int fieldValue){
            Class<?> subClass = getSubClass(superClass, subName);
            if(subClass != null) {
                Field field = getClassField(subClass, fieldName);
                if (field != null) {
                    setFieldValue(objField, field, fieldValue);
                }
            }
        }
    
        public static Class<?> getSubClass(Class<?> superClass, String subName){
            Class<?>[] classes = superClass.getDeclaredClasses();
            if(classes != null && classes.length > 0){
                for(Class<?> clss : classes){
                    if(clss.getSimpleName().equals(subName)){
                        return clss;
                    }
                }
            }
            return null;
        }
    
        public static Field getClassField(Class<?> clss, String fieldName){
            try {
                Field field = clss.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field;
            } catch (NoSuchFieldException nsfE) {
                Log.e(TAG, nsfE.getMessage());
            } catch (SecurityException sE){
                Log.e(TAG, sE.getMessage());
            } catch (Exception e){
                Log.e(TAG, e.getMessage());
            }
            return null;
        }
    
    public static int[][] arrayToMatrix(int[] array, int numColumns){
            int numRows = array.length / numColumns;
            int[][] matrix = new int[numRows][numColumns];
            int nElemens = array.length;
            for(int i=0; i < nElemens; i++){
                matrix[i / numColumns][i % numColumns] = array[i];
            }
            return matrix;
        }

public static int[] matrixToArray(int[][] matrix){
        /** [+] Square matrix of order n        ->      A matrix with n rows and n columns, same number of rows and columns.
         *  [+] Matrix rows & columns number annotations:
         *          matrix[rows][columns]           matrix (rows x columns)         matrix rows, columns        rows by columns matrix
         * **/
        int numRows = matrix.length;
        int[] arr = new int[]{};
        for(int i=0; i < numRows; i++){
            int numColumns = matrix[i].length;
            int[] row = new int[numColumns];
            for(int j=0; j < numColumns; j++){
                row[j] = matrix[i][j];
            }
            arr = ArrayUtils.addAll(arr, row);
        }
        return arr;
    }

Code of default layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@color/transparent">
    <LinearLayout
        android:id="@+id/layout_progress_bar_only"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone">
        <android.support.constraint.ConstraintLayout
            android:id="@+id/dpb_constraint_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <me.zhanghai.android.materialprogressbar.MaterialProgressBar
                android:id="@+id/dpb_progress_bar"
                android:layout_width="@dimen/pbd_progressbar_width_2"
                android:layout_height="@dimen/pbd_progressbar_height_2"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"/>
            <LinearLayout
                android:id="@+id/dpb_text_container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"/>
        </android.support.constraint.ConstraintLayout>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/layout_progress_bar_and_msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone"
        style="@style/PBDTextualMainLayoutStyle">
        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardElevation="@dimen/pbd_textual_card_elevation">
            <TextView
                android:id="@+id/pbd_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/PBDTextualTitle"/>
        </android.support.v7.widget.CardView>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/pbd_textual_main_layout_height"
            android:orientation="horizontal">
            <android.support.v7.widget.CardView
                android:layout_width="@dimen/pbd_textual_progressbar_width"
                android:layout_height="@dimen/pbd_textual_progressbar_height">
                <me.zhanghai.android.materialprogressbar.MaterialProgressBar
                    android:id="@+id/dpb_progress_bar_and_msg"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    style="@style/PBDProgressBarStyle"/>
            </android.support.v7.widget.CardView>
            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="@dimen/pbd_textual_msg_container_height">
                <TextView
                    android:id="@+id/dpb_progress_msg"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    style="@style/PBDTextualProgressMsgStyle"/>
            </android.support.v7.widget.CardView>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Progress Bar Rings:

<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:fromDegrees="300"
            android:toDegrees="660">
            <shape
                android:shape="ring"
                android:useLevel="false">
                <gradient
                    android:type="sweep"/>
            </shape>
        </rotate>
    </item>
    <item>
        <rotate
            android:fromDegrees="210"
            android:toDegrees="570">
            <shape
                android:shape="ring"
                android:useLevel="false">
                <gradient
                    android:type="sweep"/>
            </shape>
        </rotate>
    </item>
    <item>
        <rotate
            android:fromDegrees="120"
            android:toDegrees="480">
            <shape
                android:shape="ring"
                android:useLevel="false">
                <gradient
                    android:type="sweep"
                    android:startColor="#00000000"
                    android:centerColor="#00000000"/>
            </shape>
        </rotate>
    </item>
    <item>
        <rotate
            android:fromDegrees="30"
            android:toDegrees="390">
            <shape
                android:shape="ring"
                android:useLevel="false">
                <solid android:color="#000000"/>
                <gradient
                    android:type="sweep"/>
            </shape>
        </rotate>
    </item>
</layer-list>

Dimens Resources:

 <!-- ProgressBarDialog Dimens (Normal & Textual Versions) -->
        <dimen name="pbd_window_width">250dp</dimen>
        <dimen name="pbd_window_height">250dp</dimen>
        <dimen name="pbd_progressbar_width_1">250dp</dimen>
        <dimen name="pbd_progressbar_height_1">250dp</dimen>
        <dimen name="pbd_progressbar_width_2">400dp</dimen>
        <dimen name="pbd_progressbar_height_2">400dp</dimen>
        <dimen name="pbd_textual_window_height">170dp</dimen>
        <dimen name="pbd_textual_main_layout_height">150dp</dimen>
        <dimen name="pbd_textual_progressbar_width">150dp</dimen>
        <dimen name="pbd_textual_progressbar_height">150dp</dimen>
        <dimen name="pbd_textual_msg_container_height">150dp</dimen>
        <dimen name="pbd_textual_main_layout_margin_horizontal">50dp</dimen>
        <dimen name="pbd_textual_main_layout_padding_horizontal">5dp</dimen>
        <dimen name="pbd_textual_main_layout_padding_bottom">15dp</dimen>
        <dimen name="pbd_textual_title_padding">4dp</dimen>
        <dimen name="pbd_textual_msg_container_margin">3dp</dimen>
        <dimen name="pbd_textual_msg_container_padding">3dp</dimen>
        <dimen name="pbd_textual_card_elevation">15dp</dimen>
        <dimen name="pbd_textual_progressmsg_padding_start">10dp</dimen>
        <dimen name="pbd_inner_radius_30dp">30dp</dimen>
        <dimen name="pbd_inner_radius_60dp">60dp</dimen>
        <dimen name="pbd_inner_radius_90dp">90dp</dimen>
        <dimen name="pbd_inner_radius_120dp">120dp</dimen>
        <dimen name="pbd_thickness_40dp">40dp</dimen>
        <dimen name="pbd_thickness_30dp">30dp</dimen>
        <dimen name="pbd_thickness_25dp">25dp</dimen>
        <dimen name="pbd_thickness_20dp">20dp</dimen>
        <dimen name="pbd_thickness_15dp">15dp</dimen>
        <dimen name="pbd_thickness_10dp">10dp</dimen>

Styles Resources:

<!-- PROGRESS BAR DIALOG STYLES -->
    <style name="PBDCenterTextStyleWhite">
        <item name="android:textAlignment">center</item>
        <item name="android:textAppearance">?android:attr/textAppearanceLarge</item>
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">@color/material_white</item>
        <item name="android:layout_gravity">center</item>
        <item name="android:gravity">center</item>
    </style>

    <style name="PBDTextualTitle">
        <item name="android:textAlignment">viewStart</item>
        <item name="android:textAppearance">?android:attr/textAppearanceLargeInverse</item>
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">@color/colorAccent</item>
        <item name="android:padding">@dimen/pbd_textual_title_padding</item>
        <item name="android:layout_gravity">start</item>
        <item name="android:gravity">center_vertical|start</item>
        <item name="android:background">@color/colorPrimaryDark</item>
    </style>

    <style name="PBDTextualProgressMsgStyle">
        <item name="android:textAlignment">viewStart</item>
        <item name="android:textAppearance">?android:attr/textAppearanceMedium</item>
        <item name="android:textColor">@color/material_black</item>
        <item name="android:textStyle">normal|italic</item>
        <item name="android:paddingStart">@dimen/pbd_textual_progressmsg_padding_start</item>
        <item name="android:layout_gravity">start</item>
        <item name="android:gravity">center_vertical|start</item>
        <item name="android:background">@color/material_yellow_A100</item>
    </style>

    <style name="PBDTextualMainLayoutStyle">
        <item name="android:paddingLeft">@dimen/pbd_textual_main_layout_padding_horizontal</item>
        <item name="android:paddingRight">@dimen/pbd_textual_main_layout_padding_horizontal</item>
        <item name="android:paddingBottom">@dimen/pbd_textual_main_layout_padding_bottom</item>
        <item name="android:background">@color/colorPrimaryDark</item>
    </style>

    <style name="PBDProgressBarStyle">
        <item name="android:layout_gravity">center</item>
        <item name="android:gravity">center</item>
    </style>

What LaTeX Editor do you suggest for Linux?

In Linux it's more likely that extensions to existing editors will be more mature than entirely new ones. Thus, the two stalwarts (vi and emacs) are likely to have packages available.

EDIT: Indeed, here's the vi one:

http://vim-latex.sourceforge.net/

... and here's the emacs one:

http://www.gnu.org/software/auctex/

I have to say, I'm a vi man, but the emacs package looks rather spiffy: it includes the ability to embed preview images of formulas in your emacs buffer.

Disable Tensorflow debugging information

for tensorflow 2.1.0, following code works fine.

import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

Rename Excel Sheet with VBA Macro

Suggest you add handling to test if any of the sheets to be renamed already exist:

Sub Test()

Dim ws As Worksheet
Dim ws1 As Worksheet
Dim strErr As String

On Error Resume Next
For Each ws In ActiveWorkbook.Sheets
Set ws1 = Sheets(ws.Name & "_v1")
    If ws1 Is Nothing Then
        ws.Name = ws.Name & "_v1"
    Else
         strErr = strErr & ws.Name & "_v1" & vbNewLine
    End If
Set ws1 = Nothing
Next
On Error GoTo 0

If Len(strErr) > 0 Then MsgBox strErr, vbOKOnly, "these sheets already existed"

End Sub

PHP 7: Missing VCRUNTIME140.dll

I had same problem when installing Robot Framework 2.9.2 using the Windows installer version on Windows 7.

I could solve it installing the VC14 builds require to have the "Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed" from Microsoft website.

XPath: difference between dot and text()

There is big difference between dot (".") and text() :-

  • The dot (".") in XPath is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element, attribute, or text node) or an atomic value (such as a string, number, or boolean). While text() refers to match only element text which is in string form.

  • The dot (".") notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath text() function.

For an example :-

<a href="something.html">
  <img src="filename.gif">
  link
</a>

Here if you want to find anchor a element by using text link, you need to use dot ("."). Because if you use //a[contains(.,'link')] it finds the anchor a element but if you use //a[contains(text(),'link')] the text() function does not seem to find it.

Hope it will help you..:)

How to convert object to Dictionary<TKey, TValue> in C#?

Another option is to use NewtonSoft.JSON.

var dictionary = JObject.FromObject(anObject).ToObject<Dictionary<string, object>>();

Truncate Two decimal places without rounding

would this work for you?

Console.Write(((int)(3.4679999999*100))/100.0);

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I have the same problem and the solution was uncheck the "use ports 80 and 443" on skype advanced configuration!

What's the best strategy for unit-testing database-driven applications?

I've actually used your first approach with quite some success, but in a slightly different ways that I think would solve some of your problems:

  1. Keep the entire schema and scripts for creating it in source control so that anyone can create the current database schema after a check out. In addition, keep sample data in data files that get loaded by part of the build process. As you discover data that causes errors, add it to your sample data to check that errors don't re-emerge.

  2. Use a continuous integration server to build the database schema, load the sample data, and run tests. This is how we keep our test database in sync (rebuilding it at every test run). Though this requires that the CI server have access and ownership of its own dedicated database instance, I say that having our db schema built 3 times a day has dramatically helped find errors that probably would not have been found till just before delivery (if not later). I can't say that I rebuild the schema before every commit. Does anybody? With this approach you won't have to (well maybe we should, but its not a big deal if someone forgets).

  3. For my group, user input is done at the application level (not db) so this is tested via standard unit tests.

Loading Production Database Copy:
This was the approach that was used at my last job. It was a huge pain cause of a couple of issues:

  1. The copy would get out of date from the production version
  2. Changes would be made to the copy's schema and wouldn't get propagated to the production systems. At this point we'd have diverging schemas. Not fun.

Mocking Database Server:
We also do this at my current job. After every commit we execute unit tests against the application code that have mock db accessors injected. Then three times a day we execute the full db build described above. I definitely recommend both approaches.

how to remove the first two columns in a file using shell (awk, sed, whatever)

You can use sed:

sed 's/^[^ ][^ ]* [^ ][^ ]* //'

This looks for lines starting with one-or-more non-blanks, a blank, another set of one-or-more non-blanks and another blank, and deletes the matched material, aka the first two fields. The [^ ][^ ]* is marginally shorter than the equivalent but more explicit [^ ]\{1,\} notation, and the second might run into issues with GNU sed (though if you use --posix as an option, even GNU sed can't screw it up). OTOH, if the character class to be repeated was more complex, the numbered notation wins for brevity. It is easy to extend this to handle 'blank or tab' as separator, or 'multiple blanks' or 'multiple blanks or tabs'. It could also be modified to handle optional leading blanks (or tabs) before the first field, etc.

For awk and cut, see Sampson-Chen's answer. There are other ways to write the awk script, but they're not materially better than the answer given. Note that you might need to set the field separator explicitly (-F" ") in awk if you do not want tabs treated as separators, or you might have multiple blanks between fields. The POSIX standard cut does not support multiple separators between fields; GNU cut has the useful but non-standard -i option to allow for multiple separators between fields.

You can also do it in pure shell:

while read junk1 junk2 residue
do echo "$residue"
done < in-file > out-file

Is there an equivalent for var_dump (PHP) in Javascript?

A lot of modern browsers support the following syntax:

JSON.stringify(myVar);

How can I install Visual Studio Code extensions offline?

All these suggestions are great, but kind of painful to follow because executing the code to construct the URL or constructing that crazy URL by hand is kind of annoying...

So, I threw together a quick web app to make things easier. Just paste the URL of the extension you want and out comes out the download of your extension already properly named: publisher-extension-version.vsix.

Hope someone finds it helpful: http://vscode-offline.herokuapp.com/

How do check if a PHP session is empty?

I would use isset and empty:

session_start();
if(isset($_SESSION['blah']) && !empty($_SESSION['blah'])) {
   echo 'Set and not empty, and no undefined index error!';
}

array_key_exists is a nice alternative to using isset to check for keys:

session_start();
if(array_key_exists('blah',$_SESSION) && !empty($_SESSION['blah'])) {
    echo 'Set and not empty, and no undefined index error!';
}

Make sure you're calling session_start before reading from or writing to the session array.

How do you get a directory listing in C?

There is no standard C (or C++) way to enumerate files in a directory.

Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

It's a table-valued function, but you're using it as a scalar function.

Try:

where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)

But... also consider changing your function into an inline TVF, as it'll perform better.

Copy/Paste from Excel to a web page

The same idea as Tatu(thanks I'll need it soon in our project), but with a regular expression.
Which may be quicker for large dataset.

<html>
<head>
    <title>excelToTable</title>
    <script src="../libs/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
    <textarea>a1    a2  a3
b1  b2  b3</textarea>
    <div></div>
    <input type="button" onclick="convert()" value="convert"/>
    <script>
        function convert(){
            var xl = $('textarea').val();
            $('div').html( 
                '<table><tr><td>' + 
                xl.replace(/\n+$/i, '').replace(/\n/g, '</tr><tr><td>').replace(/\t/g, '</td><td>') + 
                '</tr></table>'
            )
        }
    </script>
</body>
</html>

How to simulate target="_blank" in JavaScript

This might help you to open all page links:

$(".myClass").each(
     function(i,e){
        window.open(e, '_blank');
     }
);

It will open every <a href="" class="myClass"></a> link items to another tab like you would had clicked each one.

You only need to paste it to browser console. jQuery framework required

mySQL select IN range

You can't, but you can use BETWEEN

SELECT job FROM mytable WHERE id BETWEEN 10 AND 15

Note that BETWEEN is inclusive, and will include items with both id 10 and 15.

If you do not want inclusion, you'll have to fall back to using the > and < operators.

SELECT job FROM mytable WHERE id > 10 AND id < 15

Regular Expressions and negating a whole character group

abc(?!def) will match abc not followed by def. So it'll match abce, abc, abck, etc. what if I want neither def nor xyz will it be abc(?!(def)(xyz)) ???

I had the same question and found a solution:

abc(?:(?!def))(?:(?!xyz))

These non-counting groups are combined by "AND", so it this should do the trick. Hope it helps.

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

d = dict.fromkeys(a, 0)

a is the list, 0 is the default value. Pay attention not to set the default value to some mutable object (i.e. list or dict), because it will be one object used as value for every key in the dictionary (check here for a solution for this case). Numbers/strings are safe.

Getting all types in a namespace via reflection

Get all classes by part of Namespace name in just one row:

var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(@"..your namespace...")).ToList();

ASP.NET MVC Conditional validation

I had the same problem yesterday but I did it in a very clean way which works for both client side and server side validation.

Condition: Based on the value of other property in the model, you want to make another property required. Here is the code

public class RequiredIfAttribute : RequiredAttribute
{
    private String PropertyName { get; set; }
    private Object DesiredValue { get; set; }

    public RequiredIfAttribute(String propertyName, Object desiredvalue)
    {
        PropertyName = propertyName;
        DesiredValue = desiredvalue;
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        Object instance = context.ObjectInstance;
        Type type = instance.GetType();
        Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
        if (proprtyvalue.ToString() == DesiredValue.ToString())
        {
            ValidationResult result = base.IsValid(value, context);
            return result;
        }
        return ValidationResult.Success;
    }
}

Here PropertyName is the property on which you want to make your condition DesiredValue is the particular value of the PropertyName (property) for which your other property has to be validated for required

Say you have the following

public class User
{
    public UserType UserType { get; set; }

    [RequiredIf("UserType", UserType.Admin, ErrorMessageResourceName = "PasswordRequired", ErrorMessageResourceType = typeof(ResourceString))]
    public string Password
    {
        get;
        set;
    }
}

At last but not the least , register adapter for your attribute so that it can do client side validation (I put it in global.asax, Application_Start)

 DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),typeof(RequiredAttributeAdapter));

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

nchar requires more space than nvarchar.

eg,

A nchar(100) will always store 100 characters even if you only enter 5, the remaining 95 chars will be padded with spaces. Storing 5 characters in a nvarchar(100) will save 5 characters.

What are the differences between type() and isinstance()?

The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because isinstance()'s second parameter may be a tuple:

if isinstance(b, (str, unicode)):
    do_something_else()

or, using the basestring abstract class:

if isinstance(b, basestring):
    do_something_else()

Why is it not advisable to have the database and web server on the same machine?

  1. Security. Your web server lives in a DMZ, accessible to the public internet and taking untrusted input from anonymous users. If your web server gets compromised, and you've followed least privilege rules in connecting to your DB, the maximum exposure is what your app can do through the database API. If you have a business tier in between, you have one more step between your attacker and your data. If, on the other hand, your database is on the same server, the attacker now has root access to your data and server.
  2. Scalability. Keeping your web server stateless allows you to scale your web servers horizontally pretty much effortlessly. It is very difficult to horizontally scale a database server.
  3. Performance. 2 boxes = 2 times the CPU, 2 times the RAM, and 2 times the spindles for disk access.

All that being said, I can certainly see reasonable cases that none of those points really matter.

node.js hash string?

Take a look at crypto.createHash(algorithm)

var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');

var md5sum = crypto.createHash('md5');

var s = fs.ReadStream(filename);
s.on('data', function(d) {
  md5sum.update(d);
});

s.on('end', function() {
  var d = md5sum.digest('hex');
  console.log(d + '  ' + filename);
});

How do I change the figure size for a seaborn plot?

In addition to elz answer regarding "figure level" methods that return multi-plot grid objects it is possible to set the figure height and width explicitly (that is without using aspect ratio) using the following approach:

import seaborn as sns 

g = sns.catplot(data=df, x='xvar', y='yvar', hue='hue_bar')
g.fig.set_figwidth(8.27)
g.fig.set_figheight(11.7)

Laravel Eloquent ORM Transactions

You can do this:

DB::transaction(function() {
      //
});

Everything inside the Closure executes within a transaction. If an exception occurs it will rollback automatically.

How to SELECT a dropdown list item by value programmatically

Ian Boyd (above) had a great answer -- Add this to Ian Boyd's class "WebExtensions" to select an item in a dropdownlist based on text:

/// <summary>
/// Selects the item in the list control that contains the specified text, if it exists.
/// </summary>
/// <param name="dropDownList"></param>
/// <param name="selectedText">The text of the item in the list control to select</param>
/// <returns>Returns true if the value exists in the list control, false otherwise</returns>
public static Boolean SetSelectedText(this DropDownList dropDownList, String selectedText)
{
    ListItem selectedListItem = dropDownList.Items.FindByText(selectedText);
    if (selectedListItem != null)
    {
        selectedListItem.Selected = true;
        return true;
    }
    else
        return false;
}

To call it:

WebExtensions.SetSelectedText(MyDropDownList, "MyValue");

Unknown version of Tomcat was specified in Eclipse

Having installed tomcat with brew the solution for me was:

sudo chmod -R 777 /usr/local/Cellar/tomcat/<your_version>

Failed to load AppCompat ActionBar with unknown error in android studio

Method 1:

Locate /res/values/styles.xml

Change

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

To

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

Method 2:

Modify template file(locate: android-studio/plugins/android/lib/templates/gradle-projects/NewAndroidModule/root/res/values/styles.xml.ftl)

Change

backwardsCompatibility!true>Theme.AppCompat<#else><#if

To

backwardsCompatibility!true>Base.Theme.AppCompat<#else><#if

Watch Solution On YouTube

Solution

Turn a number into star rating display using jQuery and CSS

If you only have to support modern browsers, you can get away with:

  • No images;
  • Mostly static css;
  • Nearly no jQuery or Javascript;

You only need to convert the number to a class, e.g. class='stars-score-50'.

First a demo of "rendered" markup:

_x000D_
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: gold;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
Within block level elements:_x000D_
_x000D_
<div><span class="stars-container stars-0">?????</span></div>_x000D_
<div><span class="stars-container stars-10">?????</span></div>_x000D_
<div><span class="stars-container stars-20">?????</span></div>_x000D_
<div><span class="stars-container stars-30">?????</span></div>_x000D_
<div><span class="stars-container stars-40">?????</span></div>_x000D_
<div><span class="stars-container stars-50">?????</span></div>_x000D_
<div><span class="stars-container stars-60">?????</span></div>_x000D_
<div><span class="stars-container stars-70">?????</span></div>_x000D_
<div><span class="stars-container stars-80">?????</span></div>_x000D_
<div><span class="stars-container stars-90">?????</span></div>_x000D_
<div><span class="stars-container stars-100">?????</span></div>_x000D_
_x000D_
<p>Or use it in a sentence: <span class="stars-container stars-70">?????</span> (cool, huh?).</p>
_x000D_
_x000D_
_x000D_

Then a demo that uses a wee bit of code:

_x000D_
_x000D_
$(function() {_x000D_
  function addScore(score, $domElement) {_x000D_
    $("<span class='stars-container'>")_x000D_
      .addClass("stars-" + score.toString())_x000D_
      .text("?????")_x000D_
      .appendTo($domElement);_x000D_
  }_x000D_
_x000D_
  addScore(70, $("#fixture"));_x000D_
});
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: gold;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
Generated: <div id="fixture"></div>
_x000D_
_x000D_
_x000D_

The biggest downsides of this solution are:

  1. You need the stars inside the element to generate correct width;
  2. There's no semantic markup, e.g. you'd prefer the score as text inside the element;
  3. It only allows for as many scores as you'll have classes (because we can't use Javascript to set a precise width on a pseudo-element).

To fix this the solution above can be easily tweaked. The :before and :after bits need to become actual elements in the DOM (so we need some JS for that).

The latter is left as an excercise for the reader.

How to compare two dates in php

Don't know what your problem is but:

function date_compare($d1, $d2)
{
    $d1 = explode('_', $d1);
    $d2 = explode('_', $d2);
    
    $d1 = array_reverse($d1);
    $d2 = array_reverse($d2);
    
    if (strtotime(implode('-', $d1)) > strtotime(implode('-', $d2)))
    {
        return $d2;
    }
    else
    {
        return $d1;
    }
}

Char array to hex string C++

Here is something:

char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

for( int i = data; i < data_length; ++i )
{
    char const byte = data[i];

    string += hex_chars[ ( byte & 0xF0 ) >> 4 ];
    string += hex_chars[ ( byte & 0x0F ) >> 0 ];
}

How to choose an AWS profile when using boto3 to connect to CloudFront

This section of the boto3 documentation is helpful.

Here's what worked for me:

session = boto3.Session(profile_name='dev')
client = session.client('cloudfront')

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Executing a batch script on Windows shutdown

Well, its an easy way of doing some registry changes: I tried this on 2008 r2 and 2016 servers.

Things need to be done:

  1. Create a text file "regedit.txt"
  2. Paste the following code in it:
Windows Registry Editor Version 5.00 

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown] 

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown]     

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0]  
"GPO-ID"="LocalGPO"    
"SOM-ID"="Local"    
"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"    
"DisplayName"="Local Group Policy"    
"GPOName"="Local Group Policy"    

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0\0]    
"Script"="terminate_script.bat"    
"Parameters"=""    
"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00    

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0]
"GPO-ID"="LocalGPO"    
"SOM-ID"="Local"    
"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"    
"DisplayName"="Local Group Policy"    
"GPOName"="Local Group Policy"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0\0]    
"Script"="terminate_script.bat"    
"Parameters"=""
"IsPowershell"=dword:00000000
"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
  1. Save this file as regedit.reg extension

  2. Run it on any command line using below command:

    regedit.exe /s regedit.reg
    

vertical-align with Bootstrap 3

I ran into the same situation where I wanted to align a few div elements vertically in a row and found that Bootstrap classes col-xx-xx applies style to the div as float: left.

I had to apply the style on the div elements like style="Float:none" and all my div elements started vertically aligned. Here is the working example:

<div class="col-lg-4" style="float:none;">

JsFiddle Link

Just in case someone wants to read more about the float property:

W3Schools - Float

How to capture a list of specific type with mockito

The nested generics-problem can be avoided with the @Captor annotation:

public class Test{

    @Mock
    private Service service;

    @Captor
    private ArgumentCaptor<ArrayList<SomeType>> captor;

    @Before
    public void init(){
        MockitoAnnotations.initMocks(this);
    }

    @Test 
    public void shouldDoStuffWithListValues() {
        //...
        verify(service).doStuff(captor.capture()));
    }
}

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

If youre running wamp update

define("DB_HOST", "localhost");

To your machines ip address (mine is 192.168.0.25);

define("DB_HOST", "192.168.0.25");

You can find it on window by typing ipconfig in your console or ifconfig on mac/linux

Material Design not styling alert dialogs

You can consider this project: https://github.com/fengdai/AlertDialogPro

It can provide you material theme alert dialogs almost the same as lollipop's. Compatible with Android 2.1.

How to force maven update?

You can do effectively from Eclipse IDE. Of course if you are using it.

Project_Name->Maven->Update Project Configuration->Force Update of Snapshots/Releases

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

REPLACE INTO table(column_list) VALUES(value_list);

is a shorter form of

INSERT OR REPLACE INTO table(column_list) VALUES(value_list);

For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.

REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.


This is a work around.. not checked the speed..

INSERT OR IGNORE INTO table (column_list) VALUES(value_list);

followed by

UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'

This method allows a replace to occur without causing a trigger.

Rails 4 Authenticity Token

Add authenticity_token: true to the form tag

How to concatenate items in a list to a single string?

We can specify how we have to join the string. Instead of '-', we can use ' '

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)

Driver executable must be set by the webdriver.ie.driver system property

For spring :

File inputFile = new ClassPathResource("\\chrome\\chromedriver.exe").getFile();
System.setProperty("webdriver.chrome.driver",inputFile.getCanonicalPath());

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

Error Code: 1005. Can't create table '...' (errno: 150)

I had a similar error. The problem had to do with the child and parent table not having the same charset and collation. This can be fixed by appending ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;

CREATE TABLE IF NOT EXISTS `country` (`id` INT(11) NOT NULL AUTO_INCREMENT,...) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;

... on the SQL statement means that there is some missing code.

Remove Item in Dictionary based on Value

Here is a method you can use:

    public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
    {
        foreach (var key in dictionary.Where(
                kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                Select(x => x.Key).ToArray())
            dictionary.Remove(key);
    }

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

There is some official documentation on that point: Best Practices for Writing Dockerfiles

Because image size matters, using ADD to fetch packages from remote URLs is strongly discouraged; you should use curl or wget instead. That way you can delete the files you no longer need after they've been extracted and you won't have to add another layer in your image.

RUN mkdir -p /usr/src/things \
  && curl -SL http://example.com/big.tar.gz \
    | tar -xJC /usr/src/things \
  && make -C /usr/src/things all

For other items (files, directories) that do not require ADD’s tar auto-extraction capability, you should always use COPY.

DISABLE the Horizontal Scroll

If you want to disable horizontal scrolling over the entire screen width, use this code.

_x000D_
_x000D_
element {_x000D_
  max-width: 100vw;_x000D_
  overflow-x: hidden;_x000D_
}
_x000D_
_x000D_
_x000D_

This works better than "100%" because it ignores the parent width and instead uses the viewport.

How can I pass command-line arguments to a Perl program?

You pass them in just like you're thinking, and in your script, you get them from the array @ARGV. Like so:

my $numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";

foreach my $argnum (0 .. $#ARGV) {

   print "$ARGV[$argnum]\n";

}

From here.

How to set background image of a view?

You can set multiple background image in every view using custom method as below.

make plist for every theam with background image name and other color

#import <Foundation/Foundation.h>
@interface ThemeManager : NSObject
@property (nonatomic,strong) NSDictionary*styles;
+ (ThemeManager *)sharedManager;
-(void)selectTheme;
 @end

             #import "ThemeManager.h"

            @implementation ThemeManager
            @synthesize styles;
            + (ThemeManager *)sharedManager
            {
                static ThemeManager *sharedManager = nil;
                if (sharedManager == nil)
                {
                    sharedManager = [[ThemeManager alloc] init];
                }
                [sharedManager selectTheme];
                return sharedManager;
            }
            - (id)init
            {
                if ((self = [super init]))
                {

                }
                return self;
            }
            -(void)selectTheme{
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *themeName = [defaults objectForKey:@"AppTheme"] ?: @"DefaultTheam";

                NSString *path = [[NSBundle mainBundle] pathForResource:themeName ofType:@"plist"];
                self.styles = [NSDictionary dictionaryWithContentsOfFile:path];
            }
            @end

Can use this via

 NSDictionary *styles = [ThemeManager sharedManager].styles;
 NSString *imageName = [styles objectForKey:@"backgroundImage"];
[imgViewBackGround setImage:[UIImage imageNamed:imageName]];

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

I had this problem after installing Crystal Reports for Visual Studio. I solved it by closing all Visual Studio instances and reinstalling Crystal Reports.

How to Consume WCF Service with Android

If I were doing this I would probably use WCF REST on the server and a REST library on the Java/Android client.

How to suppress warnings globally in an R Script

I have replaced the printf calls with calls to warning in the C-code now. It will be effective in the version 2.17.2 which should be available tomorrow night. Then you should be able to avoid the warnings with suppressWarnings() or any of the other above mentioned methods.

suppressWarnings({ your code })

Attach Authorization header for all axios requests

If you use "axios": "^0.17.1" version you can do like this:

Create instance of axios:

// Default config options
  const defaultOptions = {
    baseURL: <CHANGE-TO-URL>,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

Then for any request the token will be select from localStorage and will be added to the request headers.

I'm using the same instance all over the app with this code:

import axios from 'axios';

const fetchClient = () => {
  const defaultOptions = {
    baseURL: process.env.REACT_APP_API_PATH,
    method: 'get',
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // Create instance
  let instance = axios.create(defaultOptions);

  // Set the AUTH token for any request
  instance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
  });

  return instance;
};

export default fetchClient();

Good luck.

Default optional parameter in Swift function

It is little tricky when you try to combine optional parameter and default value for that parameter. Like this,

func test(param: Int? = nil)

These two are completely opposite ideas. When you have an optional type parameter but you also provide default value to it, it is no more an optional type now since it has a default value. Even if the default is nil, swift simply removes the optional binding without checking what the default value is.

So it is always better not to use nil as default value.

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

Whenever I'm testing something with PHP/Curl, I try it from the command line first, figure out what works, and then port my options to PHP.

How to test Spring Data repositories?

With Spring Boot + Spring Data it has become quite easy:

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    MyRepository subject;

    @Test
    public void myTest() throws Exception {
        subject.save(new MyEntity());
    }
}

The solution by @heez brings up the full context, this only bring up what is needed for JPA+Transaction to work. Note that the solution above will bring up a in memory test database given that one can be found on the classpath.

How can I add a string to the end of each line in Vim?

If u want to add Hello world at the end of each line:

:%s/$/HelloWorld/

If you want to do this for specific number of line say, from 20 to 30 use:

:20,30s/$/HelloWorld/

If u want to do this at start of each line then use:

:20,30s/^/HelloWorld/

Eclipse JPA Project Change Event Handler (waiting)

I still have the same issue in Neon.2 My solution is to disable the JPA Configurator.

Open the Eclipse Preferences (not the project prefs!). Go to Maven --> Java EE Integration and disable the JPA Configurator. I also disabled the JAX-RS Configurator and the JSF Configurator.

From that point on the JPA Project Change Event Handler doesn't show up anymore.

Restart Eclipse if the change does not take effect immediately.

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

What you are looking for are all objects that have either a=false or x=5. In Django, | serves as OR operator between querysets:

results = Model.objects.filter(a=false)|Model.objects.filter(x=5)

What does random.sample() method in python do?

random.sample(population, k)

It is used for randomly sampling a sample of length 'k' from a population. returns a 'k' length list of unique elements chosen from the population sequence or set

it returns a new list and leaves the original population unchanged and the resulting list is in selection order so that all sub-slices will also be valid random samples

I am putting up an example in which I am splitting a dataset randomly. It is basically a function in which you pass x_train(population) as an argument and return indices of 60% of the data as D_test.

import random

def randomly_select_70_percent_of_data_from_1_to_length(x_train):
    return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

This helped me. Sharing it for someone who might come up with same issue.

android {
    ....
    defaultConfig {
        ....
        ndk {
            abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
        }
    }
}

How do I auto-hide placeholder text upon focus using css or jquery?

This piece of CSS worked for me:

input:focus::-webkit-input-placeholder {
        color:transparent;

}

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

I know i am probably the only one that will have this problem in this way. but if you deleted the mdf files in the C:/{user}/ directory, you will get this error too. restore it and you are golden

Is it not possible to define multiple constructors in Python?

Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.

def __init__(self, city="Berlin"):
  self.city = city

How to remove Left property when position: absolute?

left:auto;

This will default the left back to the browser default.


So if you have your Markup/CSS as:

<div class="myClass"></div>

.myClass
{
  position:absolute;
  left:0;
}

When setting RTL, you could change to:

<div class="myClass rtl"></div>

.myClass
{
  position:absolute;
  left:0;
}
.myClass.rtl
{
  left:auto;
  right:0;
}

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player); is passing a type as parameter. That's illegal, you need to pass an object.

For example, something like:

player p;
showInventory(p);  

I'm guessing you have something like this:

int main()
{
   player player;
   toDo();
}

which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:

int main()
{
   player p;
   toDo(p);
}

and

std::string toDo(player& p) 
{
    //....
    showInventory(p);
    //....
}

Oracle SQL: Update a table with data from another table

If your table t1 and it's backup t2 have many columns, here's a compact way to do it.

In addition, my related problem was that only some of the columns were modified and many rows had no edits to these columns, so I wanted to leave those alone - basically restore a subset of columns from a backup of the entire table. If you want to just restore all rows, skip the where clause.

Of course the simpler way would be to delete and insert as select, but in my case I needed a solution with just updates.

The trick is that when you do select * from a pair of tables with duplicate column names, the 2nd one will get named _1. So here's what I came up with:

  update (
    select * from t1 join t2 on t2.id = t1.id
    where id in (
      select id from (
        select id, col1, col2, ... from t2
        minus select id, col1, col2, ... from t1
      )
    )
  ) set col1=col1_1, col2=col2_1, ...

How to put img inline with text

Images have display: inline by default.
You might want to put the image inside the paragraph.
<p><img /></p>

Receiving login prompt using integrated windows authentication

I also had the same issue. Tried most of the things found on this and other forums.

Finally was successful after doing a little own RnD.

I went into IIS Settings and then into my website permission options added my Organizations Domain User Group.

Now as all my domain user have been granted the access to that website i did not encounter that issue.

Hope this helps

Error: TypeError: $(...).dialog is not a function

I had a similar problem and in my case, the issue was different (I am using Django templates).

The order of JS was incorrect (I know that's the first thing you check but I was almost sure that that was not the case, but it was). The js calling the dialog was called before jqueryUI library was called.

I am using Django, so was inheriting a template and using {{super.block}} to inherit code from the block as well to the template. I had to move {{super.block}} at the end of the block which solved the issue. The js calling the dialog was declared in the Media class in Django's admin.py. I spent more than an hour to figure it out. Hope this helps someone.

Programmatically get the version number of a DLL

Assembly assembly = Assembly.LoadFrom("MyAssembly.dll");
Version ver = assembly.GetName().Version;

Important: It should be noted that this is not the best answer to the original question. Don't forget to read more on this page.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

What is the difference between <p> and <div>?

They have semantic difference - a <div> element is designed to describe a container of data whereas a <p> element is designed to describe a paragraph of content.

The semantics make all the difference. HTML is a markup language which means that it is designed to "mark up" content in a way that is meaningful to the consumer of the markup. Most developers believe that the semantics of the document are the default styles and rendering that browsers apply to these elements but that is not the case.

The elements that you choose to mark up your content should describe the content. Don't mark up your document based on how it should look - mark it up based on what it is.

If you need a generic container purely for layout purposes then use a <div>. If you need an element to describe a paragraph of content then use a <p>.

Note: It is important to understand that both <div> and <p> are block-level elements which means that most browsers will treat them in a similar fashion.

Why doesn't height: 100% work to expand divs to the screen height?

Try to play around also with the calc and overflow functions

.myClassName {
    overflow: auto;
    height: calc(100% - 1.5em);
}

Input button target="_blank" isn't causing the link to load in a new window/tab

The formtarget attribute is only used for buttons with type="submit".

That is from this reference.

Here is an answer using JavaScript:

<input type="button" onClick="openNewTab()" value="facebook">

<script type="text/javascript">
    function openNewTab() {
        window.open("http://www.facebook.com/");
    }
</script>

What is difference between monolithic and micro kernel?

Monolithic kernel

All the parts of a kernel like the Scheduler, File System, Memory Management, Networking Stacks, Device Drivers, etc., are maintained in one unit within the kernel in Monolithic Kernel

Advantages

•Faster processing

Disadvantages

•Crash Insecure •Porting Inflexibility •Kernel Size explosion

Examples •MS-DOS, Unix, Linux

Micro kernel

Only the very important parts like IPC(Inter process Communication), basic scheduler, basic memory handling, basic I/O primitives etc., are put into the kernel. Communication happen via message passing. Others are maintained as server processes in User Space

Advantages

•Crash Resistant, Portable, Smaller Size

Disadvantages

•Slower Processing due to additional Message Passing

Examples •Windows NT

Open a local HTML file using window.open in Chrome

window.location.href = 'file://///fileserver/upload/Old_Upload/05_06_2019/THRESHOLD/BBH/Look/chrs/Delia';

Nothing Worked for me.

How to group dataframe rows into list in pandas groupby

Use any of the following groupby and agg recipes.

# Setup
df = pd.DataFrame({
  'a': ['A', 'A', 'B', 'B', 'B', 'C'],
  'b': [1, 2, 5, 5, 4, 6],
  'c': ['x', 'y', 'z', 'x', 'y', 'z']
})
df

   a  b  c
0  A  1  x
1  A  2  y
2  B  5  z
3  B  5  x
4  B  4  y
5  C  6  z

To aggregate multiple columns as lists, use any of the following:

df.groupby('a').agg(list)
df.groupby('a').agg(pd.Series.tolist)

           b          c
a                      
A     [1, 2]     [x, y]
B  [5, 5, 4]  [z, x, y]
C        [6]        [z]

To group-listify a single column only, convert the groupby to a SeriesGroupBy object, then call SeriesGroupBy.agg. Use,

df.groupby('a').agg({'b': list})  # 4.42 ms 
df.groupby('a')['b'].agg(list)    # 2.76 ms - faster

a
A       [1, 2]
B    [5, 5, 4]
C          [6]
Name: b, dtype: object

Turning off eslint rule for a specific line

To disable all rules on a specific line:

alert('foo'); // eslint-disable-line

Are there dictionaries in php?

No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?

$array = array(
    "foo" => "bar",
    "bar" => "foo"
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

The following line is allowed with the above array but would give an error if it was a dictionary.

print $array[0]

Python has both arrays and dictionaries.

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

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

Hi,
Are you there?
regards,
Admin
.

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

How to count duplicate rows in pandas dataframe?

None of the existing answers quite offers a simple solution that returns "the number of rows that are just duplicates and should be cut out". This is a one-size-fits-all solution that does:

# generate a table of those culprit rows which are duplicated:
dups = df.groupby(df.columns.tolist()).size().reset_index().rename(columns={0:'count'})

# sum the final col of that table, and subtract the number of culprits:
dups['count'].sum() - dups.shape[0]

What is the difference between "::" "." and "->" in c++

Put very simple :: is the scoping operator, . is the access operator (I forget what the actual name is?), and -> is the dereference arrow.

:: - Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static function.

. - This allows access to a member function on an already created object. For instance, Foo x; x.bar() calls the method bar() on instantiated object x which has type Foo. You can also use this to access public class variables.

-> - Essentially the same thing as . except this works on pointer types. In essence it dereferences the pointer, than calls .. Using this is equivalent to (*ptr).method()

Remove last item from array

You can do it in two way using splice():

  1. arr.splice(-1,1)
  2. arr.splice(arr.length-1,1)

splice(position_to_start_deleting, how_many_data_to_delete) takes two parameter.

position_to_start_deleting : The zero based index from where to start deleting. how_many_data_to_delete : From indicated index, how many consecutive data should be deleted.

You can also remove the last element using pop() as pop() removes the last element from some array.
Use arr.pop()

Returning value from Thread

With small modifications to your code, you can achieve it in a more generic way.

 final Handler responseHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                //txtView.setText((String) msg.obj);
                Toast.makeText(MainActivity.this,
                        "Result from UIHandlerThread:"+(int)msg.obj,
                        Toast.LENGTH_LONG)
                        .show();
            }
        };

        HandlerThread handlerThread = new HandlerThread("UIHandlerThread"){
            public void run(){
                Integer a = 2;
                Message msg = new Message();
                msg.obj = a;
                responseHandler.sendMessage(msg);
                System.out.println(a);
            }
        };
        handlerThread.start();

Solution :

  1. Create a Handler in UI Thread,which is called as responseHandler
  2. Initialize this Handler from Looper of UI Thread.
  3. In HandlerThread, post message on this responseHandler
  4. handleMessgae shows a Toast with value received from message. This Message object is generic and you can send different type of attributes.

With this approach, you can send multiple values to UI thread at different point of times. You can run (post) many Runnable objects on this HandlerThread and each Runnable can set value in Message object, which can be received by UI Thread.

Maven: add a dependency to a jar by relative path

I want the jar to be in a 3rdparty lib in source control, and link to it by relative path from the pom.xml file.

If you really want this (understand, if you can't use a corporate repository), then my advice would be to use a "file repository" local to the project and to not use a system scoped dependency. The system scoped should be avoided, such dependencies don't work well in many situation (e.g. in assembly), they cause more troubles than benefits.

So, instead, declare a repository local to the project:

<repositories>
  <repository>
    <id>my-local-repo</id>
    <url>file://${project.basedir}/my-repo</url>
  </repository>
</repositories>

Install your third party lib in there using install:install-file with the localRepositoryPath parameter:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<myGroup> \ 
                         -DartifactId=<myArtifactId> -Dversion=<myVersion> \
                         -Dpackaging=<myPackaging> -DlocalRepositoryPath=<path>

Update: It appears that install:install-file ignores the localRepositoryPath when using the version 2.2 of the plugin. However, it works with version 2.3 and later of the plugin. So use the fully qualified name of the plugin to specify the version:

mvn org.apache.maven.plugins:maven-install-plugin:2.3.1:install-file \
                         -Dfile=<path-to-file> -DgroupId=<myGroup> \ 
                         -DartifactId=<myArtifactId> -Dversion=<myVersion> \
                         -Dpackaging=<myPackaging> -DlocalRepositoryPath=<path>

maven-install-plugin documentation

Finally, declare it like any other dependency (but without the system scope):

<dependency>
  <groupId>your.group.id</groupId>
  <artifactId>3rdparty</artifactId>
  <version>X.Y.Z</version>
</dependency>

This is IMHO a better solution than using a system scope as your dependency will be treated like a good citizen (e.g. it will be included in an assembly and so on).

Now, I have to mention that the "right way" to deal with this situation in a corporate environment (maybe not the case here) would be to use a corporate repository.

Using "super" in C++

Super (or inherited) is Very Good Thing because if you need to stick another inheritance layer in between Base and Derived, you only have to change two things: 1. the "class Base: foo" and 2. the typedef

If I recall correctly, the C++ Standards committee was considering adding a keyword for this... until Michael Tiemann pointed out that this typedef trick works.

As for multiple inheritance, since it's under programmer control you can do whatever you want: maybe super1 and super2, or whatever.

Can the :not() pseudo-class have multiple arguments?

If you install the "cssnext" Post CSS plugin, then you can safely start using the syntax that you want to use right now.

Using cssnext will turn this:

input:not([type="radio"], [type="checkbox"]) {
  /* css here */
}

Into this:

input:not([type="radio"]):not([type="checkbox"]) {
  /* css here */
}

https://cssnext.github.io/features/#not-pseudo-class

Best way to copy from one array to another

I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];

How to check if Location Services are enabled?

You may use this code to direct users to Settings, where they can enable GPS:

    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
        new AlertDialog.Builder(context)
            .setTitle(R.string.gps_not_found_title)  // GPS not found
            .setMessage(R.string.gps_not_found_message) // Want to enable?
            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    owner.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton(R.string.no, null)
            .show();
    }

ADB.exe is obsolete and has serious performance problems

This might sound normal but I was getting the same error but just updated it and it worked now without any error. I suggests anyone to try for updates first.

Submit a form in a popup, and then close the popup

I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.

First, I utilize the onsubmit event in the form, and pass this to the function to make it easier to deal with this particular form.

<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data"  name="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.

<script type="text/javascript">
  function closeSelf (f) {
     f.submit();
     window.close();
  }
</script>

Hope this helps someone out. Enjoy!


Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin

First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.

<form action="/system/wpacert" method="post" enctype="multipart/form-data"  id="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

    <script>
       $(document).ready(function () {
          $('#certform').ajaxForm(function () {
          window.close();
          });
       });
    </script>

Combating AngularJS executing controller twice

In my case it was because of the url pattern I used

my url was like /ui/project/:parameter1/:parameter2.

I didn't need paramerter2 in all cases of state change. In cases where I didn't need the second parameter my url would be like /ui/project/:parameter1/. And so whenever I had a state change I will have my controller refreshed twice.

The solution was to set parameter2 as empty string and do the state change.

No module named 'pymysql'

If even sudo apt-get install python3-pymysql does not work for you try this:

  • Go to the PyMySQL page and download the zip file.
  • Then, via the terminal, cd to your Downloads folder and extract the folder
  • cd into the newly extracted folder
  • Install the setup.py file with: sudo python3 setup.py install

How to represent a DateTime in Excel

Excel expects dates and times to be stored as a floating point number whose value depends on the Date1904 setting of the workbook, plus a number format such as "mm/dd/yyyy" or "hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" so that the number is displayed to the user as a date / time.

Using SpreadsheetGear for .NET you can do this: worksheet.Cells["A1"].Value = DateTime.Now;

This will convert the DateTime to a double which is the underlying type which Excel uses for a Date / Time, and then format the cell with a default date and / or time number format automatically depending on the value.

SpreadsheetGear also has IWorkbook.DateTimeToNumber(DateTime) and NumberToDateTime(double) methods which convert from .NET DateTime objects to a double which Excel can use.

I would expect XlsIO to have something similar.

Disclaimer: I own SpreadsheetGear LLC

Angular JS update input field after change

Create a directive and put a watch on it.

app.directive("myApp", function(){
link:function(scope){

    function:getTotal(){
    ..do your maths here

    }
    scope.$watch('one', getTotals());
    scope.$watch('two', getTotals());
   }

})

How to get an object's properties in JavaScript / jQuery?

Spotlight.js is a great library for iterating over the window object and other host objects looking for certain things.

// find all "length" properties
spotlight.byName('length');

// or find all "map" properties on jQuery
spotlight.byName('map', { 'object': jQuery, 'path': '$' });

// or all properties with `RegExp` values
spotlight.byKind('RegExp');

// or all properties containing "oo" in their name
spotlight.custom(function(value, key) { return key.indexOf('oo') > -1; });

You'll like it for this.

How to generate a random string in Ruby

I just write a small gem random_token to generate random tokens for most use case, enjoy ~

https://github.com/sibevin/random_token

What is the worst programming language you ever worked with?

Webspeed and SpeedScript.. Just terrible, no explanation :)

var.replace is not a function

You should use toString() Method of java script for the convert into string before because replace method is a string function.

Pivoting rows into columns dynamically in Oracle

To deal with situations where there are a possibility of multiple values (v in your example), I use PIVOT and LISTAGG:

SELECT * FROM
(
  SELECT id, k, v
  FROM _kv 
)
PIVOT 
(
  LISTAGG(v ,',') 
  WITHIN GROUP (ORDER BY k) 
  FOR k IN ('name', 'age','gender','status')
)
ORDER BY id;

Since you want dynamic values, use dynamic SQL and pass in the values determined by running a select on the table data before calling the pivot statement.

How to use a keypress event in AngularJS?

Some example of code that I did for my project. Basically you add tags to your entity. Imagine you have input text, on entering Tag name you get drop-down menu with preloaded tags to choose from, you navigate with arrows and select with Enter:

HTML + AngularJS v1.2.0-rc.3

    <div>
        <form ng-submit="addTag(newTag)">
            <input id="newTag" ng-model="newTag" type="text" class="form-control" placeholder="Enter new tag"
                   style="padding-left: 10px; width: 700px; height: 33px; margin-top: 10px; margin-bottom: 3px;" autofocus
                   data-toggle="dropdown"
                   ng-change="preloadTags()"
                   ng-keydown="navigateTags($event)">
            <div ng-show="preloadedTags.length > 0">
                <nav class="dropdown">
                    <div class="dropdown-menu preloadedTagPanel">
                        <div ng-repeat="preloadedTag in preloadedTags"
                             class="preloadedTagItemPanel"
                             ng-class="preloadedTag.activeTag ? 'preloadedTagItemPanelActive' : '' "
                             ng-click="selectTag(preloadedTag)"
                             tabindex="{{ $index }}">
                            <a class="preloadedTagItem"
                               ng-class="preloadedTag.activeTag ? 'preloadedTagItemActive' : '' "
                               ng-click="selectTag(preloadedTag)">{{ preloadedTag.label }}</a>
                        </div>
                    </div>
                </nav>
            </div>
        </form>
    </div>

Controller.js

$scope.preloadTags = function () {
    var newTag = $scope.newTag;
    if (newTag && newTag.trim()) {
        newTag = newTag.trim().toLowerCase();

        $http(
            {
                method: 'GET',
                url: 'api/tag/gettags',
                dataType: 'json',
                contentType: 'application/json',
                mimeType: 'application/json',
                params: {'term': newTag}
            }
        )
            .success(function (result) {
                $scope.preloadedTags = result;
                $scope.preloadedTagsIndex = -1;
            }
        )
            .error(function (data, status, headers, config) {
            }
        );
    } else {
        $scope.preloadedTags = {};
        $scope.preloadedTagsIndex = -1;
    }
};

function checkIndex(index) {
    if (index > $scope.preloadedTags.length - 1) {
        return 0;
    }
    if (index < 0) {
        return $scope.preloadedTags.length - 1;
    }
    return index;
}

function removeAllActiveTags() {
    for (var x = 0; x < $scope.preloadedTags.length; x++) {
        if ($scope.preloadedTags[x].activeTag) {
            $scope.preloadedTags[x].activeTag = false;
        }
    }
}

$scope.navigateTags = function ($event) {
    if (!$scope.newTag || $scope.preloadedTags.length == 0) {
        return;
    }
    if ($event.keyCode == 40) {  // down
        removeAllActiveTags();
        $scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex + 1);
        $scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
    } else if ($event.keyCode == 38) {  // up
        removeAllActiveTags();
        $scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex - 1);
        $scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
    } else if ($event.keyCode == 13) {  // enter
        removeAllActiveTags();
        $scope.selectTag($scope.preloadedTags[$scope.preloadedTagsIndex]);
    }
};

$scope.selectTag = function (preloadedTag) {
    $scope.addTag(preloadedTag.label);
};

CSS + Bootstrap v2.3.2

.preloadedTagPanel {
    background-color: #FFFFFF;
    display: block;
    min-width: 250px;
    max-width: 700px;
    border: 1px solid #666666;
    padding-top: 0;
    border-radius: 0;
}

.preloadedTagItemPanel {
    background-color: #FFFFFF;
    border-bottom: 1px solid #666666;
    cursor: pointer;
}

.preloadedTagItemPanel:hover {
    background-color: #666666;
}

.preloadedTagItemPanelActive {
    background-color: #666666;
}

.preloadedTagItem {
    display: inline-block;
    text-decoration: none;
    margin-left: 5px;
    margin-right: 5px;
    padding-top: 5px;
    padding-bottom: 5px;
    padding-left: 20px;
    padding-right: 10px;
    color: #666666 !important;
    font-size: 11px;
}

.preloadedTagItem:hover {
    background-color: #666666;
}

.preloadedTagItemActive {
    background-color: #666666;
    color: #FFFFFF !important;
}

.dropdown .preloadedTagItemPanel:last-child {
    border-bottom: 0;
}

How do I execute a bash script in Terminal?

If you are in a directory or folder where the script file is available then simply change the file permission in executable mode by doing

chmod +x your_filename.sh

After that you will run the script by using the following command.

$ sudo ./your_filename.sh

Above the "." represent the current directory. Note! If you are not in the directory where the bash script file is present then you change the directory where the file is located by using

cd Directory_name/write the complete path

command. Otherwise your script can not run.

How to undo a git pull?

Even though the above solutions do work,This answer is for you in case you want to reverse the clock instead of undoing a git pull.I mean if you want to get your exact repo the way it was X Mins back then run the command

git reset --hard branchName@{"X Minutes ago"}

Note: before you actually go ahead and run this command please only try this command if you are sure about the time you want to go back to and heres about my situation.

I was currently on a branch develop, I was supposed to checkout to a new branch and pull in another branch lets say Branch A but I accidentally ran git pull origin B before checking out.

so to undo this change I tried this command

git reset --hard develop@{"10 Minutes ago"}

if you are on windows cmd and get error: unknown switch `e

try adding quotes like this

git reset --hard 'develop@{"10 Minutes ago"}'

How to remove a TFS Workspace Mapping?

Follow these steps to remove mapping from TFS:

  1. Open team explorer
  2. Click Source Control
  3. Right click on you project
  4. Click on Remove Mapping

How to fix "The ConnectionString property has not been initialized"

The connection string is not in AppSettings.

What you're looking for is in:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...

How to prune local tracking branches that do not exist on remote anymore

There doesn't seem to be a safe one-liner, too many edge cases (like a branch having "master" as part of its name, etc). Safest is these steps:

  1. git branch -vv | grep 'gone]' > stale_branches.txt
  2. view the file and remove lines for branches you want to keep (such as master branch!); you don't need to edit the contents of any line
  3. awk '{print $1}' stale_branches.txt | xargs git branch -d

How do I correct this Illegal String Offset?

if ($inputs['type'] == 'attach') {

The code is valid, but it expects the function parameter $inputs to be an array. The "Illegal string offset" warning when using $inputs['type'] means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type' is not suitable.)

So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.

However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type' to 0, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)

You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs); in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:

if (is_array($inputs) && $inputs['type'] == 'attach') {

How to capitalize the first letter of text in a TextView in an Android Application

The accepted answer is good, but if you are using it to get values from a textView in android, it would be good to check if the string is empty. If the string is empty it would throw an exception.

private String capitizeString(String name){
    String captilizedString="";
    if(!name.trim().equals("")){
       captilizedString = name.substring(0,1).toUpperCase() + name.substring(1);
    }
    return captilizedString;
}

Android - how do I investigate an ANR?

my issue with ANR , after much work i found out that a thread was calling a resource that did not exist in the layout, instead of returning an exception , i got ANR ...

Reminder - \r\n or \n\r?

New line depends on your OS:

DOS & Windows: \r\n 0D0A (hex), 13,10 (decimal)
Unix & Mac OS X: \n, 0A, 10
Macintosh (OS 9): \r, 0D, 13

More details here: https://ccrma.stanford.edu/~craig/utility/flip/

When in doubt, use any freeware hex viewer/editor to see how a file encodes its new line.

For me, I use following guide to help me remember: 0D0A = \r\n = CR,LF = carriage return, line feed

Open Facebook Page in Facebook App (if installed) on Android

Okay I modifed @AndroidMechanics Code, because on devices were facebook is disabled the app crashes!

here is the modifed getFacebookUrl:

public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

            boolean activated =  packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
            if(activated){
                if ((versionCode >= 3002850)) { 
                    return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
                } else { 
                    return "fb://page/" + FACEBOOK_PAGE_ID;
                }
            }else{
                return FACEBOOK_URL;
            }
         } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL; 
        }
    }

The only added thing is to look if the app is disabled or not if it is disabled the app will call the webbrowser!

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

In my case,

I was trying to update my model by making a foreign key required, but the database had "null" data in it already in some columns from previously entered data. So every time i run update-database...i got the error.

I SOLVED it by manually deleting from the database all rows that had null in the column i was making required.

What is a 'workspace' in Visual Studio Code?

So, yet again the lesson of not polluting the source tree of a project with artifacts that aren't directly related to that project is being ignored.

There is zero reason for a Visual Studio Code workspace file (workspaces.json) or directory (.vscode) or whatever to be placed in the source tree. It could just as easily have been placed under your user settings.

I thought we figured this out about 20+ years ago, but it seems that some lessons are doomed to be repeated.

"Could not find acceptable representation" using spring-boot-starter-web

If you are using Lombok, make sure it have annotations like @Data or @Getter @Setter in your Response Model class.

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

both answers are is incorrect. it should read:

x-=r;
y-=r;


drawOval(x,y,r*2,r*2);

How to create a jQuery plugin with methods?

The problem with the currently selected answer is that you're not actually creating a new instance of the custom plugin for every element in the selector like you think you're doing... you're actually only creating a single instance and passing in the selector itself as the scope.

View this fiddle for a deeper explanation.

Instead, you'll need to loop through the selector using jQuery.each and instantiate a new instance of the custom plugin for every element in the selector.

Here's how:

(function($) {

    var CustomPlugin = function($el, options) {

        this._defaults = {
            randomizer: Math.random()
        };

        this._options = $.extend(true, {}, this._defaults, options);

        this.options = function(options) {
            return (options) ?
                $.extend(true, this._options, options) :
                this._options;
        };

        this.move = function() {
            $el.css('margin-left', this._options.randomizer * 100);
        };

    };

    $.fn.customPlugin = function(methodOrOptions) {

        var method = (typeof methodOrOptions === 'string') ? methodOrOptions : undefined;

        if (method) {
            var customPlugins = [];

            function getCustomPlugin() {
                var $el          = $(this);
                var customPlugin = $el.data('customPlugin');

                customPlugins.push(customPlugin);
            }

            this.each(getCustomPlugin);

            var args    = (arguments.length > 1) ? Array.prototype.slice.call(arguments, 1) : undefined;
            var results = [];

            function applyMethod(index) {
                var customPlugin = customPlugins[index];

                if (!customPlugin) {
                    console.warn('$.customPlugin not instantiated yet');
                    console.info(this);
                    results.push(undefined);
                    return;
                }

                if (typeof customPlugin[method] === 'function') {
                    var result = customPlugin[method].apply(customPlugin, args);
                    results.push(result);
                } else {
                    console.warn('Method \'' + method + '\' not defined in $.customPlugin');
                }
            }

            this.each(applyMethod);

            return (results.length > 1) ? results : results[0];
        } else {
            var options = (typeof methodOrOptions === 'object') ? methodOrOptions : undefined;

            function init() {
                var $el          = $(this);
                var customPlugin = new CustomPlugin($el, options);

                $el.data('customPlugin', customPlugin);
            }

            return this.each(init);
        }

    };

})(jQuery);

And a working fiddle.

You'll notice how in the first fiddle, all divs are always moved to the right the exact same number of pixels. That is because only one options object exists for all elements in the selector.

Using the technique written above, you'll notice that in the second fiddle, each div is not aligned and is randomly moved (excluding the first div as it's randomizer is always set to 1 on line 89). That is because we are now properly instantiating a new custom plugin instance for every element in the selector. Every element has its own options object and is not saved in the selector, but in the instance of the custom plugin itself.

This means that you'll be able to access the methods of the custom plugin instantiated on a specific element in the DOM from new jQuery selectors and aren't forced to cache them, as you would be in the first fiddle.

For example, this would return an array of all options objects using the technique in the second fiddle. It would return undefined in the first.

$('div').customPlugin();
$('div').customPlugin('options'); // would return an array of all options objects

This is how you would have to access the options object in the first fiddle, and would only return a single object, not an array of them:

var divs = $('div').customPlugin();
divs.customPlugin('options'); // would return a single options object

$('div').customPlugin('options');
// would return undefined, since it's not a cached selector

I'd suggest using the technique above, not the one from the currently selected answer.

Is there a way to override class variables in Java?

This looks like a design flaw.

Remove the static keyword and set the variable for example in the constructor. This way Son just sets the variable to a different value in his constructor.

Function or sub to add new row and data to table

Is this what you are looking for?

Option Explicit

Public Sub addDataToTable(ByVal strTableName As String, ByVal strData As String, ByVal col As Integer)
    Dim lLastRow As Long
    Dim iHeader As Integer

    With ActiveSheet.ListObjects(strTableName)
        'find the last row of the list
        lLastRow = ActiveSheet.ListObjects(strTableName).ListRows.Count
        'shift from an extra row if list has header
        If .Sort.Header = xlYes Then
            iHeader = 1
        Else
            iHeader = 0
        End If
    End With
    'add the data a row after the end of the list
    ActiveSheet.Cells(lLastRow + 1 + iHeader, col).Value = strData
End Sub

It handles both cases whether you have header or not.

How to get Toolbar from fragment?

if you are using custom toolbar or ActionBar and you want to get reference of your toolbar/action bar from Fragments then you need to first get instance of your Main Activity from Fragment's onCreateView Method like below.

MainActivity activity = (MainActivity) getActivity();

then use activity for further implementation like below

ImageView vRightBtn = activity.toolbar.findViewById(R.id.toolbar_right_btn);

Before calling this, you need to initialize your custom toolbar in your MainActivity as below.

First set define your toolbar public like

public Toolbar toolbar;
public ActionBar actionBar;

and in onCreate() Method assign the custom toolbar id

toolbar = findViewById(R.id.custom_toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();

That's It. It will work in Fragment.

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

I could not get any of these solutions to work for me. I had to manually go to every method/class that I got the error on and import it manually. After that everything was fine.

Use Ant for running program with command line arguments

If you do not want to handle separate properties for each possible argument, I suggest you'd use:

<arg line="${args}"/>

You can check if the property is not set using a specific target with an unless attribute and inside do:

<input message="Type the desired command line arguments:" addProperty="args"/>

Putting it all together gives:

<target name="run" depends="compile, input-runargs" description="run the project">
  <!-- You can use exec here, depending on your needs -->
  <java classname="Main">
    <arg line="${args}"/>
  </java>
</target>
<target name="input-runargs" unless="args" description="prompts for command line arguments if necessary">
  <input addProperty="args" message="Type the desired command line arguments:"/>
</target>

You can use it as follows:

ant
ant run
ant run -Dargs='--help'

The first two commands will prompt for the command-line arguments, whereas the latter won't.

Add Favicon with React and Webpack

Adding your favicon simply into to the public folder should do. Make sure the favicon is named as favicon.ico.

A method to count occurrences in a list

public void printsOccurences(List<String> words)
{
    var selectQuery =
        from word in words
        group word by word into g
        select new {Word = g.Key, Count = g.Count()};
    foreach(var word in selectQuery)
        Console.WriteLine($"{word.Word}: {word.Count}");*emphasized text*
}

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

How do you disable the unused variable warnings coming out of gcc?
I'm getting errors out of boost on windows and I do not want to touch the boost code...

You visit Boost's Trac and file a bug report against Boost.

Your application is not responsible for clearing library warnings and errors. The library is responsible for clearing its own warnings and errors.

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

In case of windows if there is any space in path to jdk like ("C:\Program Files\jdk") then it doesn't work, but if we keep jdk in a location which doesn't have space then it works fine like ("C:\jdk")

Working with INTERVAL and CURDATE in MySQL

As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH

Similarly you can do:

NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

Fixing broken UTF-8 encoding

The way is to convert to binary and then to correct encoding

Appending HTML string to the DOM

Performance

AppendChild (E) is more than 2x faster than other solutions on chrome and safari, insertAdjacentHTML(F) is fastest on firefox. The innerHTML= (B) (do not confuse with += (A)) is second fast solution on all browsers and it is much more handy than E and F.

Details

Set up environment (2019.07.10) MacOs High Sierra 10.13.4 on Chrome 75.0.3770 (64-bit), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64-bit)

enter image description here

  • on Chrome E (140k operations per second) is fastest, B (47k) and F (46k) are second, A (332) is slowest
  • on firefox F (94k) is fastest, then B(80k), D (73k), E(64k), C (21k) slowest is A(466)
  • on Safari E(207k) is fastest, then B(89k), F(88k), D(83k), C (25k), slowest is A(509)

You can replay test in your machine here

_x000D_
_x000D_
function A() {    _x000D_
  container.innerHTML += '<p>A: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function B() {    _x000D_
  container.innerHTML = '<p>B: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function C() {    _x000D_
  $('#container').append('<p>C: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
function D() {_x000D_
  var p = document.createElement("p");_x000D_
  p.innerHTML = 'D: Just some <span>text</span> here';_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function E() {    _x000D_
  var p = document.createElement("p");_x000D_
  var s = document.createElement("span"); _x000D_
  s.appendChild( document.createTextNode("text ") );_x000D_
  p.appendChild( document.createTextNode("E: Just some ") );_x000D_
  p.appendChild( s );_x000D_
  p.appendChild( document.createTextNode(" here") );_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function F() {    _x000D_
  container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
This snippet only for show code used in test (in jsperf.com) - it not perform test itself. _x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

How to close Android application?

Copy below code and paste AndroidManifest.xml file in under First Activity Tag.

<activity                        
            android:name="com.SplashActivity"
            android:clearTaskOnLaunch="true" 
            android:launchMode="singleTask"
            android:excludeFromRecents="true">              
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER"
                />
            </intent-filter>
        </activity>     

Also Add this below code in all under Activity Tag in AndroidManifest.xml file

 android:finishOnTaskLaunch="true"

How to reload a page after the OK click on the Alert Page

As the alert method in JavaScript does not return a Boolean or yield the current thread, you must use a different method.

My number one recommendation requires a little CSS experience. You should instead create a div element that is fixed positionally.

Otherwise you could use the confirm() method.

confirm("Successful Message");
window.location.reload();

However, this will add a cancel button. Because the confirm method is not within an if statement though, the cancel button will still refresh the page like you want it.

How to pass arguments to addEventListener listener function?

The following code worked fine for me (firefox):

for (var i=0; i<3; i++) {
   element = new ...   // create your element
   element.counter = i;
   element.addEventListener('click', function(e){
        console.log(this.counter);
        ...            // another code with this element
   }, false);
}

Output:

0
1
2

Java: How to convert String[] to List or Set

It's a old code, anyway, try it:

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class StringArrayTest
{
   public static void main(String[] args)
   {
      String[] words = {"word1", "word2", "word3", "word4", "word5"};

      List<String> wordList = Arrays.asList(words);

      for (String e : wordList)
      {
         System.out.println(e);
      }
    }
}

How to create a new file in unix?

Try > workdirectory/filename.txt

This would:

  • truncate the file if it exists
  • create if it doesn't exist

You can consider it equivalent to:

rm -f workdirectory/filename.txt; touch workdirectory/filename.txt

C - casting int to char and append char to char

You can use itoa function to convert the integer to a string.

You can use strcat function to append characters in a string at the end of another string.

If you want to convert a integer to a character, just do the following -

int a = 65;
char c = (char) a;

Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned in this case (though you may still lose data).

To do a light reading about type conversion, go here.

If you are still having trouble, comment on this answer.

Edit

Go here for a more suitable example of joining characters.

Also some more useful link is given below -

  1. http://www.cplusplus.com/reference/clibrary/cstring/strncat/
  2. http://www.cplusplus.com/reference/clibrary/cstring/strcat/

Second Edit

char msg[200];
int msgLength;
char rankString[200];

........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id

strncat( msg, rankString, (200 - msgLength) );  // msg now contains previous msg + id

// You may loose some portion of id if message length + id string length is greater than 200

Third Edit

Go to this link. Here you will find an implementation of itoa. Use that instead.

Is it possible to cast a Stream in Java 8?

Along the lines of ggovan's answer, I do this as follows:

/**
 * Provides various high-order functions.
 */
public final class F {
    /**
     * When the returned {@code Function} is passed as an argument to
     * {@link Stream#flatMap}, the result is a stream of instances of
     * {@code cls}.
     */
    public static <E> Function<Object, Stream<E>> instancesOf(Class<E> cls) {
        return o -> cls.isInstance(o)
                ? Stream.of(cls.cast(o))
                : Stream.empty();
    }
}

Using this helper function:

Stream.of(objects).flatMap(F.instancesOf(Client.class))
        .map(Client::getId)
        .forEach(System.out::println);

Difference between pre-increment and post-increment in a loop?

It boggles my mind why so may people write the increment expression in for-loop as i++.

In a for-loop, when the 3rd component is a simple increment statement, as in

for (i=0; i<x; i++)  

or

for (i=0; i<x; ++i)   

there is no difference in the resulting executions.

When to use MongoDB or other document oriented database systems?

After two years using MongoDb for a social app, I have witnessed what it really means to live without a SQL RDBMS.

  1. You end up writing jobs to do things like joining data from different tables/collections, something that an RDBMS would do for you automatically.
  2. Your query capabilities with NoSQL are drastically crippled. MongoDb may be the closest thing to SQL but it is still extremely far behind. Trust me. SQL queries are super intuitive, flexible and powerful. MongoDb queries are not.
  3. MongoDb queries can retrieve data from only one collection and take advantage of only one index. And MongoDb is probably one of the most flexible NoSQL databases. In many scenarios, this means more round-trips to the server to find related records. And then you start de-normalizing data - which means background jobs.
  4. The fact that it is not a relational database means that you won't have (thought by some to be bad performing) foreign key constrains to ensure that your data is consistent. I assure you this is eventually going to create data inconsistencies in your database. Be prepared. Most likely you will start writing processes or checks to keep your database consistent, which will probably not perform better than letting the RDBMS do it for you.
  5. Forget about mature frameworks like hibernate.

I believe that 98% of all projects probably are way better with a typical SQL RDBMS than with NoSQL.

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

I encountered this problem when attempint to run my web application as a fat jar rather than from within my IDE (IntelliJ).

This is what worked for me. Simply adding a default profile to the application.properties file.

spring.profiles.active=default

You don't have to use default if you have already set up other specific profiles (dev/test/prod). But if you haven't this is necessary to run the application as a fat jar.

Possible reason for NGINX 499 error codes

In my case, I have setup like

AWS ELB >> ECS(nginx) >> ECS(php-fpm).

I had configured the wrong AWS security group for ECS(php-fpm) service, so Nginx wasn't able to reach out to php-fpm task container. That's why i was getting errors in nginx task log

499 0 - elb-healthchecker/2.0

Health check was configured as to check php-fpm service and confirm it's up and give back a response.

Loop timer in JavaScript

I believe you are looking for setInterval()

Console.log not working at all

Consider a more pragmatic approach to the question of "doing it correctly".

console.log("about to bind scroll fx");

$(window).scroll(function() {

       console.log("scroll bound, loop through div's");

       $('div').each(function(){

If both of those logs output correctly, then its likely the problem exists in your var declaration. To debug that, consider breaking it out into several lines:

var id='#'+$(this).attr('id');

console.log(id);

var off=$(id).offset().top;
var hei=$(id).height();
var winscroll=$(window).scrollTop();
var dif=hei+off-($(window).height());

By doing this, at least during debugging, you may find that the var id is undefined, causing errors throughout the rest of the code. Is it possible some of your div tags do not have id's?

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Yes you can run JavaFX application on iOS, android, desktop, RaspberryPI (no windows8 mobile yet).

Work in Action :

We did it! JavaFX8 multimedia project on iPad, Android, Windows and Mac!

JavaFX Everywhere

Ensemble8 Javafx8 Android Demo

My Sample JavaFX application Running on Raspberry Pi

My Sample Application Running on Android

JavaFX on iOS and Android

Dev Resources :

Android :

Building and deploying JavaFX Applications on Android

iOS :

NetBeans support for JavaFX for iOS is out!

Develop a JavaFX + iOS app with RoboVM + e(fx)clipse tools in 10 minutes

If you are going to develop serious applications here is some more info

Misc :

At present for JavaFX Oracle priority list is Desktop (Mac,windows,linux) and Embedded (Raspberry Pi, beagle Board etc) .For iOS/android oracle done most of the hardwork and opnesourced javafxports of these platforms as part of OpenJFX ,but there is no JVM from oracle for ios/android.Community is putting all together by filling missing piece(JVM) for ios/android,Community made good progress in running JavaFX on ios (RoboVM) / android(DalvikVM). If you want you can also contribute to the community by sponsoring (Become a RoboVM sponsor) or start developing apps and report issues.

Edit 06/23/2014 :

Johan Vos created a website for javafx ports JavaFX on Mobile and Tablets,check this for updated info ..

How do I set the size of an HTML text box?

You can make the dependent input width versus container width.

.container {
   width: 360px;
}

.container input {
   width: 100%;
}

Disabling contextual LOB creation as createClob() method threw error

The problem occurs because of you didn't choose the appropriate JDBC. Just download and use the JDBC for oracle 10g rather than 11g.

Export/import jobs in Jenkins

If you have exported the config.xml then use the same to import:

curl -k -X POST 'https:///<user>:<token>@<jenkins_url>/createItem?name=<job_name>' --header "Content-Type: application/xml" -d @config.xml

I am connecting via HTTPS and disabled certificate validation using -k.

  • This is how to generate user api token on Jenkins.
  • Jenkins REST API details can be seen if you click the link with same name at bottom right corner of your Jenkins instance.

Displaying Windows command prompt output and redirecting it to a file

I was able to find a solution/workaround of redirecting output to a file and then to the console:

dir > a.txt | type a.txt

where dir is the command which output needs to be redirected, a.txt a file where to store output.

Taking pictures with camera on Android programmatically

There are two ways to take a photo:

1 - Using an Intent to make a photo

2 - Using the camera API

I think you should use the second way and there is a sample code here for two of them.

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had this same problem when trying to upgrade pm2 to the latest version.

Thanks to sdm's answer I did npm update npm -g and it did the trick for me.

Doctrine - How to print out the real sql, not just the prepared statement?

You can easily access the SQL parameters using the following approach.

   $result = $qb->getQuery()->getSQL();

   $param_values = '';  
   $col_names = '';   

   foreach ($result->getParameters() as $index => $param){              
            $param_values .= $param->getValue().',';
            $col_names .= $param->getName().',';
   } 

   //echo rtrim($param_values,',');
   //echo rtrim($col_names,',');    

So if you printed out the $param_values and $col_names , you can get the parameter values passing through the sql and respective column names.

Note : If $param returns an array, you need to re iterate, as parameters inside IN (:?) usually comes is as a nested array.

Meantime if you found another approach, please be kind enough to share with us :)

Thank you!