Programs & Examples On #Meego

Open Source Operating System primarily for the mobile devices and developed by Nokia and Intel. MeeGo is a Linux-based free mobile operating system project.

How to create a temporary table in SSIS control flow task and then use it in data flow task?

Solution:

Set the property RetainSameConnection on the Connection Manager to True so that temporary table created in one Control Flow task can be retained in another task.

Here is a sample SSIS package written in SSIS 2008 R2 that illustrates using temporary tables.

Walkthrough:

Create a stored procedure that will create a temporary table named ##tmpStateProvince and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora Use the below create stored procedure script.

USE Sora;
GO

CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
    
    SET NOCOUNT ON;

    IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
        DROP TABLE ##tmpStateProvince;

    CREATE TABLE ##tmpStateProvince
    (
            CountryCode     nvarchar(3)         NOT NULL
        ,   StateCode       nvarchar(3)         NOT NULL
        ,   Name            nvarchar(30)        NOT NULL
    );

    INSERT INTO ##tmpStateProvince 
        (CountryCode, StateCode, Name)
    VALUES
        ('CA', 'AB', 'Alberta'),
        ('US', 'CA', 'California'),
        ('DE', 'HH', 'Hamburg'),
        ('FR', '86', 'Vienne'),
        ('AU', 'SA', 'South Australia'),
        ('VI', 'VI', 'Virgin Islands');
END
GO

Create a table named dbo.StateProvince that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.

USE Sora;
GO

CREATE TABLE dbo.StateProvince
(
        StateProvinceID int IDENTITY(1,1)   NOT NULL
    ,   CountryCode     nvarchar(3)         NOT NULL
    ,   StateCode       nvarchar(3)         NOT NULL
    ,   Name            nvarchar(30)        NOT NULL
    CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
        ([StateProvinceID] ASC)
) ON [PRIMARY];
GO

Create an SSIS package using Business Intelligence Development Studio (BIDS). Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection... to create a new connection to access SQL Server 2008 R2 database.

Connection Managers - New OLE DB Connection

Click New... on Configure OLE DB Connection Manager.

Configure OLE DB Connection Manager - New

Perform the following actions on the Connection Manager dialog.

  • Select Native OLE DB\SQL Server Native Client 10.0 from Provider since the package will connect to SQL Server 2008 R2 database
  • Enter the Server name, like MACHINENAME\INSTANCE
  • Select Use Windows Authentication from Log on to the server section or whichever you prefer.
  • Select the database from Select or enter a database name, the sample uses the database name Sora.
  • Click Test Connection
  • Click OK on the Test connection succeeded message.
  • Click OK on Connection Manager

Connection Manager

The newly created data connection will appear on Configure OLE DB Connection Manager. Click OK.

Configure OLE DB Connection Manager - Created

OLE DB connection manager KIWI\SQLSERVER2008R2.Sora will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties

Connection Manager Properties

Set the property RetainSameConnection on the connection KIWI\SQLSERVER2008R2.Sora to the value True.

RetainSameConnection Property on Connection Manager

Right-click anywhere inside the package and then click Variables to view the variables pane. Create the following variables.

  • A new variable named PopulateTempTable of data type String in the package scope SO_5631010 and set the variable with the value EXEC dbo.PopulateTempTable.

  • A new variable named FetchTempData of data type String in the package scope SO_5631010 and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince

Variables

Drag and drop an Execute SQL Task on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.

On the General page of the Execute SQL Task Editor, perform the following actions.

  • Set the Name to Create and populate temp table
  • Set the Connection Type to OLE DB
  • Set the Connection to KIWI\SQLSERVER2008R2.Sora
  • Select Variable from SQLSourceType
  • Select User::PopulateTempTable from SourceVariable
  • Click OK

Execute SQL Task Editor

Drag and drop a Data Flow Task onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table. Connect the green arrow from the Execute SQL Task to the Data Flow Task.

Control Flow Tab

Double-click the Data Flow Task to switch to Data Flow tab. Drag and drop an OLE DB Source onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.

On the Connection Manager page of the OLE DB Source Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select SQL command from variable from Data access mode
  • Select User::FetchTempData from Variable name
  • Click Columns page

OLE DB Source Editor - Connection Manager

Clicking Columns page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince specified in the source command variable does not exist and SSIS is unable to read the column definition.

Error message

To fix the error, execute the statement EXEC dbo.PopulateTempTable using SQL Server Management Studio (SSMS) on the database Sora so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns page on OLE DB Source Editor, you will see the column information. Click OK.

OLE DB Source Editor - Columns

Drag and drop OLE DB Destination onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination to open OLE DB Destination Editor.

On the Connection Manager page of the OLE DB Destination Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select Table or view - fast load from Data access mode
  • Select [dbo].[StateProvince] from Name of the table or the view
  • Click Mappings page

OLE DB Destination Editor - Connection Manager

Click Mappings page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK. Column StateProvinceID does not have a matching input column and it is defined as an IDENTITY column in database. Hence, no mapping is required.

OLE DB Destination Editor - Mappings

Data Flow tab should look something like this after configuring all the components.

Data Flow tab

Click the OLE DB Source on Data Flow tab and press F4 to view Properties. Set the property ValidateExternalMetadata to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.

Set ValidateExternalMetadata

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.

Rows in table before package execution

Execute the package. Control Flow shows successful execution.

Package Execution  - Control Flow tab

In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.

Package Execution  - Data Flow tab

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.

Rows in table after package execution

The above example illustrated how to create and use temporary table within a package.

Color a table row with style="color:#fff" for displaying in an email

you can easily do like this:-

    <table>
    <thead>
        <tr>
          <th bgcolor="#5D7B9D"><font color="#fff">Header 1</font></th>
          <th bgcolor="#5D7B9D"><font color="#fff">Header 2</font></th>
           <th bgcolor="#5D7B9D"><font color="#fff">Header 3</font></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>blah blah</td>
            <td>blah blah</td>
            <td>blah blah</td>
        </tr>
    </tbody>
</table>

Demo:- http://jsfiddle.net/VWdxj/7/

How to return multiple values in one column (T-SQL)?

Well... I see that an answer was already accepted... but I think you should see another solutions anyway:

/* EXAMPLE */
DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))
INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'
     UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'
     UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'

/* QUERY */
;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )
SELECT 
    LEFT(tmp.UserId, 10) +
    '/ ' +
    STUFF(
            (   SELECT ', '+Alias 
                FROM @UserAliases 
                WHERE UserId = tmp.UserId 
                FOR XML PATH('') 
            ) 
            , 1, 2, ''
        ) AS [UserId/Alias]
FROM tmp

/* -- OUTPUT
  UserId/Alias
  1/ MrX, MrY, MrA
  2/ Abc, Xyz    
*/

Logical operator in a handlebars.js {{#if}} conditional

taking this one up a notch, for those of you who live on the edge.

gist: https://gist.github.com/akhoury/9118682 Demo: Code snippet below

Handlebars Helper: {{#xif EXPRESSION}} {{else}} {{/xif}}

a helper to execute an IF statement with any expression

  1. EXPRESSION is a properly escaped String
  2. Yes you NEED to properly escape the string literals or just alternate single and double quotes
  3. you can access any global function or property i.e. encodeURIComponent(property)
  4. this example assumes you passed this context to your handlebars template( {name: 'Sam', age: '20' } ), notice age is a string, just for so I can demo parseInt() later in this post

Usage:

<p>
 {{#xif " name == 'Sam' && age === '12' " }}
   BOOM
 {{else}}
   BAMM
 {{/xif}}
</p>

Output

<p>
  BOOM
</p>

JavaScript: (it depends on another helper- keep reading)

 Handlebars.registerHelper("xif", function (expression, options) {
    return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);
  });

Handlebars Helper: {{x EXPRESSION}}

A helper to execute javascript expressions

  1. EXPRESSION is a properly escaped String
  2. Yes you NEED to properly escape the string literals or just alternate single and double quotes
  3. you can access any global function or property i.e. parseInt(property)
  4. this example assumes you passed this context to your handlebars template( {name: 'Sam', age: '20' } ), age is a string for demo purpose, it can be anything..

Usage:

<p>Url: {{x "'hi' + name + ', ' + window.location.href + ' <---- this is your href,' + ' your Age is:' + parseInt(this.age, 10)"}}</p>

Output:

<p>Url: hi Sam, http://example.com <---- this is your href, your Age is: 20</p>

JavaScript:

This looks a little large because I expanded syntax and commented over almost each line for clarity purposes

_x000D_
_x000D_
Handlebars.registerHelper("x", function(expression, options) {_x000D_
  var result;_x000D_
_x000D_
  // you can change the context, or merge it with options.data, options.hash_x000D_
  var context = this;_x000D_
_x000D_
  // yup, i use 'with' here to expose the context's properties as block variables_x000D_
  // you don't need to do {{x 'this.age + 2'}}_x000D_
  // but you can also do {{x 'age + 2'}}_x000D_
  // HOWEVER including an UNINITIALIZED var in a expression will return undefined as the result._x000D_
  with(context) {_x000D_
    result = (function() {_x000D_
      try {_x000D_
        return eval(expression);_x000D_
      } catch (e) {_x000D_
        console.warn('•Expression: {{x \'' + expression + '\'}}\n•JS-Error: ', e, '\n•Context: ', context);_x000D_
      }_x000D_
    }).call(context); // to make eval's lexical this=context_x000D_
  }_x000D_
  return result;_x000D_
});_x000D_
_x000D_
Handlebars.registerHelper("xif", function(expression, options) {_x000D_
  return Handlebars.helpers["x"].apply(this, [expression, options]) ? options.fn(this) : options.inverse(this);_x000D_
});_x000D_
_x000D_
var data = [{_x000D_
  firstName: 'Joan',_x000D_
  age: '21',_x000D_
  email: '[email protected]'_x000D_
}, {_x000D_
  firstName: 'Sam',_x000D_
  age: '18',_x000D_
  email: '[email protected]'_x000D_
}, {_x000D_
  firstName: 'Perter',_x000D_
  lastName: 'Smith',_x000D_
  age: '25',_x000D_
  email: '[email protected]'_x000D_
}];_x000D_
_x000D_
var source = $("#template").html();_x000D_
var template = Handlebars.compile(source);_x000D_
$("#main").html(template(data));
_x000D_
h1 {_x000D_
  font-size: large;_x000D_
}_x000D_
.content {_x000D_
  padding: 10px;_x000D_
}_x000D_
.person {_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.min.js"></script>_x000D_
_x000D_
<script id="template" type="text/x-handlebars-template">_x000D_
  <div class="content">_x000D_
    {{#each this}}_x000D_
    <div class="person">_x000D_
      <h1>{{x  "'Hi ' + firstName"}}, {{x 'lastName'}}</h1>_x000D_
      <div>{{x '"you were born in " + ((new Date()).getFullYear() - parseInt(this.age, 10)) '}}</div>_x000D_
      {{#xif 'parseInt(age) >= 21'}} login here:_x000D_
      <a href="http://foo.bar?email={{x 'encodeURIComponent(email)'}}">_x000D_
         http://foo.bar?email={{x 'encodeURIComponent(email)'}}_x000D_
        </a>_x000D_
      {{else}} Please go back when you grow up. {{/xif}}_x000D_
    </div>_x000D_
    {{/each}}_x000D_
  </div>_x000D_
</script>_x000D_
_x000D_
<div id="main"></div>
_x000D_
_x000D_
_x000D_

Moar

if you want access upper level scope, this one is slightly different, the expression is the JOIN of all arguments, usage: say context data looks like this:

// data
{name: 'Sam', age: '20', address: { city: 'yomomaz' } }

// in template
// notice how the expression wrap all the string with quotes, and even the variables
// as they will become strings by the time they hit the helper
// play with it, you will immediately see the errored expressions and figure it out

{{#with address}}
    {{z '"hi " + "' ../this.name '" + " you live with " + "' city '"' }}
{{/with}}

Javascript:

Handlebars.registerHelper("z", function () {
    var options = arguments[arguments.length - 1]
    delete arguments[arguments.length - 1];
    return Handlebars.helpers["x"].apply(this, [Array.prototype.slice.call(arguments, 0).join(''), options]);
});

Handlebars.registerHelper("zif", function () {
    var options = arguments[arguments.length - 1]
    delete arguments[arguments.length - 1];
    return Handlebars.helpers["x"].apply(this, [Array.prototype.slice.call(arguments, 0).join(''), options]) ? options.fn(this) : options.inverse(this);
});

JSON Parse File Path

var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);

This code worked for me.

How can I define an array of objects?

You can also try

    interface IData{
        id: number;
        name:string;
    }

    let userTestStatus:Record<string,IData> = {
        "0": { "id": 0, "name": "Available" },
        "1": { "id": 1, "name": "Ready" },
        "2": { "id": 2, "name": "Started" }
    };

To check how record works: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

Here in our case Record is used to declare an object whose key will be a string and whose value will be of type IData so now it will provide us intellisense when we will try to access its property and will throw type error in case we will try something like userTestStatus[0].nameee

Unresolved external symbol in object files

I've just seen the problem I can't call a function from main in .cpp file, correctly declared in .h file and defined in .c file. Encountered a linker error. Meanwhile I can call function from usual .c file. Possibly it depends on call convention. Solution was to add following preproc lines in every .h file:

#ifdef __cplusplus
extern "C"
{
#endif

and these in the end

#ifdef __cplusplus
}
#endif

(HTML) Download a PDF file instead of opening them in browser when clicked

The behaviour should depend on how the browser is set up to handle various MIME types. In this case the MIME type is application/pdf. If you want to force the browser to download the file you can try forcing a different MIME type on the PDF files. I recommend against this as it should be the users choice what will happen when they open a PDF file.

Set Radiobuttonlist Selected from Codebehind

You could do:

radio1.SelectedIndex = 1;

But this is the most simple form and would most likely become problematic as your UI grows. Say, for instance, if a team member inserts an item in the RadioButtonList above option2 but doesn't know we use magic numbers in code-behind to select - now the app selects the wrong index!

Maybe you want to look into using FindControl in order to determine the ListItem actually required, by name, and selecting appropriately. For instance:

//omitting possible null reference checks...
var wantedOption = radio1.FindControl("option2").Selected = true;

Responsive Google Map?

Tried it with CSS, but its never 100% responsive, so I built a pure javascript solution. This one uses jQuery,

google.maps.event.addDomListener(window, "resize", function() {

  var center = map.getCenter();

  resizeMap();

  google.maps.event.trigger(map, "resize");
  map.setCenter(center);

});



function resizeMap(){

  var h = window.innerHeight;
  var w = window.innerWidth;

  $("#map_canvas").width(w/2);
  $("#map_canvas").height(h-50);

}

How to put a div in center of browser using CSS?

 <center>
        <h3 > your div goes here!</h3>    
    </center>

Render Content Dynamically from an array map function in React Native

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })
}

You forgot to return the map. this code will resolve the issue.

Getting an odd error, SQL Server query using `WITH` clause

always use with statement like ;WITH then you'll never get this error. The WITH command required a ; between it and any previous command, by always using ;WITH you'll never have to remember to do this.

see WITH common_table_expression (Transact-SQL), from the section Guidelines for Creating and Using Common Table Expressions:

When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.

How to install OpenSSL in windows 10?

I recently needed to document how to get a version of it installed, so I've copied my steps here, as the other answers were using different sources from what I recommend, which is Cygwin. I like Cygwin because it is well maintained and provides a wealth of other utilities for Windows. Cygwin also allows you to easily update the versions as needed when vulnerabilities are fixed. Please update your version of OpenSSL often!

Open a Windows Command prompt and check to see if you have OpenSSL installed by entering: openssl version

If you get an error message that the command is NOT recognized, then install OpenSSL by referring to Cygwin following the summary steps below:

Basically, download and run the Cygwin Windows Setup App to install and to update as needed the OpenSSL application:

  1. Select an install directory, such as C:\cygwin64. Choose a download mirror such as: http://mirror.cs.vt.edu
  2. Enter in openssl into the search and select it. You can also select/un-select other items of interest at this time. The click Next twice then click Finish.
  3. After installing, you need to edit the PATH variable. On Windows, you can access the System Control Center by pressing Windows Key + Pause. In the System window, click Advanced System Settings ? Advanced (tab) ? Environment Variables. For Windows 10, a quick access is to enter "Edit the system environment variables" in the Start Search of Windows and click the button "Environment Variables". Change the PATH variable (double-click on it or Select and Edit), and add the path where your Cywgwin is, e.g. C:\cygwin\bin.
  4. Verify you have it installed via a new Command Prompt window: openssl version. For example: C:\Program Files\mosquitto>openssl versionOpenSSL 1.1.1f 31 Mar 2020

What is tail recursion?

Instead of explaining it with words, here's an example. This is a Scheme version of the factorial function:

(define (factorial x)
  (if (= x 0) 1
      (* x (factorial (- x 1)))))

Here is a version of factorial that is tail-recursive:

(define factorial
  (letrec ((fact (lambda (x accum)
                   (if (= x 0) accum
                       (fact (- x 1) (* accum x))))))
    (lambda (x)
      (fact x 1))))

You will notice in the first version that the recursive call to fact is fed into the multiplication expression, and therefore the state has to be saved on the stack when making the recursive call. In the tail-recursive version there is no other S-expression waiting for the value of the recursive call, and since there is no further work to do, the state doesn't have to be saved on the stack. As a rule, Scheme tail-recursive functions use constant stack space.

How do I set the driver's python version in spark?

I just faced the same issue and these are the steps that I follow in order to provide Python version. I wanted to run my PySpark jobs with Python 2.7 instead of 2.6.

  1. Go to the folder where $SPARK_HOME is pointing to (in my case is /home/cloudera/spark-2.1.0-bin-hadoop2.7/)

  2. Under folder conf, there is a file called spark-env.sh. In case you have a file called spark-env.sh.template you will need to copy the file to a new file called spark-env.sh.

  3. Edit the file and write the next three lines

    export PYSPARK_PYTHON=/usr/local/bin/python2.7

    export PYSPARK_DRIVER_PYTHON=/usr/local/bin/python2.7

    export SPARK_YARN_USER_ENV="PYSPARK_PYTHON=/usr/local/bin/python2.7"

  4. Save it and launch your application again :)

In that way, if you download a new Spark standalone version, you can set the Python version which you want to run PySpark to.

A monad is just a monoid in the category of endofunctors, what's the problem?

Note: No, this isn't true. At some point there was a comment on this answer from Dan Piponi himself saying that the cause and effect here was exactly the opposite, that he wrote his article in response to James Iry's quip. But it seems to have been removed, perhaps by some compulsive tidier.

Below is my original answer.


It's quite possible that Iry had read From Monoids to Monads, a post in which Dan Piponi (sigfpe) derives monads from monoids in Haskell, with much discussion of category theory and explicit mention of "the category of endofunctors on Hask" . In any case, anyone who wonders what it means for a monad to be a monoid in the category of endofunctors might benefit from reading this derivation.

Current timestamp as filename in Java

You can use DateTime

import org.joda.time.DateTime

Option 1 : with yyyyMMddHHmmss

DateTime.now().toString("yyyyMMddHHmmss")

Will give 20190205214430

Option 2 : yyyy-dd-M--HH-mm-ss

   DateTime.now().toString("yyyy-dd-M--HH-mm-ss")

will give 2019-05-2--21-43-32

AJAX reload page with POST

If you want to refresh the entire page, it makes no sense to use AJAX. Use normal Javascript to post the form element in that page. Make sure the form submits to the same page, or that the form submits to a page which then redirects back to that page

Javascript to be used (always in myForm.php):

function submitform()
{
  document.getElementById('myForm').submit();
}

Suppose your form is on myForm.php: Method 1:

<form action="./myForm.php" method="post" id="myForm">
    ...
</form>

Method 2:

myForm.php:

<form action="./myFormActor.php" method="post" id="myForm">
    ...
</form>

myFormActor.php:

<?php
    //all code here, no output
    header("Location: ./myForm.php");
?>

transparent navigation bar ios

For those looking for OBJC solution, to be added in App Delegate didFinishLaunchingWithOptions method:

[[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[UINavigationBar appearance].shadowImage = [UIImage new];
[UINavigationBar appearance].backgroundColor = [UIColor clearColor];
[UINavigationBar appearance].translucent = YES;

XSLT string replace

I keep hitting this answer. But none of them list the easiest solution for xsltproc (and probably most XSLT 1.0 processors):

  1. Add the exslt strings name to the stylesheet, i.e.:
<xsl:stylesheet
  version="1.0"
  xmlns:str="http://exslt.org/strings"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  1. Then use it like:
<xsl:value-of select="str:replace(., ' ', '')"/>

cmake error 'the source does not appear to contain CMakeLists.txt'

This reply may be late but it may help users having similar problem. The opencv-contrib (available at https://github.com/opencv/opencv_contrib/releases) contains extra modules but the build procedure has to be done from core opencv (available at from https://github.com/opencv/opencv/releases) modules.

Follow below steps (assuming you are building it using CMake GUI)

  1. Download openCV (from https://github.com/opencv/opencv/releases) and unzip it somewhere on your computer. Create build folder inside it

  2. Download exra modules from OpenCV. (from https://github.com/opencv/opencv_contrib/releases). Ensure you download the same version.

  3. Unzip the folder.

  4. Open CMake

  5. Click Browse Source and navigate to your openCV folder.

  6. Click Browse Build and navigate to your build Folder.

  7. Click the configure button. You will be asked how you would like to generate the files. Choose Unix-Makefile from the drop down menu and Click OK. CMake will perform some tests and return a set of red boxes appear in the CMake Window.

  8. Search for "OPENCV_EXTRA_MODULES_PATH" and provide the path to modules folder (e.g. /Users/purushottam_d/Programs/OpenCV3_4_5_contrib/modules)

  9. Click Configure again, then Click Generate.

  10. Go to build folder

# cd build
# make
# sudo make install
  1. This will install the opencv libraries on your computer.

Execute php file from another php

exec is shelling to the operating system, and unless the OS has some special way of knowing how to execute a file, then it's going to default to treating it as a shell script or similar. In this case, it has no idea how to run your php file. If this script absolutely has to be executed from a shell, then either execute php passing the filename as a parameter, e.g

exec ('/usr/local/bin/php -f /opt/lampp/htdocs/.../name.php)') ;

or use the punct at the top of your php script

#!/usr/local/bin/php
<?php ... ?>

Hibernate: hbm2ddl.auto=update in production?

It's not safe, not recommended, but it's possible.

I have experience in an application using the auto-update option in production.

Well, the main problems and risks found in this solution are:

  • Deploy in the wrong database. If you commit the mistake to run the application server with a old version of the application (EAR/WAR/etc) in the wrong database... You will have a lot of new columns, tables, foreign keys and errors. The same problem can occur with a simple mistake in the datasource file, (copy/paste file and forgot to change the database). In resume, the situation can be a disaster in your database.
  • Application server takes too long to start. This occur because the Hibernate try to find all created tables/columns/etc every time you start the application. He needs to know what (table, column, etc) needs to be created. This problem will only gets worse as the database tables grows up.
  • Database tools it's almost impossible to use. To create database DDL or DML scripts to run with a new version, you need to think about what will be created by the auto-update after you start the application server. Per example, If you need to fill a new column with some data, you need to start the application server, wait to Hibernate crete the new column and run the SQL script only after that. As can you see, database migration tools (like Flyway, Liquibase, etc) it's almost impossible to use with auto-update enabled.
  • Database changes is not centralized. With the possibility of the Hibernate create tables and everything else, it's hard to watch the changes on database in each version of the application, because most of them are made automatically.
  • Encourages garbage on database. Because of the "easy" use of auto-update, there is a chance your team neglecting to drop old columns and old tables, because the hibernate auto-update can't do that.
  • Imminent disaster. The imminent risk of some disaster to occur in production (like some people mentioned in other answers). Even with an application running and being updated for years, I don't think it's a safe choice. I never felt safe with this option being used.

So, I will not recommend to use auto-update in production.

If you really want to use auto-update in production, I recommend:

  • Separated networks. Your test environment cannot access the homolog environment. This helps prevent a deployment that was supposed to be in the Test environment change the Homologation database.
  • Manage scripts order. You need to organize your scripts to run before your deploy (structure table change, drop table/columns) and script after the deploy (fill information for the new columns/tables).

And, different of the another posts, I don't think the auto-update enabled it's related with "very well paid" DBAs (as mentioned in other posts). DBAs have more important things to do than write SQL statements to create/change/delete tables and columns. These simple everyday tasks can be done and automated by developers and only passed for DBA team to review, not needing Hibernate and DBAs "very well paid" to write them.

C - Convert an uppercase letter to lowercase

In ASCII the upper and lower case alphabet is 0x20 (in ASCII 0x20 is space ' ') apart from each other, so this is another way to do it.

int lower(int a) 
{
    return a | ' ';  
}

How to select a column name with a space in MySQL

To each his own but the right way to code this is to rename the columns inserting underscore so there are no gaps. This will ensure zero errors when coding. When printing the column names for public display you could search-and-replace to replace the underscore with a space.

How do you send a Firebase Notification to all devices via CURL?

Just make all users who log in subscribe to a specific topic, and then send a notification to that topic.

How to install a gem or update RubyGems if it fails with a permissions error

You really should be using a Ruby version manager.

Using one properly would prevent and can resolve your permission problem when executing a gem update command.

I recommend rbenv.

However, even when you use a Ruby version manager, you may still get that same error message.

If you do, and you are using rbenv, just verify that the ~/.rbenv/shims directory is before the path for the system Ruby.

$ echo $PATH will show you the order of your load path.

If you find that your shims directory comes after your system Ruby bin directory, then edit your ~/.bashrc file and put this as your last export PATH command: export PATH=$HOME/.rbenv/shims:$PATH

$ ruby -v shows you what version of Ruby you are using

This shows that I'm currently using the system version of Ruby (usually not good)

$ ruby -v
ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin12.0]

$ rbenv global 1.9.3-p448 switches me to a newer, pre-installed version (see references below).

This shows that I'm using a newer version of Ruby (that likely won't cause the Gem::FilePermissionError)

$ ruby -v
ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.0]

You typically should not need to preface a gem command with sudo. If you feel the need to do so, something is probably misconfigured.

For details about rbenv see the following:

Can I call a base class's virtual function if I'm overriding it?

If you want to call a function of base class from its derived class you can simply call inside the overridden function with mentioning base class name(like Foo::printStuff()).

code goes here

#include <iostream>
using namespace std;

class Foo
{
public:
    int x;

    virtual void printStuff()
    {
         cout<<"Base Foo printStuff called"<<endl;
    }
};

class Bar : public Foo
{
public:
    int y;

    void printStuff()
    {
        cout<<"derived Bar printStuff called"<<endl;
        Foo::printStuff();/////also called the base class method
    }
};

int main()
{
    Bar *b=new Bar;
    b->printStuff();
}

Again you can determine at runtime which function to call using the object of that class(derived or base).But this requires your function at base class must be marked as virtual.

code below

#include <iostream>
using namespace std;

class Foo
{
public:
    int x;

    virtual void printStuff()
    {
         cout<<"Base Foo printStuff called"<<endl;
    }
};

class Bar : public Foo
{
public:
    int y;

    void printStuff()
    {
        cout<<"derived Bar printStuff called"<<endl;
    }
};

int main()
{

    Foo *foo=new Foo;
    foo->printStuff();/////this call the base function
    foo=new Bar;
    foo->printStuff();
}

What does 'git blame' do?

From git-blame:

Annotates each line in the given file with information from the revision which last modified the line. Optionally, start annotating from the given revision.

When specified one or more times, -L restricts annotation to the requested lines.

Example:

[email protected]:~# git blame .htaccess
...
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  4) allow from all
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  5)
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  6) <IfModule mod_rewrite.c>
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  7)     RewriteEngine On
...

Please note that git blame does not show the per-line modifications history in the chronological sense. It only shows who was the last person to have changed a line in a document up to the last commit in HEAD.

That is to say that in order to see the full history/log of a document line, you would need to run a git blame path/to/file for each commit in your git log.

iOS 7 status bar back to iOS 6 default style in iPhone app?

I used this in all my view controllers, it's simple. Add this lines in all your viewDidLoad methods:

- (void)viewDidLoad{
    //add this 2 lines:
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;

    [super viewDidLoad];
}

How can I replace a newline (\n) using sed?

Why didn't I find a simple solution with awk?

awk '{printf $0}' file

printf will print the every line without newlines, if you want to separate the original lines with a space or other:

awk '{printf $0 " "}' file

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

Why does foo = filter(...) return a <filter object>, not a list?

Please see this sample implementation of filter to understand how it works in Python 3:

def my_filter(function, iterable):
    """my_filter(function or None, iterable) --> filter object

    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true."""
    if function is None:
        return (item for item in iterable if item)
    return (item for item in iterable if function(item))

The following is an example of how you might use filter or my_filter generators:

>>> greetings = {'hello'}
>>> spoken = my_filter(greetings.__contains__, ('hello', 'goodbye'))
>>> print('\n'.join(spoken))
hello

Combining two sorted lists in Python

Well, the naive approach (combine 2 lists into large one and sort) will be O(N*log(N)) complexity. On the other hand, if you implement the merge manually (i do not know about any ready code in python libs for this, but i'm no expert) the complexity will be O(N), which is clearly faster. The idea is described wery well in post by Barry Kelly.

How to get DataGridView cell value in messagebox?

You can use the DataGridViewCell.Value Property to retrieve the value stored in a particular cell.

So to retrieve the value of the 'first' selected Cell and display in a MessageBox, you can:

MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());

The above probably isn't exactly what you need to do. If you provide more details we can provide better help.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Jenkins: Failed to connect to repository

In my case, I edited the known_hosts file with root user. So it changed the file ownership to root and jenkins user started throwing "[email protected]:xxxxxx/xxxx.git HEAD" returned status code 128: stdout: stderr: Host key verification failed" error while cloning git image. Reverting the ownership resolved the issue.

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

google chrome extension :: console.log() from background page?

You can open the background page's console if you click on the "background.html" link in the extensions list.

To access the background page that corresponds to your extensions open Settings / Extensions or open a new tab and enter chrome://extensions. You will see something like this screenshot.

Chrome extensions dialogue

Under your extension click on the link background page. This opens a new window. For the context menu sample the window has the title: _generated_background_page.html.

What's the difference between TRUNCATE and DELETE in SQL

DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.

The Syntax of a SQL DELETE statement is:

DELETE FROM table_name [WHERE condition];

TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.

Cannot find vcvarsall.bat when running a Python script

THIS IS AN UP TO DATE ANSWER FOR WINDOWS USERS - VERY SIMPLE SOLUTION.

As pointed out by other, the problem is that python/cython etc. tries to find the same compiler they were built from, but this compiler does not exist on the computer. Most of the time, this compiler is a version of visual studio (2008, 2010 or 2013), but either such a compiler is not installed, or a newer version is installed and the system prevents from installing an older one. So, the solution is simple:

1) look at C:\Program Files (x86) and see if there is an installed version of Microsoft visual studio, and if it is newer than the version from which Python has been built. If not, install(/update to) the version from which Python has been built (see previous answers), or even a newest version and follow the next step.

2)If a newest version of Microsoft visual studio is already installed, we have to make Python/cython etc. believe that it is the version from which it has been built. And this is very simple: go to the the system environment variables and create the following variables, if they do not exist:

VS100COMNTOOLS

VS110COMNTOOLS

VS120COMNTOOLS

VS140COMNTOOLS

And set the field of these variables to

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools" (if visual studio 2008 is installed), or "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools" (if visual studio 2010 is installed) or "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools" (if visual studio 2013 is installed) or "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools" (if visual studio 2015 is installed).

This solution works for 32 bit versions of python. It may also work for 64 bit version but I've not tested; most probably, for 64 bit versions, the following additional steps must be performed:

3)add the path "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC" to the %PATH% environment variable (change the number of the version of visual studio according to you version).

4) from the command line, run "vcvarsall.bat x86_amd64"

That's all.

How can I stop .gitignore from appearing in the list of untracked files?

If someone has already added a .gitignore to your repo, but you want to make some changes to it and have those changes ignored do the following:

git update-index --assume-unchanged .gitignore

Source.

How to sort a list of strings numerically?

You can also use:

import re

def sort_human(l):
    convert = lambda text: float(text) if text.isdigit() else text
    alphanum = lambda key: [convert(c) for c in re.split('([-+]?[0-9]*\.?[0-9]*)', key)]
    l.sort(key=alphanum)
    return l

This is very similar to other stuff that you can find on the internet but also works for alphanumericals like [abc0.1, abc0.2, ...].

how to display none through code behind

try this

<div id="login_div" runat="server">

and on the code behind.

login_div.Style.Add("display", "none");

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

Moving the Springbootapplication(application.java) file to another package resolved the issue for me. Keep it separate from the controllers and repositories.

Java: Calling a super method which calls an overridden method

Further more extended the output of the raised question, this will give more insight on the access specifier and override behavior.

            package overridefunction;
            public class SuperClass 
                {
                public void method1()
                {
                    System.out.println("superclass method1");
                    this.method2();
                    this.method3();
                    this.method4();
                    this.method5();
                }
                public void method2()
                {
                    System.out.println("superclass method2");
                }
                private void method3()
                {
                    System.out.println("superclass method3");
                }
                protected void method4()
                {
                    System.out.println("superclass method4");
                }
                void method5()
                {
                    System.out.println("superclass method5");
                }
            }

            package overridefunction;
            public class SubClass extends SuperClass
            {
                @Override
                public void method1()
                {
                    System.out.println("subclass method1");
                    super.method1();
                }
                @Override
                public void method2()
                {
                    System.out.println("subclass method2");
                }
                // @Override
                private void method3()
                {
                    System.out.println("subclass method3");
                }
                @Override
                protected void method4()
                {
                    System.out.println("subclass method4");
                }
                @Override
                void method5()
                {
                    System.out.println("subclass method5");
                }
            }

            package overridefunction;
            public class Demo 
            {
                public static void main(String[] args) 
                {
                    SubClass mSubClass = new SubClass();
                    mSubClass.method1();
                }
            }

            subclass method1
            superclass method1
            subclass method2
            superclass method3
            subclass method4
            subclass method5

log4j configuration via JVM argument(s)?

If you are using gradle. You can apply 'aplication' plugin and use the following command

  applicationDefaultJvmArgs = [
             "-Dlog4j.configurationFile=your.xml",
                              ]

WPF Datagrid Get Selected Cell Value

If you are selecting only one cell then get selected cell content like this

var cellInfo = dataGrid1.SelectedCells[0];

var content = cellInfo.Column.GetCellContent(cellInfo.Item);

Here content will be your selected cells value

And if you are selecting multiple cells then you can do it like this

var cellInfos = dataGrid1.SelectedCells;

var list1 = new List<string>();

foreach (DataGridCellInfo cellInfo in cellInfos)
{
    if (cellInfo.IsValid)
    {
        //GetCellContent returns FrameworkElement
        var content= cellInfo.Column.GetCellContent(cellInfo.Item); 

        //Need to add the extra lines of code below to get desired output

        //get the datacontext from FrameworkElement and typecast to DataRowView
        var row = (DataRowView)content.DataContext;

        //ItemArray returns an object array with single element
        object[] obj = row.Row.ItemArray;

        //store the obj array in a list or Arraylist for later use
        list1.Add(obj[0].ToString());
    }
}

Multiple GitHub Accounts & SSH Config

I recently had to do this and had to sift through all these answers and their comments to eventually piece the information together, so I'll put it all here, in one post, for your convenience:


Step 1: ssh keys
Create any keypairs you'll need. In this example I've named me default/original 'id_rsa' (which is the default) and my new one 'id_rsa-work':

ssh-keygen -t rsa -C "[email protected]"


Step 2: ssh config
Set up multiple ssh profiles by creating/modifying ~/.ssh/config. Note the slightly differing 'Host' values:

# Default GitHub
Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa

# Work GitHub
Host work.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_work


Step 3: ssh-add
You may or may not have to do this. To check, list identity fingerprints by running:

$ ssh-add -l
2048 1f:1a:b8:69:cd:e3:ee:68:e1:c4:da:d8:96:7c:d0:6f stefano (RSA)
2048 6d:65:b9:3b:ff:9c:5a:54:1c:2f:6a:f7:44:03:84:3f [email protected] (RSA)

If your entries aren't there then run:

ssh-add ~/.ssh/id_rsa_work


Step 4: test
To test you've done this all correctly, I suggest the following quick check:

$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

Note that you'll have to change the hostname (github / work.github) depending on what key/identity you'd like to use. But now you should be good to go! :)

How to print Boolean flag in NSLog?

Here is how you can do it:

BOOL flag = NO;
NSLog(flag ? @"YES" : @"NO");

Regex to match only uppercase "words" with some exceptions

For the first case you propose you can use: '[[:blank:]]+[A-Z0-9]+[[:blank:]]+', for example:

echo "The thing P1 must connect to the J236 thing in the Foo position" | grep -oE '[[:blank:]]+[A-Z0-9]+[[:blank:]]+'

In the second case maybe you need to use something else and not a regex, maybe a script with a dictionary of technical words...

Cheers, Fernando

How to add google-play-services.jar project dependency so my project will run and present map

What i have done is that import a new project into eclipse workspace, and that path of that was be

android-sdk-macosx/extras/google/google_play_services/libproject/google-play-services_lib

and add as library in your project.. that it .. simple!! you might require to add support library in your project.

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

How to change the font color of a disabled TextBox?

NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor of the TextBox.


I think what you really want to do is enable the TextBox and set the ReadOnly property to true.

It's a bit tricky to change the color of the text in a disabled TextBox. I think you'd probably have to subclass and override the OnPaint event.

ReadOnly though should give you the same result as !Enabled and allow you to maintain control of the color and formatting of the TextBox. I think it will also still support selecting and copying text from the TextBox which is not possible with a disabled TextBox.

Another simple alternative is to use a Label instead of a TextBox.

T-SQL CASE Clause: How to specify WHEN NULL

Jason caught an error, so this works...

Can anyone confirm the other platform versions?
SQL Server:

SELECT
CASE LEN(ISNULL(last_name,'')) 
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

MySQL:

SELECT
CASE LENGTH(IFNULL(last_name,'')) 
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

Oracle:

SELECT
CASE LENGTH(NVL(last_name,'')) 
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

android: changing option menu items programmatically

Try this code:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    this.menu=menu;
    updateMenuItems(menu);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.document_list_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    if (item.getItemId() == android.R.id.home) {
        onHomeButtonPresssed();
    }else if (item.getItemId() == R.id.action_delete) {
        useCheckBoxAdapter=false;
        deleteDocuments();
    } else if (item.getItemId() == R.id.share) {
        useCheckBoxAdapter=false;
        shareDocuments();
    } else if (item.getItemId() == R.id.action_tick) {
        useCheckBoxAdapter=true;
        onShowCheckboxes();
    }
    updateMenuItems(menu);
    return true;
}

private void updateMenuItems(Menu menu){
    if (useCheckBoxAdapter && menu != null) {
        menu.findItem(R.id.action_delete).setVisible(true);
        menu.findItem(R.id.share).setVisible(true);
        menu.findItem(R.id.action_tick).setVisible(false);
    } else {
        menu.findItem(R.id.action_delete).setVisible(false);
        menu.findItem(R.id.share).setVisible(false);
        menu.findItem(R.id.action_tick).setVisible(true);
    }
    invalidateOptionsMenu();
}

How do I setup a SSL certificate for an express.js server?

See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):

var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );

https.createServer({
    key: privateKey,
    cert: certificate
}, app).listen(port);

Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener

final keyword in method parameters

final means you can't change the value of that variable once it was assigned.

Meanwhile, the use of final for the arguments in those methods means it won't allow the programmer to change their value during the execution of the method. This only means that inside the method the final variables can not be reassigned.

jQuery click function doesn't work after ajax call?

Here's the FIDDLE

Same code as yours but it will work on dynamically created elements.

$(document).on('click', '.deletelanguage', function () {
    alert("success");
    $('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
});

How to get N rows starting from row M from sorted table in T-SQL

Following is the simple query will list N rows from M+1th row of the table. Replace M and N with your preferred numbers.

Select Top N B.PrimaryKeyColumn from 
    (SELECT 
        top M PrimaryKeyColumn
     FROM 
        MyTable
) A right outer join MyTable B 
on 
    A.PrimaryKeyColumn = B.PrimaryKeyColumn
where 
    A.PrimaryKeyColumn IS NULL

Please let me know whether this is usefull for your situation.

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

I'd had this issue with Eclipse 2019-12 where the includes were previously being resolved, but then weren't. This was with a Meson build C/C++ project. I'm not sure exactly what happened, but closing the project and reopening it resolved the issue for me.

What do the crossed style properties in Google Chrome devtools mean?

When a CSS property shows as struck-through, it means that the crossed-out style was applied, but then overridden by a more specific selector, a more local rule, or by a later property within the same rule.

(Special cases: a style will also be shown as struck-through if a style exists in an matching rule but is commented out, or if you've manually disabled it by unchecking it within the Chrome developer tools. It will also show as crossed out, but with an error icon, if the style has a syntax error.)

For example, if a background color was applied to all divs, but a different background color was applied to divs with a certain id, the first color will show up but will be crossed out, as the second color has replaced it (in the property list for the div with that id).

Cannot open solution file in Visual Studio Code

Use vscode-solution-explorer extension:

This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.

https://github.com/fernandoescolar/vscode-solution-explorer

enter image description here

Thanks @fernandoescolar

Difference between $(this) and event.target?

There are cross browser issues here.

A typical non-jQuery event handler would be something like this :

function doSomething(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

jQuery normalises evt and makes the target available as this in event handlers, so a typical jQuery event handler would be something like this :

function doSomething(evt) {
    var $target = $(this);
    //do stuff here
}

A hybrid event handler which uses jQuery's normalised evt and a POJS target would be something like this :

function doSomething(evt) {
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

correct way of comparing string jquery operator =

No. = sets somevar to have that value. use === to compare value and type which returns a boolean that you need.

Never use or suggest == instead of ===. its a recipe for disaster. e.g 0 == "" is true but "" == '0' is false and many more.

More information also in this great answer

Difference between abstract class and interface in Python

Python doesn't really have either concept.

It uses duck typing, which removed the need for interfaces (at least for the computer :-))

Python <= 2.5: Base classes obviously exist, but there is no explicit way to mark a method as 'pure virtual', so the class isn't really abstract.

Python >= 2.6: Abstract base classes do exist (http://docs.python.org/library/abc.html). And allow you to specify methods that must be implemented in subclasses. I don't much like the syntax, but the feature is there. Most of the time it's probably better to use duck typing from the 'using' client side.

How does the stack work in assembly language?

I think primarily you're getting confused between a program's stack and any old stack.

A Stack

Is an abstract data structure which consists of information in a Last In First Out system. You put arbitrary objects onto the stack and then you take them off again, much like an in/out tray, the top item is always the one that is taken off and you always put on to the top.

A Programs Stack

Is a stack, it's a section of memory that is used during execution, it generally has a static size per program and frequently used to store function parameters. You push the parameters onto the stack when you call a function and the function either address the stack directly or pops off the variables from the stack.

A programs stack isn't generally hardware (though it's kept in memory so it can be argued as such), but the Stack Pointer which points to a current area of the Stack is generally a CPU register. This makes it a bit more flexible than a LIFO stack as you can change the point at which the stack is addressing.

You should read and make sure you understand the wikipedia article as it gives a good description of the Hardware Stack which is what you are dealing with.

There is also this tutorial which explains the stack in terms of the old 16bit registers but could be helpful and another one specifically about the stack.

From Nils Pipenbrinck:

It's worthy of note that some processors do not implement all of the instructions for accessing and manipulating the stack (push, pop, stack pointer, etc) but the x86 does because of it's frequency of use. In these situations if you wanted a stack you would have to implement it yourself (some MIPS and some ARM processors are created without stacks).

For example, in MIPs a push instruction would be implemented like:

addi $sp, $sp, -4  # Decrement stack pointer by 4  
sw   $t0, ($sp)   # Save $t0 to stack  

and a Pop instruction would look like:

lw   $t0, ($sp)   # Copy from stack to $t0  
addi $sp, $sp, 4   # Increment stack pointer by 4  

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

window.open target _self v window.location.href?

Definitely the second method is preferred because you don't have the overhead of another function invocation:

window.location.href = "webpage.htm";

inserting characters at the start and end of a string

Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:

s = "something about cupcakes"
print(f"L{s}LL")

How do I display images from Google Drive on a website?

If you have some image files, just upload them to a public folder on your Google Drive, copy its folder ID from the address bar (e.g. 0B0Gi4v5omoZUVXhCT2kta1l0ZG8) and paste it into a form at GDrives, then choose your own alias (e.g. myimgs) and voila! You can access the images one by one using e.g. http://gdriv.es/myimgs/myimage.jpg.

If you want to embed a whole folder on your website (in a frame), you can use one of the following URLs, replacing [folderID] with your own ID:

If you prefer to get the file list in XML or JSON, you can use YQL.

Note: You can use Google+ Photos to host ans embed your images as well.

Creating an Instance of a Class with a variable in Python

Rather than use multiple classes or class inheritance, perhaps a single Toy class that knows what "kind" it is:

class Toy:
    num = 0
    def __init__(self, name, kind, *args):
        self.name = name
        self.kind = kind
        self.data = args
        self.num = Toy.num
        Toy.num += 1

    def __repr__(self):
        return ' '.join([self.name,self.kind,str(self.num)])

    def playWith(self):
        print self

def getNewToy(name, kind):
    return Toy(name, kind)

t1 = Toy('Suzie', 'doll')
t2 = getNewToy('Jack', 'robot')
print t1
t2.playWith()

Running it:

$ python toy.py 
Suzie doll 0
Jack robot 1

As you can see, getNewToy is really unnecessary. Now you can modify playWith to check the value of self.kind and change behavior, you can redefine playWith to designate a playmate:

def playWith(self, who=None):
    if who:  pass
    print self

t1.playWith(t2)

Simple linked list in C++

link list by using node class and linked list class

this is just an example not the complete functionality of linklist, append function and printing a linklist is explained in the code

code :

#include<iostream>
using namespace std;

Node class

class Node{
    public:
    int data;
    Node* next=NULL;
    Node(int data)
        {
            this->data=data;


        }   
    };

link list class named as ll

class ll{
    public:
        Node* head;

ll(Node* node)
    {
        this->head=node;
    }

void append(int data)
    {
        Node* temp=this->head;
        while(temp->next!=NULL)
            {
                temp=temp->next;
            }
        Node* newnode= new Node(data);
        // newnode->data=data;
        temp->next=newnode;
    }
void print_list()
    {   cout<<endl<<"printing entire link list"<<endl;
        Node* temp= this->head;
        while(temp->next!=NULL)
            {
                cout<<temp->data<<endl;
                temp=temp->next;
            }
        cout<<temp->data<<endl;;

    }
};

main function

int main()
{
  cout<<"hello this is an example of link list in cpp using classes"<<endl;
  ll list1(new Node(1));
  list1.append(2);
  list1.append(3);
  list1.print_list();
  }

thanks ???

screenshot https://i.stack.imgur.com/C2D9y.jpg

Changing background color of text box input not working when empty

DEMO --> http://jsfiddle.net/2Xgfr/829/

HTML

<input type="text" id="subEmail" onchange="checkFilled();">

JavaScript

 function checkFilled() {
    var inputVal = document.getElementById("subEmail");
    if (inputVal.value == "") {
        inputVal.style.backgroundColor = "yellow";
    }
    else{
        inputVal.style.backgroundColor = "";
    }
}

checkFilled();

Note: You were checking value and setting color to value which is not allowed, that's why it was giving you errors. try like the above.

How do I install cURL on cygwin?

If someone is having problem with finding CURL in the list in setup.exe (Cygwin package manager) then trying downloading 64bit version of this setup. Worked for me.

Terminating idle mysql connections

Manual cleanup:

You can KILL the processid.

mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id      | User       | Host              | db   | Command | Time  | State | Info                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www  | Sleep   | 25946 |       | NULL                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+

mysql> kill 1193777;

But:

  • the php application might report errors (or the webserver, check the error logs)
  • don't fix what is not broken - if you're not short on connections, just leave them be.

Automatic cleaner service ;)

Or you configure your mysql-server by setting a shorter timeout on wait_timeout and interactive_timeout

mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| connect_timeout          | 5     |
| delayed_insert_timeout   | 300   |
| innodb_lock_wait_timeout | 50    |
| interactive_timeout      | 28800 |
| net_read_timeout         | 30    |
| net_write_timeout        | 60    |
| slave_net_timeout        | 3600  |
| table_lock_wait_timeout  | 50    |
| wait_timeout             | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)

Set with:

set global wait_timeout=3;
set global interactive_timeout=3;

(and also set in your configuration file, for when your server restarts)

But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...

SVN undo delete before commit

svn revert deletedDirectory

Here's the documentation for the svn revert command.


EDIT

If deletedDirectory was deleted using rmdir and not svn rm, you'll need to do

svn update deletedDirectory

instead.

How to show all of columns name on pandas dataframe?

I had lots of duplicate column names, and once I ran

df = df.loc[:,~df.columns.duplicated()]

I was able to see the full list of columns

Credit: https://stackoverflow.com/a/40435354/5846417

How can I convert an image into Base64 string using JavaScript?

If you have a file object, this simple function will work:

function getBase64 (file, callback) {

    const reader = new FileReader();

    reader.addEventListener('load', () => callback(reader.result));

    reader.readAsDataURL(file);
}

Usage example:

getBase64(fileObjectFromInput, function(base64Data){
    console.log("Base64 of file is", base64Data); // Here you can have your code which uses Base64 for its operation, // file to Base64 by oneshubh
});

Merging cells in Excel using Apache POI

You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);

example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4)); will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).

for detail refer BusyDeveloper's Guide

How to list AD group membership for AD users using input list?

First: As it currently stands, the $User variable does not have a .Users property. In your code, $User simply represents one line (the "current" line in the foreach loop) from the text file.

$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof

Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:

  1. Query forest for list of domains
  2. Call Get-ADUser for each domain (you may have to specify alternate credentials via the -Credential parameter

Thirdly, to get a list of groups that a user is a member of:

$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';

# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins

Fourthly: To get the final, desired string format, simply add the $User.Name, a semicolon, and the $GroupMembership string together:

$User.SamAccountName + ';' + $GroupMembership;

Creating/writing into a new file in Qt

It can happen that the cause is not that you don't find the right directory. For example, you can read from the file (even without absolute path) but it seems you cannot write into it.

In that case, it might be that you program exits before the writing can be finished.

If your program uses an event loop (like with a GUI application, e.g. QMainWindow) it's not a problem. However, if your program exits immediately after writing to the file, you should flush the text stream, closing the file is not always enough (and it's unnecessary, as it is closed in the destructor).

stream << "something" << endl;
stream.flush();

This guarantees that the changes are committed to the file before the program continues from this instruction.

The problem seems to be that the QFile is destructed before the QTextStream. So, even if the stream is flushed in the QTextStream destructor, it's too late, as the file is already closed.

How to cast Object to boolean?

Assuming that yourObject.toString() returns "true" or "false", you can try

boolean b = Boolean.valueOf(yourObject.toString())

How to inject Javascript in WebBrowser control?

this is a solution using mshtml

IHTMLDocument2 doc = new HTMLDocumentClass();
doc.write(new object[] { File.ReadAllText(filePath) });
doc.close();

IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement("script");
scriptObject.type = @"text/javascript";
scriptObject.text = @"function btn1_OnClick(str){
    alert('you clicked' + str);
}";
((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject);

Best way to initialize (empty) array in PHP

$myArray = []; 

Creates empty array.

You can push values onto the array later, like so:

$myArray[] = "tree";
$myArray[] = "house";
$myArray[] = "dog";

At this point, $myArray contains "tree", "house" and "dog". Each of the above commands appends to the array, preserving the items that were already there.

Having come from other languages, this way of appending to an array seemed strange to me. I expected to have to do something like $myArray += "dog" or something... or maybe an "add()" method like Visual Basic collections have. But this direct append syntax certainly is short and convenient.

You actually have to use the unset() function to remove items:

unset($myArray[1]); 

... would remove "house" from the array (arrays are zero-based).

unset($myArray); 

... would destroy the entire array.

To be clear, the empty square brackets syntax for appending to an array is simply a way of telling PHP to assign the indexes to each value automatically, rather than YOU assigning the indexes. Under the covers, PHP is actually doing this:

$myArray[0] = "tree";
$myArray[1] = "house";
$myArray[2] = "dog";

You can assign indexes yourself if you want, and you can use any numbers you want. You can also assign index numbers to some items and not others. If you do that, PHP will fill in the missing index numbers, incrementing from the largest index number assigned as it goes.

So if you do this:

$myArray[10] = "tree";
$myArray[20] = "house";
$myArray[] = "dog";

... the item "dog" will be given an index number of 21. PHP does not do intelligent pattern matching for incremental index assignment, so it won't know that you might have wanted it to assign an index of 30 to "dog". You can use other functions to specify the increment pattern for an array. I won't go into that here, but its all in the PHP docs.

Cheers,

-=Cameron

Declare a variable as Decimal

To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

enter image description here

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub

enter image description here

Making RGB color in Xcode

You already got the right answer, but if you dislike the UIColor interface like me, you can do this:

#import "UIColor+Helper.h"
// ...
myLabel.textColor = [UIColor colorWithRGBA:0xA06105FF];

UIColor+Helper.h:

#import <UIKit/UIKit.h>

@interface UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color;
@end

UIColor+Helper.m:

#import "UIColor+Helper.h"

@implementation UIColor (Helper)

+ (UIColor *)colorWithRGBA:(NSUInteger)color
{
    return [UIColor colorWithRed:((color >> 24) & 0xFF) / 255.0f
                           green:((color >> 16) & 0xFF) / 255.0f
                            blue:((color >> 8) & 0xFF) / 255.0f
                           alpha:((color) & 0xFF) / 255.0f];
}

@end

Facebook database design?

Its a type of graph database: http://components.neo4j.org/neo4j-examples/1.2-SNAPSHOT/social-network.html

Its not related to Relational databases.

Google for graph databases.

Laravel Eloquent "WHERE NOT IN"

Query Builder:

DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();

Eloquent:

SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();

How to delete session cookie in Postman?

Manually deleting it in the chrome browser removes the cookie from Postman.

In your chrome browser go to chrome://settings/cookies

Find the cookie and delete it

Edit: As per Max890 comment below (in my version of Google Chrome (ver 63)) this is now chrome://settings/content/cookies Then go to "See all cookies and site data"

Update for Google Chrome 79.0.3945.88

chrome://settings/siteData?search=cookies

Get day of week using NSDate

Swift 3 Date extension

extension Date {
    var weekdayOrdinal: Int {
        return Calendar.current.component(.weekday, from: self)
    }
}

Call jQuery Ajax Request Each X Minutes

use jquery Every time Plugin .using this you can do ajax call for "X" time period

$("#select").everyTime(1000,function(i) {
//ajax call
}

you can also use setInterval

What is the best way to parse html in C#?

I think @Erlend's use of HTMLDocument is the best way to go. However, I have also had good luck using this simple library:

SgmlReader

How do I determine scrollHeight?

Correct ways in jQuery are -

  • $('#test').prop('scrollHeight') OR
  • $('#test')[0].scrollHeight OR
  • $('#test').get(0).scrollHeight

Not equal to != and !== in PHP

$a !== $b TRUE if $a is not equal to $b, or they are not of the same type

Please Refer to http://php.net/manual/en/language.operators.comparison.php

How to import a csv file into MySQL workbench?

I guess you're missing the ENCLOSED BY clause

LOAD DATA LOCAL INFILE '/path/to/your/csv/file/model.csv'
INTO TABLE test.dummy FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n';

And specify the csv file full path

Load Data Infile - MySQL documentation

How does HTTP file upload work?

Send file as binary content (upload without form or FormData)

In the given answers/examples the file is (most likely) uploaded with a HTML form or using the FormData API. The file is only a part of the data sent in the request, hence the multipart/form-data Content-Type header.

If you want to send the file as the only content then you can directly add it as the request body and you set the Content-Type header to the MIME type of the file you are sending. The file name can be added in the Content-Disposition header. You can upload like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

If you don't (want to) use forms and you are only interested in uploading one single file this is the easiest way to include your file in the request.

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebserverInteractionClassLibrary
{
    public class RequestManager
    {
        public string LastResponse { protected set; get; }

        CookieContainer cookies = new CookieContainer();

        internal string GetCookieValue(Uri SiteUri,string name)
        {
            Cookie cookie = cookies.GetCookies(SiteUri)[name];
            return (cookie == null) ? null : cookie.Value;
        }

        public string GetResponseContent(HttpWebResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            Stream dataStream = null;
            StreamReader reader = null;
            string responseFromServer = null;

            try
            {
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                reader = new StreamReader(dataStream);
                // Read the content.
                responseFromServer = reader.ReadToEnd();
                // Cleanup the streams and the response.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {                
                if (reader != null)
                {
                    reader.Close();
                }
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                response.Close();
            }
            LastResponse = responseFromServer;
            return responseFromServer;
        }

        public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
        }

        public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
        }

        internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            // Set the Method property of the request to POST.
            request.Method = method;
            // Set cookie container to maintain cookies
            request.CookieContainer = cookies;
            request.AllowAutoRedirect = allowAutoRedirect;
            // If login is empty use defaul credentials
            if (string.IsNullOrEmpty(login))
            {
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                request.Credentials = new NetworkCredential(login, password);
            }
            if (method == "POST")
            {
                // Convert POST data to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }
            return request;
        }

        internal HttpWebResponse GetResponse(HttpWebRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();                
                cookies.Add(response.Cookies);                
                // Print the properties of each cookie.
                Console.WriteLine("\nCookies: ");
                foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
                {
                    Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return response;
        }

    }
}

How do I get the full path of the current file's directory?

System: MacOS

Version: Python 3.6 w/ Anaconda

import os

rootpath = os.getcwd()

os.chdir(rootpath)

ng if with angular for string contains

ng-if="select.name.indexOf('?') !== -1" 

How do I prevent DIV tag starting a new line?

You can simply use:

#contentInfo_new br {display:none;}

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

If you are using eclipse and maven for handling dependencies, you may need to take these extra steps to make sure eclipse copies the dependencies properly Maven dependencies not visible in WEB-INF/lib (namely the Deployment Assembly for Dynamic web application)

How to sort an array of objects in Java?

[Employee(name=John, age=25, salary=3000.0, mobile=9922001), 
Employee(name=Ace, age=22, salary=2000.0, mobile=5924001), 
Employee(name=Keith, age=35, salary=4000.0, mobile=3924401)]


public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator
  = Comparator.comparing(Employee::getName);

Arrays.sort(employees, employeeNameComparator);

assertTrue(Arrays.equals(employees, sortedEmployeesByName));

}

result

[Employee(name=Ace, age=22, salary=2000.0, mobile=5924001), 
Employee(name=John, age=25, salary=3000.0, mobile=9922001), 
Employee(name=Keith, age=35, salary=4000.0, mobile=3924401)]

How do I hide an element on a click event anywhere outside of the element?

  $(document).on('click', function(e) { // Hides the div by clicking any where in the screen
        if ( $(e.target).closest('#suggest_input').length ) {
            $(".suggest_div").show();
        }else if ( ! $(e.target).closest('.suggest_container').length ) {
            $('.suggest_div').hide();
        }
    });

Here #suggest_input in is the name of textbox and .suggest_container is the ul class name and .suggest_div is the main div element for my auto-suggest.

this code is for hiding the div elements by clicking any where in the screen. Before doing every thing please understand the code and copy it...

How to style the menu items on an Android action bar

I did this way:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="android:actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="actionMenuTextColor">@color/colorAccent</item>
</style>

<style name="MenuTextAppearance" >
    <item name="android:textAppearance">@android:style/TextAppearance.Large</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
</style>

What does the "at" (@) symbol do in Python?

This code snippet:

def decorator(func):
   return func

@decorator
def some_func():
    pass

Is equivalent to this code:

def decorator(func):
    return func

def some_func():
    pass

some_func = decorator(some_func)

In the definition of a decorator you can add some modified things that wouldn't be returned by a function normally.

How to add a second x-axis in matplotlib

From matplotlib 3.1 onwards you may use ax.secondary_xaxis

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1,13, num=301)
y = (np.sin(x)+1.01)*3000

# Define function and its inverse
f = lambda x: 1/(1+x)
g = lambda x: 1/x-1

fig, ax = plt.subplots()
ax.semilogy(x, y, label='DM')

ax2 = ax.secondary_xaxis("top", functions=(f,g))

ax2.set_xlabel("1/(x+1)")
ax.set_xlabel("x")
plt.show()

Dealing with float precision in Javascript

You could do something like this:

> +(Math.floor(y/x)*x).toFixed(15);
1.2

How to name and retrieve a stash by name in git?

I don't think there is a way to git pop a stash by its name.

I have created a bash function that does it.

#!/bin/bash

function gstashpop {
  IFS="
"
  [ -z "$1" ] && { echo "provide a stash name"; return; }
  index=$(git stash list | grep -e ': '"$1"'$' | cut -f1 -d:)
  [ "" == "$index" ] && { echo "stash name $1 not found"; return; }
  git stash apply "$index"
}

Example of usage:

[~/code/site] on master*
$ git stash push -m"here the stash name"
Saved working directory and index state On master: here the stash name

[~/code/site] on master
$ git stash list
stash@{0}: On master: here the stash name

[~/code/site] on master
$ gstashpop "here the stash name"

I hope it helps!

sql ORDER BY multiple values in specific order?

Use a case switch to translate the codes into numbers that can be sorted:

ORDER BY
  case x_field
  when 'f' then 1
  when 'p' then 2
  when 'i' then 3
  when 'a' then 4
  else 5
  end

Initialize a vector array of strings

 const char* args[] = {"01", "02", "03", "04"};
 std::vector<std::string> v(args, args + 4);

And in C++0x, you can take advantage of std::initializer_list<>:

http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists

How do I use $scope.$watch and $scope.$apply in AngularJS?

I found very in-depth videos which cover $watch, $apply, $digest and digest cycles in:

Following are a couple of slides used in those videos to explain the concepts (just in case, if the above links are removed/not working).

Enter image description here

In the above image, "$scope.c" is not being watched as it is not used in any of the data bindings (in markup). The other two ($scope.a and $scope.b) will be watched.

Enter image description here

From the above image: Based on the respective browser event, AngularJS captures the event, performs digest cycle (goes through all the watches for changes), execute watch functions and update the DOM. If not browser events, the digest cycle can be manually triggered using $apply or $digest.

More about $apply and $digest:

Enter image description here

Laravel Checking If a Record Exists

Simple, comfortable and understandable with Validator

class CustomerController extends Controller
{
    public function register(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:customers',
            'phone' => 'required|string|max:255|unique:customers',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response(['errors' => $validator->errors()->all()], 422);
        }

Using psql to connect to PostgreSQL in SSL mode

Well, you cloud provide all the information with following command in CLI, if connection requires in SSL mode:

psql "sslmode=verify-ca sslrootcert=server-ca.pem sslcert=client-cert.pem sslkey=client-key.pem hostaddr=your_host port=5432 user=your_user dbname=your_db" 

how does unix handle full path name with space and arguments?

Also be careful with double-quotes -- on the Unix shell this expands variables. Some are obvious (like $foo and \t) but some are not (like !foo).

For safety, use single-quotes!

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

In python 3 urllib2 was merged into urllib. See also another Stack Overflow question and the urllib PEP 3108.

To make Python 2 code work in Python 3:

try:
    import urllib.request as urllib2
except ImportError:
    import urllib2

How do I import an existing Java keystore (.jks) file into a Java installation?

You can bulk import all aliases from one keystore to another:

keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks

Copy rows from one Datatable to another DataTable?

Check this out, you may like it (previously, please, clone table1 to table2):

table1.AsEnumerable().Take(recodCount).CopyToDataTable(table2,LoadOption.OverwriteChanges);

Or:

table1.AsEnumerable().Where ( yourcondition  ) .CopyToDataTable(table2,LoadOption.OverwriteChanges);

How to get the current time in milliseconds from C in Linux?

Use gettimeofday() to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.

how to use concatenate a fixed string and a variable in Python

variable=" Hello..."  
print (variable)  
print("This is the Test File "+variable)  

for integer type ...

variable="  10"  
print (variable)  
print("This is the Test File "+str(variable))  

Copying the cell value preserving the formatting from one cell to another in excel using VBA

Using Excel 2010 ? Try

Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Try one of these:

  1. Use column alias:

    ORDER BY RadioServiceCodeId,RadioService

  2. Use column position:

    ORDER BY 1,2

You can only order by columns that actually appear in the result of the DISTINCT query - the underlying data isn't available for ordering on.

Is there a method for String conversion to Title Case?

This should work:

String str="i like pancakes";
String arr[]=str.split(" ");
String strNew="";
for(String str1:arr)
{
    Character oldchar=str1.charAt(0);
    Character newchar=Character.toUpperCase(str1.charAt(0));
    strNew=strNew+str1.replace(oldchar,newchar)+" ";    
}
System.out.println(strNew);

How to disable margin-collapsing?

You can also use the good old micro clearfix for this.

#container::before, #container::after{
    content: ' ';
    display: table;
}

See updated fiddle: http://jsfiddle.net/XB9wX/97/

indexOf Case Sensitive?

Yes, it is case-sensitive. You can do a case-insensitive indexOf by converting your String and the String parameter both to upper-case before searching.

String str = "Hello world";
String search = "hello";
str.toUpperCase().indexOf(search.toUpperCase());

Note that toUpperCase may not work in some circumstances. For instance this:

String str = "Feldbergstraße 23, Mainz";
String find = "mainz";
int idxU = str.toUpperCase().indexOf (find.toUpperCase ());
int idxL = str.toLowerCase().indexOf (find.toLowerCase ());

idxU will be 20, which is wrong! idxL will be 19, which is correct. What's causing the problem is tha toUpperCase() converts the "ß" character into TWO characters, "SS" and this throws the index off.

Consequently, always stick with toLowerCase()

Add borders to cells in POI generated Excel File

In the newer apache poi versions:

XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.MEDIUM);
style.setBorderBottom(BorderStyle.MEDIUM);
style.setBorderLeft(BorderStyle.MEDIUM);
style.setBorderRight(BorderStyle.MEDIUM);

How do I determine the size of an object in Python?

Python 3.8 (Q1 2019) will change some of the results of sys.getsizeof, as announced here by Raymond Hettinger:

Python containers are 8 bytes smaller on 64-bit builds.

tuple ()  48 -> 40       
list  []  64 ->56
set()    224 -> 216
dict  {} 240 -> 232

This comes after issue 33597 and Inada Naoki (methane)'s work around Compact PyGC_Head, and PR 7043

This idea reduces PyGC_Head size to two words.

Currently, PyGC_Head takes three words; gc_prev, gc_next, and gc_refcnt.

  • gc_refcnt is used when collecting, for trial deletion.
  • gc_prev is used for tracking and untracking.

So if we can avoid tracking/untracking while trial deletion, gc_prev and gc_refcnt can share same memory space.

See commit d5c875b:

Removed one Py_ssize_t member from PyGC_Head.
All GC tracked objects (e.g. tuple, list, dict) size is reduced 4 or 8 bytes.

Send form data with jquery ajax json

Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo '<pre>';
    print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="[email protected]" />
<button type="submit">Send!</button>

With AJAX you are able to do exactly the same thing, only without page refresh.

Paste in insert mode?

If you don't want Vim to mangle formatting in incoming pasted text, you might also want to consider using: :set paste. This will prevent Vim from re-tabbing your code. When done pasting, :set nopaste will return to the normal behavior.

It's also possible to toggle the mode with a single key, by adding something like set pastetoggle=<F2> to your .vimrc. More details on toggling auto-indent are here.

An unhandled exception occurred during the execution of the current web request. ASP.NET

I had the same problem and found out that I had forgotten to include the script in the file which I want to include in the live site.

Also, you should try this:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

How can I force a long string without any blank to be wrapped?

If you're using PHP then the wordwrap function works well for this: http://php.net/manual/en/function.wordwrap.php

The CSS solution word-wrap: break-word; does not seem to be consistent across all browsers.

Other server-side languages have similar functions - or can be hand built.

Here's how the the PHP wordwrap function works:

$string = "ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTCGATGTAGCTAGTAGCATGTAGTGA";

$wrappedstring = wordwrap($string,50,"&lt;br&gt;",true);

This wraps the string at 50 characters with a <br> tag. The 'true' parameter forces the string to be cut.

if else in a list comprehension

One way:

def change(f):
    if f is None:
        return unicode(f.strip())
    else:
        return ''

row = [change(x) for x in row]

Although then you have:

row = map(change, row)

Or you can use a lambda inline.

How to access parameters in a Parameterized Build?

I think the variable is available directly, rather than through env, when using Workflow plugin. Try:

node()
{
    print "DEBUG: parameter foo = ${foo}"
}

Read all worksheets in an Excel workbook into an R list with data.frames

You can load the work book and then use lapply, getSheets and readWorksheet and do something like this.

wb.mtcars <- loadWorkbook(system.file("demoFiles/mtcars.xlsx", 
                          package = "XLConnect"))
sheet_names <- getSheets(wb.mtcars)
names(sheet_names) <- sheet_names

sheet_list <- lapply(sheet_names, function(.sheet){
    readWorksheet(object=wb.mtcars, .sheet)})

How to generate a random String in Java

You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.

java.util.UUID.randomUUID().toString()

http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html

How to find where javaw.exe is installed?

Open a cmd shell,

cd \\
dir javaw.exe /s

How to change dataframe column names in pyspark?

Another way to rename just one column (using import pyspark.sql.functions as F):

df = df.select( '*', F.col('count').alias('new_count') ).drop('count')

Batch script to delete files

There's multiple ways of doing things in batch, so if escaping with a double percent %% isn't working for you, then you could try something like this:

set olddir=%CD%
cd /d "path of folder"
del "file name/ or *.txt etc..."
cd /d "%olddir%"

How this works:

set olddir=%CD% sets the variable "olddir" or any other variable name you like to the directory your batch file was launched from.

cd /d "path of folder" changes the current directory the batch will be looking at. keep the quotations and change path of folder to which ever path you aiming for.

del "file name/ or *.txt etc..." will delete the file in the current directory your batch is looking at, just don't add a directory path before the file name and just have the full file name or, to delete multiple files with the same extension with *.txt or whatever extension you need.

cd /d "%olddir%" takes the variable saved with your old path and goes back to the directory you started the batch with, its not important if you don't want the batch going back to its previous directory path, and like stated before the variable name can be changed to whatever you wish by changing the set olddir=%CD% line.

ipad safari: disable scrolling, and bounce effect?

You can also change the position of the body/html to fixed:

body,
html {
  position: fixed;
}

Get item in the list in Scala?

Why parentheses?

Here is the quote from the book programming in scala.

Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So greetStrings(i) gets transformed into greetStrings.apply(i). Thus accessing an element of an array in Scala is simply a method call like any other. This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an apply method call. Of course this will compile only if that type of object actually defines an apply method. So it's not a special case; it's a general rule.

Here are a few examples how to pull certain element (first elem in this case) using functional programming style.

  // Create a multdimension Array 
  scala> val a = Array.ofDim[String](2, 3)
  a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
  scala> a(0) = Array("1","2","3")
  scala> a(1) = Array("4", "5", "6")
  scala> a
  Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))

  // 1. paratheses
  scala> a.map(_(0))
  Array[String] = Array(1, 4)
  // 2. apply
  scala> a.map(_.apply(0))
  Array[String] = Array(1, 4)
  // 3. function literal
  scala> a.map(a => a(0))
  Array[String] = Array(1, 4)
  // 4. lift
  scala> a.map(_.lift(0))
  Array[Option[String]] = Array(Some(1), Some(4))
  // 5. head or last 
  scala> a.map(_.head)
  Array[String] = Array(1, 4)

sqlite database default time value 'now'

It may be better to use REAL type, to save storage space.

Quote from 1.2 section of Datatypes In SQLite Version 3

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    t REAL DEFAULT (datetime('now', 'localtime'))
);

see column-constraint .

And insert a row without providing any value.

INSERT INTO "test" DEFAULT VALUES;

Get string between two strings in a string

  private string gettxtbettwen(string txt, string first, string last)
    {

        StringBuilder sb = new StringBuilder(txt);
        int pos1 = txt.IndexOf(first)  + first.Length;
        int len = (txt.Length ) - pos1;

        string reminder = txt.Substring(pos1, len);


        int pos2 = reminder.IndexOf(last) - last.Length +1;


       



        return reminder.Substring(0, pos2); 



    }

Print JSON parsed object?

Just use

console.info("CONSOLE LOG : ")
console.log(response);
console.info("CONSOLE DIR : ")
console.dir(response);

and you will get this in chrome console :

CONSOLE LOG : 
facebookSDK_JS.html:56 Object {name: "Diego Matos", id: "10155988777540434"}
facebookSDK_JS.html:57 CONSOLE DIR : 
facebookSDK_JS.html:58 Objectid: "10155988777540434"name: "Diego Matos"__proto__: Object

How to specify multiple return types using type-hints

The statement def foo(client_id: str) -> list or bool: when evaluated is equivalent to def foo(client_id: str) -> list: and will therefore not do what you want.

The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:

If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation. You can also indicate that None could be returned with Optional[list]

How do I install command line MySQL client on mac?

If you have already installed MySQL from the disk image (dmg) from http://dev.mysql.com/downloads/), open a terminal, run:

echo 'export PATH=/usr/local/mysql/bin:$PATH' >> ~/.bash_profile

then, reload .bash_profile by running following command:

 . ~/.bash_profile

You can now use mysql to connect to any mysql server:

mysql -h xxx.xxx.xxx.xxx -u username -p

Credit & Reference: http://www.gigoblog.com/2011/03/13/add-mysql-to-terminal-shell-in-mac-os-x/

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You 100% can do this on the server side...

     Protected Sub Button3_Click(sender As Object, e As System.EventArgs)
    MesgBox("Test")
End Sub

Private Sub MesgBox(ByVal sMessage As String)
    Dim msg As String
    msg = "<script language='javascript'>"
    msg += "alert('" & sMessage & "');"
    msg += "</script>"
    Response.Write(msg)
End Sub

here is actually a whole slew of ways to go about this http://www.sislands.com/coin70/week1/dialogbox.htm

How to dynamically allocate memory space for a string and get that string from user?

realloc is a pretty expensive action... here's my way of receiving a string, the realloc ratio is not 1:1 :

char* getAString()
{    
    //define two indexes, one for logical size, other for physical
    int logSize = 0, phySize = 1;  
    char *res, c;

    res = (char *)malloc(sizeof(char));

    //get a char from user, first time outside the loop
    c = getchar();

    //define the condition to stop receiving data
    while(c != '\n')
    {
        if(logSize == phySize)
        {
            phySize *= 2;
            res = (char *)realloc(res, sizeof(char) * phySize);
        }
        res[logSize++] = c;
        c = getchar();
    }
    //here we diminish string to actual logical size, plus one for \0
    res = (char *)realloc(res, sizeof(char *) * (logSize + 1));
    res[logSize] = '\0';
    return res;
}

Get latest from Git branch

If you have forked a repository fro Delete your forked copy and fork it again from master.

Where does Anaconda Python install on Windows?

This one is easy. When you start the installation, Anaconda asks "Destination Folder" as below screenshot. If you are not sure where did default installation go, double click setup file and see what anaconda offers as a default location.
Anaconda image

Where is `%p` useful with printf?

x is used to print t pointer argument in hexadecimal.

A typical address when printed using %x would look like bfffc6e4 and the sane address printed using %p would be 0xbfffc6e4

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

How to delete multiple values from a vector?

First we can define a new operator,

"%ni%" = Negate( "%in%" )

Then, its like x not in remove

x <- 1:10
remove <- c(2,3,5)
x <- x[ x %ni% remove ]

or why to go for remove, go directly

x <- x[ x %ni% c(2,3,5)]

PDF to image using Java

You will need a PDF renderer. There are a few more or less good ones on the market (ICEPdf, pdfrenderer), but without, you will have to rely on external tools. The free PDF renderers also cannot render embedded fonts, and so will only be good for creating thumbnails (what you eventually want).

My favorite external tool is Ghostscript, which can convert PDFs to images with a single command line invocation.

This converts Postscript (and PDF?) files to bmp for us, just as a guide to modify for your needs (Know you need the env vars for gs to work!):

pushd 
setlocal

Set BIN_DIR=C:\Program Files\IKOffice_ACME\bin
Set GS=C:\Program Files\IKOffice_ACME\gs
Set GS_DLL=%GS%\gs8.54\bin\gsdll32.dll
Set GS_LIB=%GS%\gs8.54\lib;%GS%\gs8.54\Resource;%GS%\fonts
Set Path=%Path%;%GS%\gs8.54\bin
Set Path=%Path%;%GS%\gs8.54\lib

call "%GS%\gs8.54\bin\gswin32c.exe" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE#bmpmono -r600x600 -sOutputFile#%2 -f %1

endlocal
popd

UPDATE: pdfbox is now able to embed fonts, so no need for Ghostscript anymore.

How do I discover memory usage of my application in Android?

Android Studio 0.8.10+ has introduced an incredibly useful tool called Memory Monitor.

enter image description here

What it's good for:

  • Showing available and used memory in a graph, and garbage collection events over time.
  • Quickly testing whether app slowness might be related to excessive garbage collection events.
  • Quickly testing whether app crashes may be related to running out of memory.

enter image description here

Figure 1. Forcing a GC (Garbage Collection) event on Android Memory Monitor

You can have plenty good information on your app's RAM real-time consumption by using it.

GDB: break if variable equal value

First, you need to compile your code with appropriate flags, enabling debug into code.

$ gcc -Wall -g -ggdb -o ex1 ex1.c

then just run you code with your favourite debugger

$ gdb ./ex1

show me the code.

(gdb) list
1   #include <stdio.h>
2   int main(void)
3   { 
4     int i = 0;
5     for(i=0;i<7;++i)
6       printf("%d\n", i);
7   
8     return 0;
9   }

break on lines 5 and looks if i == 5.

(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i

checking breakpoints

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004fb in main at ex1.c:5
    breakpoint already hit 1 time
5       read watchpoint keep y                      i
    stop only if i==5

running the program

(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i

Value = 5
0x0000000000400523 in main () at ex1.c:5
5     for(i=0;i<7;++i)

JAXB Exception: Class not known to this context

I had this error because I registered the wrong class in this line of code:

JAXBContext context = JAXBContext.newInstance(MyRootXmlClass.class);

Best way to reset an Oracle sequence to the next value in an existing column?

You can temporarily increase the cache size and do one dummy select and then reset the cache size back to 1. So for example

ALTER SEQUENCE mysequence INCREMENT BY 100;

select mysequence.nextval from dual;

ALTER SEQUENCE mysequence INCREMENT BY 1;

Constraint Layout Vertical Align Center

Two buttons one centered one below to the left of it

Showing it graphically.

Centering on parent is done by constraining both sides to the parent. You can the constrain additional objects off of the centered object.

Note. Each arrow represents a "app:layout_constraintXXX_toYYY=" attribute. (6 in the picture)

Authenticate Jenkins CI for Github private repository

An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.

(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)

How to add List<> to a List<> in asp.net

Try using list.AddRange(VTSWeb.GetDailyWorktimeViolations(VehicleID2));

Outputting data from unit test in Python

I think I might have been overthinking this. One way I've come up with that does the job, is simply to have a global variable, that accumulates the diagnostic data.

Somthing like this:

log1 = dict()
class TestBar(unittest.TestCase):
    def runTest(self):
        for t1, t2 in testdata:
            f = Foo(t1) 
            if f.bar(t2) != 2: 
                log1("TestBar.runTest") = (f, t1, t2)
                self.fail("f.bar(t2) != 2")

Thanks for the replies. They have given me some alternative ideas for how to record information from unit tests in python.

Text size of android design TabLayout tabs

>   **create custom style in styles.xml**  <style name="customStylename"
> parent="Theme.AppCompat">
>         <item name="android:textSize">22sp</item>  <item name="android:color">colors/primarydark</item>
>     </style>
> 
>   **link to your material same name **  
> <android.support.design.widget.TabLayout  
> android:layout_width="match_parent"
>         android:layout_height="wrap_content" 
>         android:id="@+id/tabs"
>         app:tabTextAppearance="@style/customStylename" 
>       />

this is my solution

How can I convert String to Int?

This works for me:

using System;

namespace numberConvert
{
    class Program
    {
        static void Main(string[] args)
        {
            string numberAsString = "8";
            int numberAsInt = int.Parse(numberAsString);
        }
    }
}

Getting an "ambiguous redirect" error

I just had this error in a bash script. The issue was an accidental \ at the end of the previous line that was giving an error.

How to convert a byte to its binary string representation

You could check each bit on the byte then append either 0 or 1 to a string. Here is a little helper method I wrote for testing:

public static String byteToString(byte b) {
    byte[] masks = { -128, 64, 32, 16, 8, 4, 2, 1 };
    StringBuilder builder = new StringBuilder();
    for (byte m : masks) {
        if ((b & m) == m) {
            builder.append('1');
        } else {
            builder.append('0');
        }
    }
    return builder.toString();
}

What is sys.maxint in Python 3?

Python 3.0 doesn't have sys.maxint any more since Python 3's ints are of arbitrary length. Instead of sys.maxint it has sys.maxsize; the maximum size of a positive sized size_t aka Py_ssize_t.

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

GUI Tool for PostgreSQL

Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.

http://www.enterprisedb.com/products-services-training/products/postgres-enterprise-manager

Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.

Is there a way to run Python on Android?

Pygame Subset for Android

Pygame is a 2D game engine for Python (on desktop) that is popular with new programmers. The Pygame Subset for Android describes itself as...

...a port of a subset of Pygame functionality to the Android platform. The goal of the project is to allow the creation of Android-specific games, and to ease the porting of games from PC-like platforms to Android.

The examples include a complete game packaged as an APK, which is pretty interesting.

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

just put #login-box before <h2>Welcome</h2> will be ok.

<div class='container'>
    <div class='hero-unit'>
        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>
        <h2>Welcome</h2>

        <p>Please log in</p>

    </div>
</div>

here is jsfiddle http://jsfiddle.net/SyjjW/4/

ERROR 1049 (42000): Unknown database 'mydatabasename'

mysql -uroot -psecret mysql < mydatabase.sql

findAll() in yii

Just to add some alternate, you could do like this also:

$id =101;
$criteria = new CDbCriteria();
$criteria->condition = "email_id =:email_id";
$criteria->params = array(':email_id' => $id);
$comments = EmailArchive::model()->findAll($criteria);

How do I find out what License has been applied to my SQL Server installation?

When I run:

   exec sp_readerrorlog @p1 = 0
   ,@p2 = 1
   ,@p3 = N'licensing'

I get:

SQL Server detected 2 sockets with 21 cores per socket and 21 logical processors per socket, 42 total logical processors; using 20 logical processors based on SQL Server licensing. This is an informational message; no user action is required.

also, SELECT @@VERSION shows:

Microsoft SQL Server 2014 (SP1-GDR) (KB4019091) - 12.0.4237.0 (X64) Jul 5 2017 22:03:42 Copyright (c) Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.3 (Build 9600: ) (Hypervisor)

This is a VM

How do I install Composer on a shared hosting?

SIMPLE SOLUTION (tested on Red Hat):

run command: curl -sS https://getcomposer.org/installer | php

to use it: php composer.phar

SYSTEM WIDE SOLLUTION (tested on Red Hat):

run command: mv composer.phar /usr/local/bin/composer

to use it: composer update

now you can call composer from any directory.

Source: http://www.agix.com.au/install-composer-on-centosredhat/

Can you force Vue.js to reload/re-render?

Try this magic spell:

vm.$forceUpdate();

No need to create any hanging vars :)

Update: I found this solution when I only started working with VueJS. However further exploration proved this approach as a crutch. As far as I recall, in a while I got rid of it simply putting all the properties that failed to refresh automatically (mostly nested ones) into computed properties.

More info here: https://vuejs.org/v2/guide/computed.html

Visual Studio: ContextSwitchDeadlock

As Pedro said, you have an issue with the debugger preventing the message pump if you are stepping through code.

But if you are performing a long running operation on the UI thread, then call Application.DoEvents() which explicitly pumps the message queue and then returns control to your current method.

However if you are doing this I would recommend at looking at your design so that you can perform processing off the UI thread so that your UI remains nice and snappy.

What is the best way to implement a "timer"?

Use the Timer class.

public static void Main()
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 5000;
    aTimer.Enabled = true;

    Console.WriteLine("Press \'q\' to quit the sample.");
    while(Console.Read() != 'q');
}

 // Specify what you want to happen when the Elapsed event is raised.
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     Console.WriteLine("Hello World!");
 }

The Elapsed event will be raised every X amount of milliseconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify. In the example above, it is OnTimedEvent.

Illegal mix of collations error in MySql

I had this problem not because I'm storing in different collations, but because my column type is JSON, which is binary.

Fixed it like this:

select table.field COLLATE utf8mb4_0900_ai_ci AS fieldName

javax.faces.application.ViewExpiredException: View could not be restored

I add the following configuration to web.xml and it got resolved.

<context-param>
    <param-name>com.sun.faces.numberOfViewsInSession</param-name>
    <param-value>500</param-value>
</context-param>
<context-param>
    <param-name>com.sun.faces.numberOfLogicalViews</param-name>
    <param-value>500</param-value>
</context-param>

Application Crashes With "Internal Error In The .NET Runtime"

In my case the problem was related to "Referencing .NET standard library in classic asp.net projects" and these two issues

https://github.com/dotnet/standard/issues/873

https://github.com/App-vNext/Polly/issues/628

and downgrading to Polly v6 was enough to workaround it

What data type to use for hashed password field and what length?

I've always tested to find the MAX string length of an encrypted string and set that as the character length of a VARCHAR type. Depending on how many records you're going to have, it could really help the database size.

JavaScript and getElementById for multiple elements with the same ID

The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.

Insert a row to pandas dataframe

concat() seems to be a bit faster than last row insertion and reindexing. In case someone would wonder about the speed of two top approaches:

In [x]: %%timeit
     ...: df = pd.DataFrame(columns=['a','b'])
     ...: for i in range(10000):
     ...:     df.loc[-1] = [1,2]
     ...:     df.index = df.index + 1
     ...:     df = df.sort_index()

17.1 s ± 705 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [y]: %%timeit
     ...: df = pd.DataFrame(columns=['a', 'b'])
     ...: for i in range(10000):
     ...:     df = pd.concat([pd.DataFrame([[1,2]], columns=df.columns), df])

6.53 s ± 127 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

'sprintf': double precision in C

The problem is with sprintf

sprintf(aa,"%lf",a);

%lf says to interpet "a" as a "long double" (16 bytes) but it is actually a "double" (8 bytes). Use this instead:

sprintf(aa, "%f", a);

More details here on cplusplus.com

Insecure content in iframe on secure page

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

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

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


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

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

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

Tested and works in firefox.

Other Methods:

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

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

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

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

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

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

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

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

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

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

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

How to make RatingBar to show five stars

To show a simple star rating in round figure just use this code

public static String getIntToStar(int starCount) {
        String fillStar = "\u2605";
        String blankStar = "\u2606";
        String star = "";

        for (int i = 0; i < starCount; i++) {
            star = star.concat(" " + fillStar);
        }
        for (int j = (5 - starCount); j > 0; j--) {
            star = star.concat(" " + blankStar);
        }
        return star;
    }

And use it like this

button.setText(getIntToStar(4));

Routing for custom ASP.NET MVC 404 Error page

I had the same problem, the thing you have to do is, instead of adding the customErrors attribute in the web.config file in your Views folder, you have to add it in the web.config file in your projects root folder

Cross Domain Form POSTing

The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:

<form action="http://someotherserver.com">

and there is no javascript involved in posting the form, then the same origin policy is not applicable.

See wikipedia for more information

How do I use Ruby for shell scripting?

The answer by webmat is perfect. I just want to point you to a addition. If you have to deal a lot with command line parameters for your scripts, you should use optparse. It is simple and helps you tremendously.

Hash table runtime complexity (insert, search and delete)

Hash tables are O(1) average and amortized case complexity, however it suffers from O(n) worst case time complexity. [And I think this is where your confusion is]

Hash tables suffer from O(n) worst time complexity due to two reasons:

  1. If too many elements were hashed into the same key: looking inside this key may take O(n) time.
  2. Once a hash table has passed its load balance - it has to rehash [create a new bigger table, and re-insert each element to the table].

However, it is said to be O(1) average and amortized case because:

  1. It is very rare that many items will be hashed to the same key [if you chose a good hash function and you don't have too big load balance.
  2. The rehash operation, which is O(n), can at most happen after n/2 ops, which are all assumed O(1): Thus when you sum the average time per op, you get : (n*O(1) + O(n)) / n) = O(1)

Note because of the rehashing issue - a realtime applications and applications that need low latency - should not use a hash table as their data structure.

EDIT: Annother issue with hash tables: cache
Another issue where you might see a performance loss in large hash tables is due to cache performance. Hash Tables suffer from bad cache performance, and thus for large collection - the access time might take longer, since you need to reload the relevant part of the table from the memory back into the cache.

AngularJS - value attribute for select

If you use the track by option, the value attribute is correctly written, e.g.:

<div ng-init="a = [{label: 'one', value: 15}, {label: 'two', value: 20}]">
    <select ng-model="foo" ng-options="x for x in a track by x.value"/>
</div>

produces:

<select>
    <option value="" selected="selected"></option>
    <option value="15">one</option>
    <option value="20">two</option>
</select>

Least common multiple for 3 or more numbers

I just figured this out in Haskell:

lcm' :: Integral a => a -> a -> a
lcm' a b = a`div`(gcd a b) * b
lcm :: Integral a => [a] -> a
lcm (n:ns) = foldr lcm' n ns

I even took the time to write my own gcd function, only to find it in Prelude! Lots of learning for me today :D

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

Some of the sites are speaking SSLv2, or at least sending an SSLv2 server-hello, and your client doesn't speak, or isn't configured to speak, SSLv2. You need to make a policy decision here. SSLv2 should have vanished from the face of the earth years ago, and sites that still use it are insecure. However, if you gotta talk to them, you just have to enable it at your end, if you can. I would complain to the site owners though if you can.