Programs & Examples On #Gutter

Gutters are desirable white space between columns that makes for better legibility.

How to adjust gutter in Bootstrap 3 grid system?

(Posted on behalf of the OP).

I believe I figured it out.

In my case, I added [class*="col-"] {padding: 0 7.5px;};.

Then added .row {margin: 0 -7.5px;}.

This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;} to .row {margin: 0 -8.5px;}, then it works perfectly.

I have no idea why there is a 1px margin. Maybe someone can explain it?

See the sample I created:

Demo
Code

Bootstrap 3 Gutter Size

If you use sass in your own project, you can override the default bootstrap gutter size by copy pasting the sass variables from bootstrap's _variables.scss file into your own projects sass file somewhere, like:

// Grid columns
//
// Set the number of columns and specify the width of the gutters.
$grid-gutter-width-base:     50px !default;
$grid-gutter-widths: (
        xs: $grid-gutter-width-base,
        sm: $grid-gutter-width-base,
        md: $grid-gutter-width-base,
        lg: $grid-gutter-width-base,
        xl: $grid-gutter-width-base
) !default;

Now your gutters will be 50px instead of 30px. I find this to be the cleanest method to adjust the gutter size.

React JS onClick event handler

_x000D_
_x000D_
class FrontendSkillList extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { selectedSkill: {} };_x000D_
  }_x000D_
  render() {_x000D_
    return (_x000D_
      <ul>_x000D_
        {this.props.skills.map((skill, i) => (_x000D_
            <li_x000D_
              className={_x000D_
                this.state.selectedSkill.id === skill.id ? "selected" : ""_x000D_
              }_x000D_
              onClick={this.selectSkill.bind(this, skill)}_x000D_
              style={{ cursor: "pointer" }}_x000D_
              key={skill.id}_x000D_
            >_x000D_
            {skill.name}_x000D_
            </li>_x000D_
        ))}_x000D_
      </ul>_x000D_
    );_x000D_
  }_x000D_
_x000D_
  selectSkill(selected) {_x000D_
    if (selected.id !== this.state.selectedSkill.id) {_x000D_
      this.setState({ selectedSkill: selected });_x000D_
    } else {_x000D_
      this.setState({ selectedSkill: {} });_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
const data = [_x000D_
  { id: "1", name: "HTML5" },_x000D_
  { id: "2", name: "CSS3" },_x000D_
  { id: "3", name: "ES6 & ES7" }_x000D_
];_x000D_
const element = (_x000D_
  <div>_x000D_
    <h1>Frontend Skill List</h1>_x000D_
    <FrontendSkillList skills={data} />_x000D_
  </div>_x000D_
);_x000D_
ReactDOM.render(element, document.getElementById("root"));
_x000D_
.selected {_x000D_
  background-color: rgba(217, 83, 79, 0.8);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

@user544079 Hope this demo can help :) I recommend changing background color by toggling classname.

Detecting the character encoding of an HTTP POST request

Try setting the charset on your Content-Type:

httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );

SQL Server : check if variable is Empty or NULL for WHERE clause

If you can use some dynamic query, you can use LEN . It will give false on both empty and null string. By this way you can implement the option parameter.

ALTER PROCEDURE [dbo].[psProducts] 
(@SearchType varchar(50))
AS
BEGIN
    SET NOCOUNT ON;

DECLARE @Query nvarchar(max) = N'
    SELECT 
        P.[ProductId],
        P.[ProductName],
        P.[ProductPrice],
        P.[Type]
    FROM [Product] P'
    -- if @Searchtype is not null then use the where clause
    SET @Query = CASE WHEN LEN(@SearchType) > 0 THEN @Query + ' WHERE p.[Type] = ' + ''''+ @SearchType + '''' ELSE @Query END   

    EXECUTE sp_executesql @Query
    PRINT @Query
END

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

    //source    
    public async Task<string> methodName()
            {
             return Data;
             }

    //Consumption
     methodName().Result;

Hope this helps :)

How do I delete a local repository in git?

In the repository directory you remove the directory named .git and that's all :). On Un*x it is hidden, so you might not see it from file browser, but

cd repository-path/
rm -r .git

should do the trick.

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".

Writing to CSV with Python adds blank lines

import csv

hello = [['Me','You'],['293', '219'],['13','15']]
length = len(hello[0])

with open('test1.csv', 'wb') as testfile:
    csv_writer = csv.writer(testfile)
    for y in range(length):
        csv_writer.writerow([x[y] for x in hello])

will produce an output like this

Me You
293 219
13 15

Hope this helps

OpenCV !_src.empty() in function 'cvtColor' error

I had the same problem and it turned out that my image names included special characters (e.g. château.jpg), which could not bet handled by cv2.imread. My solution was to make a temporary copy of the file, renaming it e.g. temp.jpg, which could be loaded by cv2.imread without any problems.

Note: I did not check the performance of shutil.copy2 vice versa other options. So probably there is a better/faster solution to make a temporary copy.

import shutil, sys, os, dlib, glob, cv2

for f in glob.glob(os.path.join(myfolder_path, "*.jpg")):
    shutil.copy2(f, myfolder_path + 'temp.jpg')
    img = cv2.imread(myfolder_path + 'temp.jpg')
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    os.remove(myfolder_path + 'temp.jpg')

If there are only few files with special characters, renaming can also be done as an exeption, e.g.

for f in glob.glob(os.path.join(myfolder_path, "*.jpg")):
    try:
        img = cv2.imread(f)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    except:
        shutil.copy2(f, myfolder_path + 'temp.jpg')
        img = cv2.imread(myfolder_path + 'temp.jpg')
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        os.remove(myfolder_path + 'temp.jpg')

How to plot ROC curve in Python

The previous answers assume that you indeed calculated TP/Sens yourself. It's a bad idea to do this manually, it's easy to make mistakes with the calculations, rather use a library function for all of this.

the plot_roc function in scikit_lean does exactly what you need: http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html

The essential part of the code is:

  for i in range(n_classes):
      fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
      roc_auc[i] = auc(fpr[i], tpr[i])

How to check Django version

you can import django and then type print statement as given below to know the version of django i.e. installed on your system:

>>> import django
>>> print(django.get_version())
2.1

How do I force Robocopy to overwrite files?

I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:

FOR /F "tokens=*" %G IN ('dir /b') DO robocopy  "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0

As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.

It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.

Get docker container id from container name

Thanks for the answer of https://stackoverflow.com/a/65513726/889126, it gave me an idea to make a complete bash script as it is

export api_image_id=$(docker inspect --format="{{.Id}}" <image-name> | sed '/^[[:space:]]*$/d')

sudo docker exec -i -t ${api_image_id} /bin/bash

I need a specific container and make a script to extract some info from it in a quick sight.

Hope this would help others.

Turn off enclosing <p> tags in CKEditor 3.0

Try this in config.js

CKEDITOR.editorConfig = function( config )
{
config.enterMode = CKEDITOR.ENTER_BR;
config.shiftEnterMode = CKEDITOR.ENTER_BR;
};

How to list active connections on PostgreSQL?

Following will give you active connections/ queries in postgres DB-

SELECT 
    pid
    ,datname
    ,usename
    ,application_name
    ,client_hostname
    ,client_port
    ,backend_start
    ,query_start
    ,query
    ,state
FROM pg_stat_activity
WHERE state = 'active';

You may use 'idle' instead of active to get already executed connections/queries.

Parsing JSON objects for HTML table

This post is very much helpful to all of you

First Parse the json data by using jquery eval parser and then iterarate through jquery each function below is the code sniplet:

                var obj = eval("(" + data.d + ")");

                alert(obj);
                $.each(obj, function (index,Object) {

                    var Id = Object.Id;
                    var AptYear = Object.AptYear;
                    $("#ddlyear").append('<option value=' + Id + '>' + AptYear + '</option>').toString();
                });

SQL Server: Make all UPPER case to Proper Case/Title Case

On Server Server 2016 and newer, you can use STRING_SPLIT


with t as (
    select 'GOOFYEAR Tire and Rubber Company' as n
    union all
    select 'THE HAPPY BEAR' as n
    union all
    select 'MONK HOUSE SALES' as n
    union all
    select 'FORUM COMMUNICATIONS' as n
)
select
    n,
    (
        select ' ' + (
            upper(left(value, 1))
            + lower(substring(value, 2, 999))
        )
        from (
            select value
            from string_split(t.n, ' ')
        ) as sq
        for xml path ('')
    ) as title_cased
from t

Example

How can I generate an HTML report for Junit results?

Junit xml format is used outside of Java/Maven/Ant word. Jenkins with http://wiki.jenkins-ci.org/display/JENKINS/xUnit+Plugin is a solution.

For the one shot solution I have found this tool that does the job: https://www.npmjs.com/package/junit-viewer

junit-viewer --results=surefire-reports --save=file_location.html

--results= is directory with xml files (test reports)

Postgres and Indexes on Foreign Keys and Primary Keys

For a PRIMARY KEY, an index will be created with the following message:

NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "index" for table "table" 

For a FOREIGN KEY, the constraint will not be created if there is no index on the referenced table.

An index on referencing table is not required (though desired), and therefore will not be implicitly created.

non static method cannot be referenced from a static context

You are calling nextInt statically by using Random.nextInt.

Instead, create a variable, Random r = new Random(); and then call r.nextInt(10).

It would be definitely worth while to check out:

Update:

You really should replace this line,

Random Random = new Random(); 

with something like this,

Random r = new Random();

If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.

Error: Can't set headers after they are sent to the client

I simply add the return key word like: return res.redirect("/great"); and walla!

CMake not able to find OpenSSL library

If you're using Ubuntu, run sudo apt install libssl-dev.

Open youtube video in Fancybox jquery

THIS IS BROKEN, SEE EDIT

<script type="text/javascript">
$("a.more").fancybox({
                    'titleShow'     : false,
                    'transitionIn'  : 'elastic',
                    'transitionOut' : 'elastic',
            'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'      : 'swf',
            'swf'       : {'wmode':'transparent','allowfullscreen':'true'}
        });
</script>

This way if the user javascript is enabled it opens a fancybox with the youtube embed video, if javascript is disabled it opens the video's youtube page. If you want you can add

target="_blank"

to each of your links, it won't validate on most doctypes, but it will open the link in a new window if fancybox doesn't pick it up.

EDIT

this, above, isn't referenced correctly, so the code won't find href under this. You have to call it like this:

$("a.more").click(function() {
    $.fancybox({
            'padding'       : 0,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'title'         : this.title,
            'width'     : 680,
            'height'        : 495,
            'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'          : 'swf',
            'swf'           : {
                 'wmode'        : 'transparent',
                'allowfullscreen'   : 'true'
            }
        });

    return false;
});

as covered at http://fancybox.net/blog #4, replicated above

Find empty or NaN entry in Pandas Dataframe

To obtain all the rows that contains an empty cell in in a particular column.

DF_new_row=DF_raw.loc[DF_raw['columnname']=='']

This will give the subset of DF_raw, which satisfy the checking condition.

How to open a web page from my application?

I've been using this line to launch the default browser:

System.Diagnostics.Process.Start("http://www.google.com"); 

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

This ERROR can happen when you use Mockito to mock final classes.

Consider using Mockito inline or Powermock instead.

Combine or merge JSON on node.js without jQuery

A normal loop?

function extend(target) {
    var sources = [].slice.call(arguments, 1);
    sources.forEach(function (source) {
        for (var prop in source) {
            target[prop] = source[prop];
        }
    });
    return target;
}

var object3 = extend({}, object1, object2);

That's a basic starting point. You may want to add things like a hasOwnProperty check, or add some logic to handle the case where multiple source objects have a property with the same identifier.

Here's a working example.

Side note: what you are referring to as "JSON" are actually normal JavaScript objects. JSON is simply a text format that shares some syntax with JavaScript.

validate natural input number with ngpattern

This is working

<form name="myform" ng-submit="create()">
    <input type="number"
           name="price_field"
           ng-model="price"
           require
           ng-pattern="/^\d{0,9}(\.\d{1,9})?$/">
    <span  ng-show="myform.price_field.$error.pattern">Not valid number!</span>
    <input type="submit" class="btn">
 </form>

CASE in WHERE, SQL Server

A few ways:

-- Do the comparison, OR'd with a check on the @Country=0 case
WHERE (a.Country = @Country OR @Country = 0)

-- compare the Country field to itself
WHERE a.Country = CASE WHEN @Country > 0 THEN @Country ELSE a.Country END

Or, use a dynamically generated statement and only add in the Country condition if appropriate. This should be most efficient in the sense that you only execute a query with the conditions that actually need to apply and can result in a better execution plan if supporting indices are in place. You would need to use parameterised SQL to prevent against SQL injection.

How to make a pure css based dropdown menu?

Tested in IE7 - 9 and Firefox: http://jsfiddle.net/WCaKg/. Markup:

<ul>
    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;

        <ul>
            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>

            <li>&lt;li&gt;</li>
        </ul>
    </li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>

    <li>&lt;li&gt;</li>
</ul>

CSS:

* {
  margin: 0;
  padding: 0;
}

body {
  font: 200%/1.5 Optima, 'Lucida Grande', Lucida, 'Lucida Sans Unicode', sans-serif;
}

ul {
  width: 9em;
  list-style-type: none;
  font-size: 0.75em;
}

li {
  float: left;
  margin: 0 4px 4px 0;
  background: #60c;
  background: rgba(102, 0, 204, 0.66);
  border: 4px solid #60c;
  color: #fff;
}
li:hover {
  position: relative;
}

ul ul {
  z-index: 1;
  position: absolute;
  left: -999em;
  width: auto;
  background: #ccc;
  background: rgba(204, 204, 204, 0.33);
}

li:hover ul {
  top: 2em;
  left: 3px;
}

li li {
  margin: 0 0 3px 0;
  background: #909;
  background: rgba(153, 0, 153, 0.66);
  border: 3px solid #909;
}

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

This could be a issue in mvn home path in IntellijIdea IDE. For me it worked out when I set the mvn home directory correctly.enter image description here

How do I compare two DateTime objects in PHP 5.2.8?

From the official documentation:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2); // false
var_dump($date1 < $date2); // true
var_dump($date1 > $date2); // false

For PHP versions before 5.2.2 (actually for any version), you can use diff.

$datetime1 = new DateTime('2009-10-11'); // 11 October 2013
$datetime2 = new DateTime('2009-10-13'); // 13 October 2013

$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); // +2 days

How to encode text to base64 in python

For py3, base64 encode and decode string:

import base64

def b64e(s):
    return base64.b64encode(s.encode()).decode()


def b64d(s):
    return base64.b64decode(s).decode()

Possible to make labels appear when hovering over a point in matplotlib?

A slight edit on an example provided in http://matplotlib.org/users/shell.html:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')

line, = ax.plot(np.random.rand(100), '-', picker=5)  # 5 points tolerance


def onpick(event):
    thisline = event.artist
    xdata = thisline.get_xdata()
    ydata = thisline.get_ydata()
    ind = event.ind
    print('onpick points:', *zip(xdata[ind], ydata[ind]))


fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

This plots a straight line plot, as Sohaib was asking

Put quotes around a variable string in JavaScript

var text = "\"http://example.com\""; 

Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:

"http://example.com"

m2eclipse error

I had same problem with Eclipse 3.7.2 (Indigo) and maven 3.0.4.

In my case, the problem was caused by missing maven-resources-plugin-2.4.3.jar in {user.home}\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3 folder. (no idea why maven didn't update it)

Solution:

1.) add dependency to pom.xml

<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.4.3</version>
</dependency>

2.) run mvn install from Eclipse or from command line

3.) refresh the project in eclipse (F5)

4.) run Maven > Update Project Configuration... on project (right click)

JAR file is downloaded to local repository and there are no errors in WS.

PostgreSQL IF statement

You could also use the the basic structure for the PL/pgSQL CASE with anonymous code block procedure block:

DO $$ BEGIN
    CASE
        WHEN boolean-expression THEN
          statements;
        WHEN boolean-expression THEN
          statements;
        ...
        ELSE
          statements;
    END CASE;
END $$;

References:

  1. http://www.postgresql.org/docs/current/static/sql-do.html
  2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

I tried to rebuilt, restart, clean, update Gradle, etc. However, none of them worked for me.

Sometimes, it can be caused by a wrong naming for an XML or resource file.

At least, for me, that problem was solved by changing the name.

ORA-01882: timezone region not found

In my case I could get the query working by changing "TZR" with "TZD"..

String query = "select * from table1 to_timestamp_tz(origintime,'dd-mm-yyyy hh24:mi:ss TZD') between ?  and ?";

Difference between Iterator and Listiterator?

The differences are listed in the Javadoc for ListIterator

You can

  • iterate backwards
  • obtain the iterator at any point.
  • add a new value at any point.
  • set a new value at that point.

Array to String PHP?

No, you don't want to store it as a single string in your database like that.

You could use serialize() but this will make your data harder to search, harder to work with, and wastes space.

You could do some other encoding as well, but it's generally prone to the same problem.

The whole reason you have a DB is so you can accomplish work like this trivially. You don't need a table to store arrays, you need a table that you can represent as an array.

Example:

id | word
1  | Sports
2  | Festivals
3  | Classes
4  | Other

You would simply select the data from the table with SQL, rather than have a table that looks like:

id | word
1  | Sports|Festivals|Classes|Other

That's not how anybody designs a schema in a relational database, it totally defeats the purpose of it.

How to add a second x-axis in matplotlib

You can use twiny to create 2 x-axis scales. For Example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

a = np.cos(2*np.pi*np.linspace(0, 1, 60.))

ax1.plot(range(60), a)
ax2.plot(range(100), np.ones(100)) # Create a dummy plot
ax2.cla()
plt.show()

Ref: http://matplotlib.sourceforge.net/faq/howto_faq.html#multiple-y-axis-scales

Output: enter image description here

Difference between text and varchar (character varying)

UPDATING BENCHMARKS FOR 2016 (pg9.5+)

And using "pure SQL" benchmarks (without any external script)

  1. use any string_generator with UTF8

  2. main benchmarks:

    2.1. INSERT

    2.2. SELECT comparing and counting


CREATE FUNCTION string_generator(int DEFAULT 20,int DEFAULT 10) RETURNS text AS $f$
  SELECT array_to_string( array_agg(
    substring(md5(random()::text),1,$1)||chr( 9824 + (random()*10)::int )
  ), ' ' ) as s
  FROM generate_series(1, $2) i(x);
$f$ LANGUAGE SQL IMMUTABLE;

Prepare specific test (examples)

DROP TABLE IF EXISTS test;
-- CREATE TABLE test ( f varchar(500));
-- CREATE TABLE test ( f text); 
CREATE TABLE test ( f text  CHECK(char_length(f)<=500) );

Perform a basic test:

INSERT INTO test  
   SELECT string_generator(20+(random()*(i%11))::int)
   FROM generate_series(1, 99000) t(i);

And other tests,

CREATE INDEX q on test (f);

SELECT count(*) FROM (
  SELECT substring(f,1,1) || f FROM test WHERE f<'a0' ORDER BY 1 LIMIT 80000
) t;

... And use EXPLAIN ANALYZE.

UPDATED AGAIN 2018 (pg10)

little edit to add 2018's results and reinforce recommendations.


Results in 2016 and 2018

My results, after average, in many machines and many tests: all the same
(statistically less tham standard deviation).

Recommendation

  • Use text datatype,
    avoid old varchar(x) because sometimes it is not a standard, e.g. in CREATE FUNCTION clauses varchar(x)?varchar(y).

  • express limits (with same varchar performance!) by with CHECK clause in the CREATE TABLE
    e.g. CHECK(char_length(x)<=10).
    With a negligible loss of performance in INSERT/UPDATE you can also to control ranges and string structure
    e.g. CHECK(char_length(x)>5 AND char_length(x)<=20 AND x LIKE 'Hello%')

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

Had exactly the same problem; I'd brew added [email protected] (after previously having 5.5).

The brew defaults for 5.6 are innodb_file_per_table=1 whereas in 5.5 they're innodb_file_per_table=0.

Your existing ibdata1 file (the combined innodb data) will still have references to the tables you're trying to create/drop. Either change innodb_file_per_table back to 0, or delete the ibdata1 data file (this will lose you all your data, so make sure you mysqldump it first or already have an .sql dump).

The other brew [email protected] default that bit me was the lack of a port, so networking was defaulting to unix sockets, and the mysql client kept reporting:

ERROR 2013 (HY000): Lost connection to MySQL server at 'sending authentication information', system error: 32

I added <string>--port=3306</string> to the .plist array, but you could also specify port=3306 in your my.cnf

Run brew services stop [email protected] make your changes then brew services start [email protected]

"Sources directory is already netbeans project" error when opening a project from existing sources

I checked the "Put NetBeans metadata in separate directory" tick and it works fine.

This is in 2. Name and Location after you choose PHP from existing source

Difference between matches() and find() in Java Regex

matches(); does not buffer, but find() buffers. find() searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.

That is why when you have a code like

1:Pattern.compile("[a-z]");

2:Pattern.matcher("0a1b1c3d4");

3:int count = 0;

4:while(matcher.find()){

5:count++: }

At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character] to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches(); does not. The while statement would never execute since the first character of the matched string is not an alphabet.

How do I convert a number to a numeric, comma-separated formatted string?

For SQL Server 2012, or later, an easier solution is to use FORMAT ()Documentation.
EG:

SELECT Format(1234567.8, '##,##0') 

Results in: 1,234,568

maven compilation failure

I had the same problem...

How to fix - add the following properties in to the pom.xml

<properties>
    <!--  compiler settings -->
    <maven.compiler.source>1.6</maven.compiler.source>
    <maven.compiler.target>1.6</maven.compiler.target>
</properties>        

How to pass a type as a method parameter in Java

I had a similar question, so I worked up a complete runnable answer below. What I needed to do is pass a class (C) to an object (O) of an unrelated class and have that object (O) emit new objects of class (C) back to me when I asked for them.

The example below shows how this is done. There is a MagicGun class that you load with any subtype of the Projectile class (Pebble, Bullet or NuclearMissle). The interesting is you load it with subtypes of Projectile, but not actual objects of that type. The MagicGun creates the actual object when it's time to shoot.

The Output

You've annoyed the target!
You've holed the target!
You've obliterated the target!
click
click

The Code

import java.util.ArrayList;
import java.util.List;

public class PassAClass {
    public static void main(String[] args) {
        MagicGun gun = new MagicGun();
        gun.loadWith(Pebble.class);
        gun.loadWith(Bullet.class);
        gun.loadWith(NuclearMissle.class);
        //gun.loadWith(Object.class);   // Won't compile -- Object is not a Projectile
        for(int i=0; i<5; i++){
            try {
                String effect = gun.shoot().effectOnTarget();
                System.out.printf("You've %s the target!\n", effect);
            } catch (GunIsEmptyException e) {
                System.err.printf("click\n");
            }
        }
    }
}

class MagicGun {
    /**
     * projectiles holds a list of classes that extend Projectile. Because of erasure, it
     * can't hold be a List<? extends Projectile> so we need the SuppressWarning. However
     * the only way to add to it is the "loadWith" method which makes it typesafe. 
     */
    private @SuppressWarnings("rawtypes") List<Class> projectiles = new ArrayList<Class>();
    /**
     * Load the MagicGun with a new Projectile class.
     * @param projectileClass The class of the Projectile to create when it's time to shoot.
     */
    public void loadWith(Class<? extends Projectile> projectileClass){
        projectiles.add(projectileClass);
    }
    /**
     * Shoot the MagicGun with the next Projectile. Projectiles are shot First In First Out.
     * @return A newly created Projectile object.
     * @throws GunIsEmptyException
     */
    public Projectile shoot() throws GunIsEmptyException{
        if (projectiles.isEmpty())
            throw new GunIsEmptyException();
        Projectile projectile = null;
        // We know it must be a Projectile, so the SuppressWarnings is OK
        @SuppressWarnings("unchecked") Class<? extends Projectile> projectileClass = projectiles.get(0);
        projectiles.remove(0);
        try{
            // http://www.java2s.com/Code/Java/Language-Basics/ObjectReflectioncreatenewinstance.htm
            projectile = projectileClass.newInstance();
        } catch (InstantiationException e) {
            System.err.println(e);
        } catch (IllegalAccessException e) {
            System.err.println(e);
        }
        return projectile;
    }
}

abstract class Projectile {
    public abstract String effectOnTarget();
}

class Pebble extends Projectile {
    @Override public String effectOnTarget() {
        return "annoyed";
    }
}

class Bullet extends Projectile {
    @Override public String effectOnTarget() {
        return "holed";
    }
}

class NuclearMissle extends Projectile {
    @Override public String effectOnTarget() {
        return "obliterated";
    }
}

class GunIsEmptyException extends Exception {
    private static final long serialVersionUID = 4574971294051632635L;
}

how to output every line in a file python

Did you try

for line in open("masters", "r").readlines(): print line

?

readline() 

only reads "a line", on the other hand

readlines()

reads whole lines and gives you a list of all lines.

What's the @ in front of a string in C#?

It marks the string as a verbatim string literal - anything in the string that would normally be interpreted as an escape sequence is ignored.

So "C:\\Users\\Rich" is the same as @"C:\Users\Rich"

There is one exception: an escape sequence is needed for the double quote. To escape a double quote, you need to put two double quotes in a row. For instance, @"""" evaluates to ".

Calculating Page Load Time In JavaScript

Don't ever use the setInterval or setTimeout functions for time measuring! They are unreliable, and it is very likely that the JS execution scheduling during a documents parsing and displaying is delayed.

Instead, use the Date object to create a timestamp when you page began loading, and calculate the difference to the time when the page has been fully loaded:

<doctype html>
<html>
    <head>
        <script type="text/javascript">
            var timerStart = Date.now();
        </script>
        <!-- do all the stuff you need to do -->
    </head>
    <body>
        <!-- put everything you need in here -->

        <script type="text/javascript">
             $(document).ready(function() {
                 console.log("Time until DOMready: ", Date.now()-timerStart);
             });
             $(window).load(function() {
                 console.log("Time until everything loaded: ", Date.now()-timerStart);
             });
        </script>
    </body>
</html>

CSS smooth bounce animation

In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:

.ball {
  animation: bounce 1s infinite alternate;
  -webkit-animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from {
    margin-top: 0;
  }
  to {
    margin-top: -15px;
  }
}

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

Can you explain the HttpURLConnection connection process?

I went through the exercise to capture low level packet exchange, and found that network connection is only triggered by operations like getInputStream, getOutputStream, getResponseCode, getResponseMessage etc.

Here is the packet exchange captured when I try to write a small program to upload file to Dropbox.

enter image description here

Below is my toy program and annotation

    /* Create a connection LOCAL object,
     * the openConnection() function DOES NOT initiate
     * any packet exchange with the remote server.
     * 
     * The configurations only setup the LOCAL
     * connection object properties.
     */
    HttpURLConnection connection = (HttpURLConnection) dst.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    ...//headers setup
    byte[] testContent = {0x32, 0x32};

    /**
     * This triggers packet exchange with the remote
     * server to create a link. But writing/flushing
     * to a output stream does not send out any data.
     * 
     * Payload are buffered locally.
     */
    try (BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream())) {
        outputStream.write(testContent);
        outputStream.flush();
    }

    /**
     * Trigger payload sending to the server.
     * Client get ALL responses (including response code,
     * message, and content payload) 
     */
    int responseCode = connection.getResponseCode();
    System.out.println(responseCode);

    /* Here no further exchange happens with remote server, since
     * the input stream content has already been buffered
     * in previous step
     */
    try (InputStream is = connection.getInputStream()) {
        Scanner scanner = new Scanner(is);
        StringBuilder stringBuilder = new StringBuilder();
        while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine()).append(System.lineSeparator());
        }
    }

    /**
     * Trigger the disconnection from the server.
     */
    String responsemsg = connection.getResponseMessage();
    System.out.println(responsemsg);
    connection.disconnect();

Deleting objects from an ArrayList in Java

Obviously, of the two methods you mention number 1 is more efficient, since it only needs to go through the list once, while with method number 2 the list has to be traversed two times (first to find the elements to remove, and them to remove them).

Actually, removing a list of elements from another list is likely an algorithm that's worse than O(n) so method 2 is even worse.

The iterator method:

List data = ...;

for (Iterator i = data.iterator(); i.hasNext(); ) {
    Object element = i.next();

    if (!(...)) {
        i.remove();
    }
}

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

How can I listen for keypress event on the whole page?

I would use @HostListener decorator within your component:

import { HostListener } from '@angular/core';

@Component({
  ...
})
export class AppComponent {

  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
    this.key = event.key;
  }
}

There are also other options like:

host property within @Component decorator

Angular recommends using @HostListener decorator over host property https://angular.io/guide/styleguide#style-06-03

@Component({
  ...
  host: {
    '(document:keypress)': 'handleKeyboardEvent($event)'
  }
})
export class AppComponent {
  handleKeyboardEvent(event: KeyboardEvent) {
    console.log(event);
  }
}

renderer.listen

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

@Component({
  ...
})
export class AppComponent {
  globalListenFunc: Function;

  constructor(private renderer: Renderer2) {}

  ngOnInit() {
    this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
      console.log(e);
    });
  }

  ngOnDestroy() {
    // remove listener
    this.globalListenFunc();
  }
}

Observable.fromEvent

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';

@Component({
  ...
})
export class AppComponent {
  subscription: Subscription;

  ngOnInit() {
    this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
      console.log(e);
    })
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

How to send and retrieve parameters using $state.go toParams and $stateParams?

If you want to pass non-URL state, then you must not use url when setting up your state. I found the answer on a PR and did some monkeying around to better understand.

$stateProvider.state('toState', {
  templateUrl:'wokka.html',
  controller:'stateController',
  params: {
    'referer': 'some default', 
    'param2': 'some default', 
    'etc': 'some default'
  }
});

Then you can navigate to it like so:

$state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' });

Or:

var result = { referer:'jimbob', param2:37, etc:'bluebell' };
$state.go('toState', result);

And in HTML thusly:

<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>

This use case is completely uncovered in the documentation, but I think it's a powerful means on transitioning state without using URLs.

Found conflicts between different versions of the same dependent assembly that could not be resolved

I found that, sometimes, nuget packages will install (what I'm guessing are) .NET Core required components or other items that conflict with the already-installed framework. My solution there was to open the project (.csproj) file and remove those references. For example, System.IO, System.Threading and such, tend to be added when Microsoft.Bcl is included via some recently installed NuGet package. There's no reason for specific versions of those in my projects, so I remove the references and the project builds. Hope that helps.

You can search your project file for "reference" and remove the conflicts. If they're included in System, get rid of them, and the build should work. This may not answer all cases of this issue - I'm making sure you know what worked for me :)

Example of what I commented out:

_x000D_
_x000D_
<!-- <Reference Include="System.Runtime, Version=2.6.9.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> -->_x000D_
  <!-- <HintPath>$(SolutionDir)packages\Microsoft.Bcl.1.1.9\lib\net40\System.Runtime.dll</HintPath> -->_x000D_
  <!-- <Private>True</Private> -->_x000D_
<!-- </Reference> -->
_x000D_
_x000D_
_x000D_

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

How do I declare an array variable in VBA?

Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.

sub Demo_array()
    Dim MyArray as Variant, MyArray2 as Variant, i as Long

    MyArray = Array(1, 10, 20, 50)  'The key - the powerful Array() statement
    MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too

    For i = 0 to UBound(MyArray)
        Debug.Print i, MyArray(i)
    Next i
    For i = 0 to UBound(MyArray2)
        Debug.Print i, MyArray2(i)
    Next i
End Sub

I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type

, "Egg"

in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.

If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.

Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.

How to do a SQL NOT NULL with a DateTime?

SELECT * FROM Table where codtable not in (Select codtable from Table where fecha is null)

codeigniter model error: Undefined property

It solved throung second parameter in Model load:

$this->load->model('user','User');

first parameter is the model's filename, and second it defining the name of model to be used in the controller:

function alluser() 
{
$this->load->model('User');
$result = $this->User->showusers();
}

What is the difference between json.load() and json.loads() functions

Just going to add a simple example to what everyone has explained,

json.load()

json.load can deserialize a file itself i.e. it accepts a file object, for example,

# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
  print(json.load(content))

will output,

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

If I use json.loads to open a file instead,

# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
  print(json.loads(content))

I would get this error:

TypeError: expected string or buffer

json.loads()

json.loads() deserialize string.

So in order to use json.loads I will have to pass the content of the file using read() function, for example,

using content.read() with json.loads() return content of the file,

with open("json_data.json", "r") as content:
  print(json.loads(content.read()))

Output,

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

That's because type of content.read() is string, i.e. <type 'str'>

If I use json.load() with content.read(), I will get error,

with open("json_data.json", "r") as content:
  print(json.load(content.read()))

Gives,

AttributeError: 'str' object has no attribute 'read'

So, now you know json.load deserialze file and json.loads deserialize a string.

Another example,

sys.stdin return file object, so if i do print(json.load(sys.stdin)), I will get actual json data,

cat json_data.json | ./test.py

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

If I want to use json.loads(), I would do print(json.loads(sys.stdin.read())) instead.

require is not defined? Node.js

In the terminal, you are running the node application and it is running your script. That is a very different execution environment than directly running your script in the browser. While the Javascript language is largely the same (both V8 if you're running the Chrome browser), the rest of the execution environment such as libraries available are not the same.

node.js is a server-side Javascript execution environment that combines the V8 Javascript engine with a bunch of server-side libraries. require() is one such feature that node.js adds to the environment. So, when you run node in the terminal, you are running an environment that contains require().

require() is not a feature that is built into the browser. That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require().

There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require() that work similarly (though not identically).

But, you won't be running a web server in your browser as that is not something the browser has the capability to do.


You may be interested in browserify which lets you use node-style modules in a browser using require() statements.

A simple algorithm for polygon intersection

You have not given us your representation of a polygon. So I am choosing (more like suggesting) one for you :)

Represent each polygon as one big convex polygon, and a list of smaller convex polygons which need to be 'subtracted' from that big convex polygon.

Now given two polygons in that representation, you can compute the intersection as:

Compute intersection of the big convex polygons to form the big polygon of the intersection. Then 'subtract' the intersections of all the smaller ones of both to get a list of subracted polygons.

You get a new polygon following the same representation.

Since convex polygon intersection is easy, this intersection finding should be easy too.

This seems like it should work, but I haven't given it more deeper thought as regards to correctness/time/space complexity.

Adding Multiple Values in ArrayList at a single index

Use two dimensional array instead. For instance, int values[][] = new int[2][5]; Arrays are faster, when you are not manipulating much.

Check if a temporary table exists and delete if it exists before creating a temporary table

This worked for me,

IF OBJECT_ID('tempdb.dbo.#tempTable') IS NOT NULL 
DROP TABLE #tempTable; 

Here tempdb.dbo(dbo is nothing but your schema) is having more importance.

Can CSS force a line break after each word in an element?

You can't target each word in CSS. However, with a bit of jQuery you probably could.

With jQuery you can wrap each word in a <span> and then CSS set span to display:block which would put it on its own line.

In theory of course :P

How to drop a table if it exists?

Simple is that:

IF OBJECT_ID(dbo.TableName, 'U') IS NOT NULL
DROP TABLE dbo.TableName

where dbo.TableName is your desired table and 'U' is type of your table.

How to get xdebug var_dump to show full object/array

Or you can use an alternative:

https://github.com/kint-php/kint

It works with zero set up and has much more features than Xdebug's var_dump anyway. To bypass the nested limit on the fly with Kint, just use

 +d( $variable ); // append `+` to the dump call

Declaring & Setting Variables in a Select Statement

Coming from SQL Server as well, and this really bugged me. For those using Toad Data Point or Toad for Oracle, it's extremely simple. Just putting a colon in front of your variable name will prompt Toad to open a dialog where you enter the value on execute.

SELECT * FROM some_table WHERE some_column = :var_name;

What is the difference between single-quoted and double-quoted strings in PHP?

Here some possibilities of single and double quotes with variable

$world = "world";

"Hello '.$world.' ";

'hello ".$world."';

How can I set a cookie in react?

I set cookies in React using the react-cookie library, it has options you can pass in options to set expiration time.

Check it out here

An example of its use for your case:

import cookie from "react-cookie";

setCookie() => {
  let d = new Date();
  d.setTime(d.getTime() + (minutes*60*1000));

  cookie.set("onboarded", true, {path: "/", expires: d});
};

PreparedStatement with list of parameters in a IN clause

public static ResultSet getResult(Connection connection, List values) {
    try {
        String queryString = "Select * from table_name where column_name in";

        StringBuilder parameterBuilder = new StringBuilder();
        parameterBuilder.append(" (");
        for (int i = 0; i < values.size(); i++) {
            parameterBuilder.append("?");
            if (values.size() > i + 1) {
                parameterBuilder.append(",");
            }
        }
        parameterBuilder.append(")");

        PreparedStatement statement = connection.prepareStatement(queryString + parameterBuilder);
        for (int i = 1; i < values.size() + 1; i++) {
            statement.setInt(i, (int) values.get(i - 1));
        }

        return statement.executeQuery();
    } catch (Exception d) {
        return null;
    }
}

Access Tomcat Manager App from different host

Each deployed webapp has a context.xml file that lives in

$CATALINA_BASE/conf/[enginename]/[hostname]

(conf/Catalina/localhost by default)

and has the same name as the webapp (manager.xml in this case). If no file is present, default values are used.

So, you need to create a file conf/Catalina/localhost/manager.xml and specify the rule you want to allow remote access. For example, the following content of manager.xml will allow access from all machines:

<Context privileged="true" antiResourceLocking="false" 
         docBase="${catalina.home}/webapps/manager">
    <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>

Note that the allow attribute of the Valve element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).

Other Valve classes cater for other rules (e.g. RemoteHostValve for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.

Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml you should have access to the Manager.

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

I liked Jed's solution but the issue with that was every time I built my project in debug mode, it would deploy my database project and removed the user again. so I added this MySQL script to the Post-Deployment script. it practically does what Jed said but creates the user every time I deploy.

CREATE USER [NT AUTHORITY\NETWORK SERVICE]
    FOR LOGIN [NT AUTHORITY\NETWORK SERVICE]
    WITH DEFAULT_SCHEMA = dbo;
Go

EXEC sp_addrolemember 'db_owner', 'NT AUTHORITY\NETWORK SERVICE'

Automatically create requirements.txt

I created this bash command.

for l in $(pip freeze); do p=$(echo "$l" | cut -d'=' -f1); f=$(find . -type f -exec grep "$p" {} \; | grep 'import'); [[ ! -z "$f" ]] && echo "$l" ; done;

how to parse json using groovy

Have you tried using JsonSlurper?

Example usage:

def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

I assume the question is already answered. If above solution doesn't help in solving the issue then can use below to solve the issue.

The issue occurs if sometimes your maven user settings is not reflecting correct settings.xml file.

To update the settings file go to Windows > Preferences > Maven > User Settings and update the settings.xml to it correct location.

Once this is doen re-build the project, these should solve the issue. Thanks.

How to start rails server?

In rails 2.3.x application you can start your server by following command:

ruby script/server

In rails 3.x, you need to go for:

rails s

IIS Express Windows Authentication

Building upon the answer from booij boy, check if you checked the "windows authentication" feature in Control Panel -> Programs -> Turn windows features on or of -> Internet Information Services -> World Wide Web Services -> Security

Also, there seems to be a big difference when using firefox or internet explorer. After enabeling the "windows authentication" it works for me but only in IE.

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Bootstrap Responsive Text Size

Simplest way is to use dimensions in % or em. Just change the base font size everything will change.

Less

@media (max-width: @screen-xs) {
    body{font-size: 10px;}
}

@media (max-width: @screen-sm) {
    body{font-size: 14px;}
}


h5{
    font-size: 1.4rem;
}       

Look at all the ways at https://stackoverflow.com/a/21981859/406659

You could use viewport units (vh,vw...) but they dont work on Android < 4.4

How to convert UTF-8 byte[] to string?

Using (byte)b.ToString("x2"), Outputs b4b5dfe475e58b67

public static class Ext {

    public static string ToHexString(this byte[] hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return string.Empty;

        var s = new StringBuilder();
        foreach (byte b in hex) {
            s.Append(b.ToString("x2"));
        }
        return s.ToString();
    }

    public static byte[] ToHexBytes(this string hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return new byte[0];

        int l = hex.Length / 2;
        var b = new byte[l];
        for (int i = 0; i < l; ++i) {
            b[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
        }
        return b;
    }

    public static bool EqualsTo(this byte[] bytes, byte[] bytesToCompare)
    {
        if (bytes == null && bytesToCompare == null) return true; // ?
        if (bytes == null || bytesToCompare == null) return false;
        if (object.ReferenceEquals(bytes, bytesToCompare)) return true;

        if (bytes.Length != bytesToCompare.Length) return false;

        for (int i = 0; i < bytes.Length; ++i) {
            if (bytes[i] != bytesToCompare[i]) return false;
        }
        return true;
    }

}

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

Just for the record if somebody needs a way to handle signals on Windows. I had a requirement to handle from prog A calling prog B through os/exec but prog B never was able to terminate gracefully because sending signals through ex. cmd.Process.Signal(syscall.SIGTERM) or other signals are not supported on Windows. The way I handled is by creating a temp file as a signal ex. .signal.term through prog A and prog B needs to check if that file exists on interval base, if file exists it will exit the program and handle a cleanup if needed, I'm sure there are other ways but this did the job.

Media Player called in state 0, error (-38,0)

You get this message in the logs, because you do something that is not allowed in the current state of your MediaPlayer instance.

Therefore you should always register an error handler to catch those things (as @tidbeck suggested).

At first, I advice you to take a look at the documentation for the MediaPlayer class and get an understanding of what that with states means. See: http://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram

Your mistake here could well be one of the common ones, the others wrote here, but in general, I would take a look at the documentation of what methods are valid to call in what state: http://developer.android.com/reference/android/media/MediaPlayer.html#Valid_and_Invalid_States

In my example it was the method mediaPlayer.CurrentPosition, that I called while the media player was in a state, where it was not allowed to call this property.

ORA-01031: insufficient privileges when selecting view

If the view is accessed via a stored procedure, the execute grant is insufficient to access the view. You must grant select explicitly.

How to loop through all enum values in C#?

static void Main(string[] args)
{
    foreach (int value in Enum.GetValues(typeof(DaysOfWeek)))
    {
        Console.WriteLine(((DaysOfWeek)value).ToString());
    }

    foreach (string value in Enum.GetNames(typeof(DaysOfWeek)))
    {
        Console.WriteLine(value);
    }
    Console.ReadLine();
}

public enum DaysOfWeek
{
    monday,
    tuesday,
    wednesday
}

Change table header color using bootstrap

You could simply apply one of the bootstrap contextual background colors to the header row. In this case (blue background, white text): primary.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<table class="table" >_x000D_
  <tr class="bg-primary">_x000D_
    <th>_x000D_
        Firstname_x000D_
    </th>_x000D_
    <th>_x000D_
        Surname_x000D_
    </th>_x000D_
    <th></th>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>John</td>_x000D_
    <td>Doe</td>_x000D_
  </tr>_x000D_
    <tr>_x000D_
      <td>Jane</td>_x000D_
      <td>Roe</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Why use HttpClient for Synchronous Connection

but what i am doing is purely synchronous

You could use HttpClient for synchronous requests just fine:

using (var client = new HttpClient())
{
    var response = client.GetAsync("http://google.com").Result;

    if (response.IsSuccessStatusCode)
    {
        var responseContent = response.Content; 

        // by calling .Result you are synchronously reading the result
        string responseString = responseContent.ReadAsStringAsync().Result;

        Console.WriteLine(responseString);
    }
}

As far as why you should use HttpClient over WebRequest is concerned, well, HttpClient is the new kid on the block and could contain improvements over the old client.

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

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

That is, cmd is not a command:

$cmd 2>filename
cat filename

command not found

The error is sent to the file like this:

2>&1

Standard error is sent to the terminal.

'git status' shows changed files, but 'git diff' doesn't

I stumbled upon this problem again. But this time it occurred for a different reason. I had copied files into the repo to overwrite the previous versions. Now I can see the files are modified but diff doesn't return the diffs.

For example, I have a mainpage.xaml file. In File Explorer I pasted a new mainpage.xaml file over the one in my current repo. I did the work on another machine and just pasted the file here.
git shows modified

The file shows modified, but when I run git diff, it will not show the changes. It's probably because the fileinfo on the file has changed and git knows that it isn't really the same file. Interesting.

git diff shows nothing

You can see that when I run diff on the file it shows nothing, just returns the prompt.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I'm a MacOS user.

I solved it by uninstalling Android Studio and reinstalling it again.

If you want to try this link helped me a lot.

Uninstall Android Studio MacOS (terminal)

Pass parameter to controller from @Html.ActionLink MVC 4

I have to pass two parameters like:

/Controller/Action/Param1Value/Param2Value

This way:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= Param1Value, 
        Param2Name = Param2Value 
    },
    htmlAttributes: null
)

will generate this url

/Controller/Action/Param1Value?Param2Name=Param2Value

I used a workaround method by merging parameter two in parameter one and I get what I wanted:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= "Param1Value / Param2Value" ,      
    },
    htmlAttributes: null
)

And I get :

/Controller/Action/Param1Value/Param2Value

string in namespace std does not name a type

You need to

#include <string>

<iostream> declares cout, cin, not string.

How to parse JSON response from Alamofire API in Swift?

in swift 5 we do like, Use typealias for the completion. Typlealias nothing just use to clean the code.

typealias response = (Bool,Any?)->()


static func postCall(_ url : String, param : [String : Any],completion : @escaping response){
    Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in

        switch response.result {
           case .success(let JSON):
               print("\n\n Success value and JSON: \(JSON)")

           case .failure(let error):
               print("\n\n Request failed with error: \(error)")

           }
    }
}

case in sql stored procedure on SQL Server

CASE isn't used for flow control... for this, you would need to use IF...

But, there's a set-based solution to this problem instead of the procedural approach:

UPDATE tblEmployee
SET 
  InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
  OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
  Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID

Note that the ELSE will preserves the original value if the @NewStatus condition isn't met.

Which exception should I raise on bad/illegal argument combinations in Python?

I'm not sure I agree with inheritance from ValueError -- my interpretation of the documentation is that ValueError is only supposed to be raised by builtins... inheriting from it or raising it yourself seems incorrect.

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

-- ValueError documentation

Run PHP function on html button click

<?php
if (isset($_POST['str'])){
function printme($str){
echo $str;
}

printme("{$_POST['str']}");
}
?>
<form action="<?php $_PHP_SELF ?>" method="POST">
<input type="text" name="str" /> <input type="submit" value="Submit"/>
</form>

How to convert a UTF-8 string into Unicode?

What you have seems to be a string incorrectly decoded from another encoding, likely code page 1252, which is US Windows default. Here's how to reverse, assuming no other loss. One loss not immediately apparent is the non-breaking space (U+00A0) at the end of your string that is not displayed. Of course it would be better to read the data source correctly in the first place, but perhaps the data source was stored incorrectly to begin with.

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string junk = "déjÃ\xa0";  // Bad Unicode string

        // Turn string back to bytes using the original, incorrect encoding.
        byte[] bytes = Encoding.GetEncoding(1252).GetBytes(junk);

        // Use the correct encoding this time to convert back to a string.
        string good = Encoding.UTF8.GetString(bytes);
        Console.WriteLine(good);
    }
}

Result:

déjà

Extract / Identify Tables from PDF python

You should definitely have a look at this answer of mine:

and also have a look at all the links included therein.

Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Coming from someone who has tried a number of "C# IDEs" on the Mac, your best bet is to install a virtual desktop with Windows and Visual Studio. It really is the best development IDE out there for .NET, nothing even comes close.

On a related note: I hate XCode.


Update: Use Xamarin Studio. It's solid.

PHP function overloading

It may be hackish to some, but I learned this way from how Cakephp does some functions and have adapted it because I like the flexibility it creates

The idea is you have different type of arguments, arrays, objects etc, then you detect what you were passed and go from there

function($arg1, $lastname) {
    if(is_array($arg1)){
        $lastname = $arg1['lastname'];
        $firstname = $arg1['firstname'];
    } else {
        $firstname = $arg1;
    }
    ...
}

Typescript export vs. default export

I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default declaration for a class, and instead append the export tag to the class declaration. The imported class should be instead listed in the import command of the module.

That is: instead of

class Foo {
    // ...
}
export default Foo;

and the simple import Foo from './foo'; in the module that will import, one should use

export class Foo {
    // ...
}

and import {Foo} from './foo' in the importer.

The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default can lead to problems

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Non-Static method cannot be referenced from a static context with methods and variables

You should place Scanner input = new Scanner (System.in); into the main method rather than creating the input object outside.

What is the best way to add options to a select from a JavaScript object with jQuery?

I decided to chime in a bit.

  1. Deal with prior selected option; some browsers mess up when we append
  2. ONLY hit DOM once with the append
  3. Deal with multiple property while adding more options
  4. Show how to use an object
  5. Show how to map using an array of objects

_x000D_
_x000D_
// objects as value/desc_x000D_
let selectValues = {_x000D_
  "1": "test 1",_x000D_
  "2": "test 2",_x000D_
  "3": "test 3",_x000D_
  "4": "test Four"_x000D_
};_x000D_
//use div here as using "select" mucks up the original selected value in "mySelect"_x000D_
let opts = $("<div />");_x000D_
let opt = {};_x000D_
$.each(selectValues, function(value, desc) {_x000D_
  opts.append($('<option />').prop("value", value).text(desc));_x000D_
});_x000D_
opts.find("option").appendTo('#mySelect');_x000D_
_x000D_
// array of objects called "options" in an object_x000D_
let selectValuesNew = {_x000D_
  options: [{_x000D_
      value: "1",_x000D_
      description: "2test 1"_x000D_
    },_x000D_
    {_x000D_
      value: "2",_x000D_
      description: "2test 2",_x000D_
      selected: true_x000D_
    },_x000D_
    {_x000D_
      value: "3",_x000D_
      description: "2test 3"_x000D_
    },_x000D_
    {_x000D_
      value: "4",_x000D_
      description: "2test Four"_x000D_
    }_x000D_
  ]_x000D_
};_x000D_
_x000D_
//use div here as using "select" mucks up the original selected value_x000D_
let opts2 = $("<div />");_x000D_
let opt2 = {}; //only append after adding all options_x000D_
$.map(selectValuesNew.options, function(val, index) {_x000D_
  opts2.append($('<option />')_x000D_
    .prop("value", val.value)_x000D_
    .prop("selected", val.selected)_x000D_
    .text(val.description));_x000D_
});_x000D_
opts2.find("option").appendTo('#mySelectNew');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="mySelect">_x000D_
  <option value="" selected="selected">empty</option>_x000D_
</select>_x000D_
_x000D_
<select id="mySelectNew" multiple="multiple">_x000D_
  <option value="" selected="selected">2empty</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

Spring Boot + JPA : Column name annotation ignored

By default Spring uses org.springframework.boot.orm.jpa.SpringNamingStrategy to generate table names. This is a very thin extension of org.hibernate.cfg.ImprovedNamingStrategy. The tableName method in that class is passed a source String value but it is unaware if it comes from a @Column.name attribute or if it has been implicitly generated from the field name.

The ImprovedNamingStrategy will convert CamelCase to SNAKE_CASE where as the EJB3NamingStrategy just uses the table name unchanged.

If you don't want to change the naming strategy you could always just specify your column name in lowercase:

@Column(name="testname")

Searching if value exists in a list of objects using Linq

List<Customer> list = ...;
Customer john = list.SingleOrDefault(customer => customer.Firstname == "John");

john will be null if no customer exists with a first name of "John".

How to crop an image in OpenCV using Python

Note that, image slicing is not creating a copy of the cropped image but creating a pointer to the roi. If you are loading so many images, cropping the relevant parts of the images with slicing, then appending into a list, this might be a huge memory waste.

Suppose you load N images each is >1MP and you need only 100x100 region from the upper left corner.

Slicing:

X = []
for i in range(N):
    im = imread('image_i')
    X.append(im[0:100,0:100]) # This will keep all N images in the memory. 
                              # Because they are still used.

Alternatively, you can copy the relevant part by .copy(), so garbage collector will remove im.

X = []
for i in range(N):
    im = imread('image_i')
    X.append(im[0:100,0:100].copy()) # This will keep only the crops in the memory. 
                                     # im's will be deleted by gc.

After finding out this, I realized one of the comments by user1270710 mentioned that but it took me quite some time to find out (i.e., debugging etc). So, I think it worths mentioning.

how to remove empty strings from list, then remove duplicate values from a list

To simplify Amiram Korach's solution:

dtList.RemoveAll(s => string.IsNullOrWhiteSpace(s))

No need to use Distinct() or ToList()

Create a remote branch on GitHub

Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.

 1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
 2. $ git branch <new_branch> (creates new branch)
 3. $ git checkout new_branch
 4. $ git add . (After making changes in the current branch)
 5. $ git commit -m "type commit msg here"
 6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
 7. $ git merge new_branch (starts merging)
 8. $ git push origin master (push to the remote server)

I referred this blog and I found it to be a cleaner approach.

What are some great online database modeling tools?

I like Clay Eclipse plugin. I've only used it with MySQL, but it claims Firebird support.

Does C have a string type?

C does not and never has had a native string type. By convention, the language uses arrays of char terminated with a null char, i.e., with '\0'. Functions and macros in the language's standard libraries provide support for the null-terminated character arrays, e.g., strlen iterates over an array of char until it encounters a '\0' character and strcpy copies from the source string until it encounters a '\0'.

The use of null-terminated strings in C reflects the fact that C was intended to be only a little more high-level than assembly language. Zero-terminated strings were already directly supported at that time in assembly language for the PDP-10 and PDP-11.

It is worth noting that this property of C strings leads to quite a few nasty buffer overrun bugs, including serious security flaws. For example, if you forget to null-terminate a character string passed as the source argument to strcpy, the function will keep copying sequential bytes from whatever happens to be in memory past the end of the source string until it happens to encounter a 0, potentially overwriting whatever valuable information follows the destination string's location in memory.

In your code example, the string literal "Hello, world!" will be compiled into a 14-byte long array of char. The first 13 bytes will hold the letters, comma, space, and exclamation mark and the final byte will hold the null-terminator character '\0', automatically added for you by the compiler. If you were to access the array's last element, you would find it equal to 0. E.g.:

const char foo[] = "Hello, world!";
assert(foo[12] == '!');
assert(foo[13] == '\0');

However, in your example, message is only 10 bytes long. strcpy is going to write all 14 bytes, including the null-terminator, into memory starting at the address of message. The first 10 bytes will be written into the memory allocated on the stack for message and the remaining four bytes will simply be written on to the end of the stack. The consequence of writing those four extra bytes onto the stack is hard to predict in this case (in this simple example, it might not hurt a thing), but in real-world code it usually leads to corrupted data or memory access violation errors.

Automatically enter SSH password with script

Use this script tossh within script, First argument is the hostname and second will be the password.

#!/usr/bin/expect
set pass [lindex $argv 1]
set host [lindex $argv 0]
spawn ssh -t root@$host echo Hello
expect "*assword: " 
send "$pass\n";
interact"

Android: How can I print a variable on eclipse console?

System.out.println and Log.d both go to LogCat, not the Console.

Define global variable with webpack

Use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

new webpack.DefinePlugin(definitions)

Example:

plugins: [
  new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true)
  })
  //...
]

Usage:

console.log(`Environment is in production: ${PRODUCTION}`);

What is the meaning of ToString("X2")?

It prints the byte in Hexadecimal format.

No format string: 13

'X2' format string: 0D

http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx

Merge two (or more) lists into one, in C# .NET

I know this is an old question I thought I might just add my 2 cents.

If you have a List<Something>[] you can join them using Aggregate

public List<TType> Concat<TType>(params List<TType>[] lists)
{
    var result = lists.Aggregate(new List<TType>(), (x, y) => x.Concat(y).ToList());

    return result;
}

Hope this helps.

How to redirect Valgrind's output to a file?

You can also set the options --log-fd if you just want to read your logs with a less. For example :

valgrind --log-fd=1 ls | less

SSL Error: unable to get local issuer certificate

jww is right — you're referencing the wrong intermediate certificate.

As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt

Finding all positions of substring in a larger string in C#

I noticed that at least two proposed solutions don't handle overlapping search hits. I didn't check the one marked with the green checkmark. Here is one that handles overlapping search hits:

    public static List<int> GetPositions(this string source, string searchString)
    {
        List<int> ret = new List<int>();
        int len = searchString.Length;
        int start = -1;
        while (true)
        {
            start = source.IndexOf(searchString, start +1);
            if (start == -1)
            {
                break;
            }
            else
            {
                ret.Add(start);
            }
        }
        return ret;
    }

How do I capture response of form.submit

First of all we will need serializeObject();

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

then you make a basic post and get response

$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) {
if(data){
//do true 
}
else
{
//do false
}

});

The FastCGI process exited unexpectedly

You might be using C:/[your-php-directory]/php.exe in Handler mapping of IIS just change it C:/[your-php-directory]/php-cgi.exe.

How do I replace all line breaks in a string with <br /> elements?

For those of you who just want to allow max. 2 <br> in a row, you can use this:

let text = text.replace(/(\r?\n){2,}/g, '<br><br>');
text = text.replace(/(\r?\n)/g, '<br>');

First line: Search for \n OR \r\n where at least 2 of them are in a row, e.g. \n\n\n\n. Then replace it with 2 br

Second line: Search for all single \r\n or \n and replace them with <br>

Incrementing in C++ - When to use x++ or ++x?

Scott Meyers tells you to prefer prefix except on those occasions where logic would dictate that postfix is appropriate.

"More Effective C++" item #6 - that's sufficient authority for me.

For those who don't own the book, here are the pertinent quotes. From page 32:

From your days as a C programmer, you may recall that the prefix form of the increment operator is sometimes called "increment and fetch", while the postfix form is often known as "fetch and increment." The two phrases are important to remember, because they all but act as formal specifications...

And on page 34:

If you're the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value and the implementation above also creates an explicit temporary object that has to be constructed and destructed. The prefix increment function has no such temporaries...

chai test array equality doesn't work as expected

Try to use deep Equal. It will compare nested arrays as well as nested Json.

expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });

Please refer to main documentation site.

How to stop line breaking in vim

I like that the long lines are displayed over more than one terminal line

This sort of visual/virtual line wrapping is enabled with the wrap window option:

set wrap

I don’t like that vim inserts newlines into my actual text.

To turn off physical line wrapping, clear both the textwidth and wrapmargin buffer options:

set textwidth=0 wrapmargin=0

How to return only the Date from a SQL Server DateTime datatype

You can use the CONVERT function to return only the date. See the link(s) below:

Date and Time Manipulation in SQL Server 2000

CAST and CONVERT

The syntax for using the convert function is:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) 

TypeError: 'dict_keys' object does not support indexing

Why you need to implement shuffle when it already exists? Stay on the shoulders of giants.

import random

d1 = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four',
     5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}

keys = list(d1)
random.shuffle(keys)

d2 = {}
for key in keys: d2[key] = d1[key]

print(d1)
print(d2)

How to implement the ReLU function in Numpy

If we have 3 parameters (t0, a0, a1) for Relu, that is we want to implement

if x > t0:
    x = x * a1
else:
    x = x * a0

We can use the following code:

X = X * (X > t0) * a1 +  X * (X < t0) * a0

X there is a matrix.

How do I print to the debug output window in a Win32 app?

If you want to print decimal variables:

wchar_t text_buffer[20] = { 0 }; //temporary buffer
swprintf(text_buffer, _countof(text_buffer), L"%d", your.variable); // convert
OutputDebugString(text_buffer); // print

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

Try this:

$(".datepicker").on("dp.change", function(e) {
    alert('hey');
});

UIDevice uniqueIdentifier deprecated - What to do now?

A UUID created by CFUUIDCreate is unique if a user uninstalls and re-installs the app: you will get a new one each time.

But you might want it to be not unique, i. e. it should stay the same when the user uninstalls and re-installs the app. This requires a bit of effort, since the most reliable per-device-identifier seems to be the MAC address. You could query the MAC and use that as UUID.

Edit: One needs to always query the MAC of the same interface, of course. I guess the best bet is with en0. The MAC is always present, even if the interface has no IP/is down.

Edit 2: As was pointed out by others, the preferred solution since iOS 6 is -[UIDevice identifierForVendor]. In most cases, you should be able use it as a drop-in replacement to the old -[UIDevice uniqueIdentifier] (but a UUID that is created when the app starts for the first time is what Apple seems to want you to use).

Edit 3: So this major point doesn't get lost in the comment noise: do not use the MAC as UUID, create a hash using the MAC. That hash will always create the same result every time, even across reinstalls and apps (if the hashing is done in the same way). Anyways, nowadays (2013) this isn't necessary any more except if you need a "stable" device identifier on iOS < 6.0.

Edit 4: In iOS 7, Apple now always returns a fixed value when querying the MAC to specifically thwart the MAC as base for an ID scheme. So you now really should use -[UIDevice identifierForVendor] or create a per-install UUID.

Example of a strong and weak entity types

First Strong/Weak Reference types are introduced in ARC. In Non ARC assign/retain are being used. A strong reference means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you points to it with a strong reference. Only once you set the property to nil, the object get destroyed.

A weak reference means you signify that you don't want to have control over the object's lifetime or don't want to "own" object. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil. The most frequent use cases of weak references in iOS are for IBOutlets, Delegates etc.

For more info Refer : http://www.informit.com/articles/article.aspx?p=1856389&seqNum=5

Calculate text width with JavaScript

The code-snips below, "calculate" the width of the span-tag, appends "..." to it if its too long and reduces the text-length, until it fits in its parent (or until it has tried more than a thousand times)

CSS

div.places {
  width : 100px;
}
div.places span {
  white-space:nowrap;
  overflow:hidden;
}

HTML

<div class="places">
  <span>This is my house</span>
</div>
<div class="places">
  <span>And my house are your house</span>
</div>
<div class="places">
  <span>This placename is most certainly too wide to fit</span>
</div>

JavaScript (with jQuery)

// loops elements classed "places" and checks if their child "span" is too long to fit
$(".places").each(function (index, item) {
    var obj = $(item).find("span");
    if (obj.length) {
        var placename = $(obj).text();
        if ($(obj).width() > $(item).width() && placename.trim().length > 0) {
            var limit = 0;
            do {
                limit++;
                                    placename = placename.substring(0, placename.length - 1);
                                    $(obj).text(placename + "...");
            } while ($(obj).width() > $(item).width() && limit < 1000)
        }
    }
});

Sort & uniq in Linux shell

I have worked on some servers where sort don't support '-u' option. there we have to use

sort xyz | uniq

How can I remove a substring from a given String?

You can use StringBuffer

StringBuffer text = new StringBuffer("Hello World");
text.replace( StartIndex ,EndIndex ,String);

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

Regex - Does not contain certain Characters

Here you go:

^[^<>]*$

This will test for string that has no < and no >

If you want to test for a string that may have < and >, but must also have something other you should use just

[^<>] (or ^.*[^<>].*$)

Where [<>] means any of < or > and [^<>] means any that is not of < or >.

And of course the mandatory link.

<code> vs <pre> vs <samp> for inline and block code snippets

This works for me to display code in frontend:

<style>
.content{
    height:50vh;
    width: 100%;
    background: transparent;
    border: none;
    border-radius: 0;
    resize: none;
    outline: none;
}
.content:focus{
    border: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
}
</style>

<textarea class="content">
<div>my div</div><p>my paragraph</p>
</textarea>

View Live Demo: https://jsfiddle.net/bytxj50e/

Simple working Example of json.net in VB.net

In Place of using this

MsgBox(json.SelectToken("Venue").SelectToken("ID"))

You can also use

MsgBox(json.SelectToken("Venue.ID"))

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

ERROR 1049 (42000): Unknown database 'mydatabasename'

You can also create a database named 'mydatabasename' and then try restoring it again.

Create a new database using MySQL CLI:

mysql -u[username] -p[password]
CREATE DATABASE mydatabasename;

Then try to restore your database:

mysql -u[username] -p[password] mydatabase<mydatabase.sql;

In Python try until no error

what about the retrying library on pypi? I have been using it for a while and it does exactly what I want and more (retry on error, retry when None, retry with timeout). Below is example from their website:

import random
from retrying import retry

@retry
def do_something_unreliable():
    if random.randint(0, 10) > 1:
        raise IOError("Broken sauce, everything is hosed!!!111one")
    else:
        return "Awesome sauce!"

print do_something_unreliable()

How to write console output to a txt file

In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.

How to create a file in memory for user to download, but not through server?

Based on @Rick answer which was really helpful.

You have to scape the string data if you want to share it this way:

$('a.download').attr('href', 'data:application/csv;charset=utf-8,'+ encodeURI(data));

` Sorry I can not comment on @Rick's answer due to my current low reputation in StackOverflow.

An edit suggestion was shared and rejected.

Remove and Replace Printed items

One way is to use ANSI escape sequences:

import sys
import time
for i in range(10):
    print("Loading" + "." * i)
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(1)

Also sometimes useful (for example if you print something shorter than before):

sys.stdout.write("\033[K") # Clear to the end of line

How to get Wikipedia content using Wikipedia's API?

You can get the introduction of the article in Wikipedia by querying pages such as https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=java. You just need to parse the json file and the result is plain text which has been cleaned including removing links and references.

Application not picking up .css file (flask/python)

If any of the above method is not working and you code is perfect then try hard refreshing by pressing Ctrl + F5. It will clear all the chaces and then reload file. It worked for me.

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\ is an escape character in Python. \t gets interpreted as a tab. If you need \ character in a string, you have to use \\.

Your code should be:
test_file=open('c:\\Python27\\test.txt','r')

What does void do in java?

The reason the code will not work without void is because the System.out.println(String string) method returns nothing and just prints the supplied arguments to the standard out terminal, which is the computer monitor in most cases. When a method returns "nothing" you have to specify that by putting the void keyword in its signature.

You can see the documentation of the System.out.println here:

http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#println%28java.lang.String%29

To press the issue further, println is a classic example of a method which is performing computation as a "side effect."

two divs the same line, one dynamic width, one fixed

HTML:

<div id="parent">
  <div class="right"></div>
  <div class="left"></div>
</div>

(div.right needs to be before div.left in the HTML markup)

CSS:

.right {
float:right;
width:200px;
}

How to write some data to excel file(.xlsx)

Try this code

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    //Get a new workbook.
    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    //Add table headers going cell by cell.
    oSheet.Cells[1, 1] = "First Name";
    oSheet.Cells[1, 2] = "Last Name";
    oSheet.Cells[1, 3] = "Full Name";
    oSheet.Cells[1, 4] = "Salary";

    //Format A1:D1 as bold, vertical alignment = center.
    oSheet.get_Range("A1", "D1").Font.Bold = true;
    oSheet.get_Range("A1", "D1").VerticalAlignment =
        Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

    // Create an array to multiple values at once.
    string[,] saNames = new string[5, 2];

    saNames[0, 0] = "John";
    saNames[0, 1] = "Smith";
    saNames[1, 0] = "Tom";

    saNames[4, 1] = "Johnson";

    //Fill A2:B6 with an array of values (First and Last Names).
    oSheet.get_Range("A2", "B6").Value2 = saNames;

    //Fill C2:C6 with a relative formula (=A2 & " " & B2).
    oRng = oSheet.get_Range("C2", "C6");
    oRng.Formula = "=A2 & \" \" & B2";

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
    oRng = oSheet.get_Range("D2", "D6");
    oRng.Formula = "=RAND()*100000";
    oRng.NumberFormat = "$0.00";

    //AutoFit columns A:D.
    oRng = oSheet.get_Range("A1", "D1");
    oRng.EntireColumn.AutoFit();

    oXL.Visible = false;
    oXL.UserControl = false;
    oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
    oXL.Quit();

    //...

Using prepared statements with JDBCTemplate

class Main {
    public static void main(String args[]) throws Exception {
        ApplicationContext ac = new
          ClassPathXmlApplicationContext("context.xml", Main.class);
        DataSource dataSource = (DataSource) ac.getBean("dataSource");
// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        String prasobhName = 
        jdbcTemplate.query(
           "select first_name from customer where last_name like ?",
            new PreparedStatementSetter() {
              public void setValues(PreparedStatement preparedStatement) throws
                SQLException {
                  preparedStatement.setString(1, "nair%");
              }
            }, 
            new ResultSetExtractor<Long>() {
              public Long extractData(ResultSet resultSet) throws SQLException,
                DataAccessException {
                  if (resultSet.next()) {
                      return resultSet.getLong(1);
                  }
                  return null;
              }
            }
        );
        System.out.println(machaceksName);
    }
}

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

Object of class DateTime could not be converted to string

Try this:

$Date = $row['valdate']->format('d/m/Y'); // the result will 01/12/2015

NOTE: $row['valdate'] its a value date in the database

jQuery - how to check if an element exists?

Mostly, I prefer to use this syntax :

if ($('#MyId')!= null) {
    // dostuff
}

Even if this code is not commented, the functionality is obvious.

How do I display a text file content in CMD?

You can use the more command. For example:

more filename.txt

Take a look at GNU utilities for Win32 or download it:

Convert interface{} to int

Adding another answer that uses switch... There are more comprehensive examples out there, but this will give you the idea.

In example, t becomes the specified data type within each case scope. Note, you have to provide a case for only one type at a type, otherwise t remains an interface.

package main

import "fmt"

func main() {
    var val interface{} // your starting value
    val = 4

    var i int // your final value

    switch t := val.(type) {
    case int:
        fmt.Printf("%d == %T\n", t, t)
        i = t
    case int8:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case int16:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case int32:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case int64:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case bool:
        fmt.Printf("%t == %T\n", t, t)
        // // not covertible unless...
        // if t {
        //  i = 1
        // } else {
        //  i = 0
        // }
    case float32:
        fmt.Printf("%g == %T\n", t, t)
        i = int(t) // standardizes across systems
    case float64:
        fmt.Printf("%f == %T\n", t, t)
        i = int(t) // standardizes across systems
    case uint8:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case uint16:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case uint32:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case uint64:
        fmt.Printf("%d == %T\n", t, t)
        i = int(t) // standardizes across systems
    case string:
        fmt.Printf("%s == %T\n", t, t)
        // gets a little messy...
    default:
        // what is it then?
        fmt.Printf("%v == %T\n", t, t)
    }

    fmt.Printf("i == %d\n", i)
}

python requests get cookies

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}

How to insert a line break before an element using CSS

This works for me:

#restart:before {
    content: ' ';
    clear: right;
    display: block;
}

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.

  2. Is git saving every repository locally (in the user's machine) and in GitHub?

    If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.

  4. How does Git compare to a backup system such as Time Machine?

    Git is specifically designed and optimized for source code.

  5. Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?

    Exactly.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    See #4.

Laravel 5: Display HTML with Blade

Please use

{!! $test !!} 

Only in case of HTML while if you want to render data, sting etc. use

{{ $test }}

This is because when your blade file is compiled

{{ $test }} is converted to <?php echo e($test) ?> while

{!! $test !!} is converted to <?php echo $test ?>

ViewDidAppear is not called when opening app from background

try adding this in AppDelegate applicationWillEnterForeground.

func applicationWillEnterForeground(_ application: UIApplication) {        
    // makes viewWillAppear run
    self.window?.rootViewController?.beginAppearanceTransition(true, animated: false)
    self.window?.rootViewController?.endAppearanceTransition()
}

ImportError: No module named MySQLdb

If you're having issues compiling the binary extension, or on a platform where you cant, you can try using the pure python PyMySQL bindings.

Simply pip install pymysql and switch your SQLAlchemy URI to start like this:

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://.....'

There are some other drivers you could also try.

Adding text to ImageView in Android

With a FrameLayout you can place a text on top of an image view, the frame layout holding both an imageView and a textView.

If that's not enough and you want something more fancy like 'drawing' text, you need to draw text on a canvas - a sample is here: How to draw RTL text (Arabic) onto a Bitmap and have it ordered properly?

string decode utf-8

Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?

How do I pass data to Angular routed components?

I looked at every solution (and tried a few) from this page but I was not convinced that we have to kind of implement a hack-ish way to achieve the data transfer between route.

Another problem with simple history.state is that if you are passing an instance of a particular class in the state object, it will not be the instance while receiving it. But it will be a plain simple JavaScript object.

So in my Angular v10 (Ionic v5) application, I did this-

this.router.navigateByUrl('/authenticate/username', {
    state: {user: new User(), foo: 'bar'}
});

enter image description here

And in the navigating component ('/authenticate/username'), in ngOnInit() method, I printed the data with this.router.getCurrentNavigation().extras.state-

ngOnInit() {
    console.log('>>authenticate-username:41:',
        this.router.getCurrentNavigation().extras.state);
}

enter image description here

And I got the desired data which was passed-

enter image description here

getApplication() vs. getApplicationContext()

Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.

Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).

So if you want the Application class you registered in the Manifest, you should never call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).

Why does getApplicationContext() exist in the first place ?

getApplication() is only available in the Activity class and the Service class, whereas getApplicationContext() is declared in the Context class.

That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext(). Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.

When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext() delegates it's call to baseContext.getApplicationContext().

One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

I know this is not an exact and precise answer, but still, does that answer your question?

JSON to PHP Array using file_get_contents

The JSON sample you provided is not valid. Check it online with this JSON Validator http://jsonlint.com/. You need to remove the extra comma on line 59.

One you have valid json you can use this code to convert it to an array.

json_decode($json, true);

Array
(
    [bpath] => http://www.sampledomain.com/
    [clist] => Array
        (
            [0] => Array
                (
                    [cid] => 11
                    [display_type] => grid
                    [ctitle] => abc
                    [acount] => 71
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6865
                                    [adate] => 2 Hours ago
                                    [atitle] => test
                                    [adesc] => test desc
                                    [aimg] => 
                                    [aurl] => ?nid=6865
                                    [weburl] => news.php?nid=6865
                                    [cmtcount] => 0
                                )

                            [1] => Array
                                (
                                    [aid] => 6857
                                    [adate] => 20 Hours ago
                                    [atitle] => test1
                                    [adesc] => test desc1
                                    [aimg] => 
                                    [aurl] => ?nid=6857
                                    [weburl] => news.php?nid=6857
                                    [cmtcount] => 0
                                )

                        )

                )

            [1] => Array
                (
                    [cid] => 1
                    [display_type] => grid
                    [ctitle] => test1
                    [acount] => 2354
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6851
                                    [adate] => 1 Days ago
                                    [atitle] => test123
                                    [adesc] => test123 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6851
                                    [weburl] => news.php?nid=6851
                                    [cmtcount] => 7
                                )

                            [1] => Array
                                (
                                    [aid] => 6847
                                    [adate] => 2 Days ago
                                    [atitle] => test12345
                                    [adesc] => test12345 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6847
                                    [weburl] => news.php?nid=6847
                                    [cmtcount] => 7
                                )

                        )

                )

        )

)

Filter array to have unique values

This is for es2015 and above as far as I know. There are 'cleaner' options with ES6 but this a great way to do it (with TypeScript).

let values: any[] = [];
const distinct = (value: any, index: any, self: any) => {
    return self.indexOf(value) === index;
};
values = values.filter(distinct);

Sum columns with null values in oracle

The top-rated answer with NVL is totally valid. If you have any interest in making your SQL code more portable, you might want to use CASE, which is supported with the same syntax in both Oracle and SQL Server:

select 
  type,craft,
  SUM(
    case when regular is null
         then 0
         else regular
    end
    +
    case when overtime is null
         then 0
         else overtime
    end
  ) as total_hours
from 
  hours_t
group by
  type
 ,craft
order by
  type
 ,craft

Partly JSON unmarshal into a map in Go

Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

  1. Create your structs for the Chat.
  2. Decode json to the Struct.
  3. Now you can access everything in Struct/Object easily.

Look below at the working code. Copy and paste it.

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

MSOnline can't be imported on PowerShell (Connect-MsolService error)

The following is needed:

  • MS Online Services Assistant needs to be downloaded and installed.
  • MS Online Module for PowerShell needs to be downloaded and installed
  • Connect to Microsoft Online in PowerShell

Source: http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/

Then Follow this one if you're running a 64bits computer: I’m running a x64 OS currently (Win8 Pro).

Copy the folder MSOnline from (1) –> (2) as seen here

1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules(MSOnline)

2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules(MSOnline)

Source: http://blog.clauskonrad.net/2013/06/powershell-and-c-cant-load-msonline.html

Hope this is better and can save some people's time

Maven with Eclipse Juno

All the info you need, is provided in the release announcement for m2e 1.1:

m2e 1.1 has been released as part of Eclipse Juno simultaneous release today.

[...]

m2e 1.1 is already included in "Eclipse IDE for Java Developers" package available from http://eclipse.org/downloads/ or it can be installed from Eclipse Juno release repository [2]. Eclipse 3.7/Indigo users can install the new version from m2e release repository [3]

[...]

[2] http://download.eclipse.org/releases/juno

[3] http://download.eclipse.org/technology/m2e/releases

Is multiplication and division using shift operators in C actually faster?

If you compare output for x+x , x*2 and x<<1 syntax on a gcc compiler, then you would get the same result in x86 assembly : https://godbolt.org/z/JLpp0j

        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi
        mov     eax, DWORD PTR [rbp-4]
        add     eax, eax
        pop     rbp
        ret

So you can consider gcc as smart enought to determine his own best solution independently from what you typed.

Import and Export Excel - What is the best library?

I've used Flexcel in the past and it was great. But this was more for programmatically creating and updating excel worksheets.

Calling dynamic function with dynamic number of parameters

The simplest way might be:

var func='myDynamicFunction_'+myHandler;
var arg1 = 100, arg2 = 'abc';

window[func].apply(null,[arg1, arg2]);

Assuming, that target function is already attached to a "window" object.

Getting "conflicting types for function" in C, why?

You are trying to call do_something before you declare it. You need to add a function prototype before your printf line:

char* do_something(char*, const char*);

Or you need to move the function definition above the printf line. You can't use a function before it is declared.

How to select all rows which have same value in some column

SELECT * FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Update : for better performance and faster query its good to add e1 before *

SELECT e1.* FROM employees e1, employees e2 
WHERE e1.phoneNumber = e2.phoneNumber 
AND e1.id != e2.id;

Splitting a string into separate variables

Foreach-object operation statement:

$a,$b = 'hi.there' | foreach split .
$a,$b

hi
there

The performance impact of using instanceof in Java

instanceof is probably going to be more costly than a simple equals in most real world implementations (that is, the ones where instanceof is really needed, and you can't just solve it by overriding a common method, like every beginner textbook as well as Demian above suggest).

Why is that? Because what is probably going to happen is that you have several interfaces, that provide some functionality (let's say, interfaces x, y and z), and some objects to manipulate that may (or not) implement one of those interfaces... but not directly. Say, for instance, I have:

w extends x

A implements w

B extends A

C extends B, implements y

D extends C, implements z

Suppose I am processing an instance of D, the object d. Computing (d instanceof x) requires to take d.getClass(), loop through the interfaces it implements to know whether one is == to x, and if not do so again recursively for all of their ancestors... In our case, if you do a breadth first exploration of that tree, yields at least 8 comparisons, supposing y and z don't extend anything...

The complexity of a real-world derivation tree is likely to be higher. In some cases, the JIT can optimize most of it away, if it is able to resolve in advance d as being, in all possible cases, an instance of something that extends x. Realistically, however, you are going to go through that tree traversal most of the time.

If that becomes an issue, I would suggest using a handler map instead, linking the concrete class of the object to a closure that does the handling. It removes the tree traversal phase in favor of a direct mapping. However, beware that if you have set a handler for C.class, my object d above will not be recognized.

here are my 2 cents, I hope they help...

Compilation error: stray ‘\302’ in program etc

This problem comes when you have copied some text from html or you have done modification in windows environment and trying to compile in Unix/Solaris environment.

Please do "dos2unix" to remove the special characters from the file:

dos2unix fileName.ext fileName.ext

#1214 - The used table type doesn't support FULLTEXT indexes

Before MySQL 5.6 Full-Text Search is supported only with MyISAM Engine.

Therefore either change the engine for your table to MyISAM

CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

Here is SQLFiddle demo

or upgrade to 5.6 and use InnoDB Full-Text Search.

Update query PHP MySQL

Update a row or column of a table

$update = "UPDATE daily_patients SET queue_status = 'pending' WHERE doctor_id = $room_no and serial_number= $serial_num";

if ($con->query($update) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $con->error;
}

"Fatal error: Cannot redeclare <function>"

I had this pop up recently where a function was being called prior to its definition in the same file, and it didnt have the returned value assigned to a variable. Adding a var for the return value to be assigned to made the error go away.

Javascript loop through object array?

for (let key in data) {
    let value = data[key];
    for (i = 0; i < value.length; i++) {
      console.log(value[i].msgFrom);
      console.log(value[i].msgBody);
    }
  }

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

8388608 bytes is 8M, the default limit in PHP. Update your post_max_size in php.ini to a larger value.

upload_max_filesize sets the max file size that a user can upload while post_max_size sets the maximum amount of data that can be sent via a POST in a form.

So you can set upload_max_filesize to 1 meg, which will mean that the biggest single file a user can upload is 1 megabyte, but they could upload 5 of them at once if the post_max_size was set to 5.

LIKE operator in LINQ

You can call the single method with a predicate:

var portCode = Database.DischargePorts
                   .Single(p => p.PortName.Contains("BALTIMORE"))
                   .PortCode;

RandomForestClassfier.fit(): ValueError: could not convert string to float

Well, there are important differences between how OneHot Encoding and Label Encoding work :

  • Label Encoding will basically switch your String variables to int. In this case, the 1st class found will be coded as 1, the 2nd as 2, ... But this encoding creates an issue.

Let's take the example of a variable Animal = ["Dog", "Cat", "Turtle"].

If you use Label Encoder on it, Animal will be [1, 2, 3]. If you parse it to your machine learning model, it will interpret Dog is closer than Cat, and farther than Turtle (because distance between 1 and 2 is lower than distance between 1 and 3).

Label encoding is actually excellent when you have ordinal variable.

For example, if you have a value Age = ["Child", "Teenager", "Young Adult", "Adult", "Old"],

then using Label Encoding is perfect. Child is closer than Teenager than it is from Young Adult. You have a natural order on your variables

  • OneHot Encoding (also done by pd.get_dummies) is the best solution when you have no natural order between your variables.

Let's take back the previous example of Animal = ["Dog", "Cat", "Turtle"].

It will create as much variable as classes you encounter. In my example, it will create 3 binary variables : Dog, Cat and Turtle. Then if you have Animal = "Dog", encoding will make it Dog = 1, Cat = 0, Turtle = 0.

Then you can give this to your model, and he will never interpret that Dog is closer from Cat than from Turtle.

But there are also cons to OneHotEncoding. If you have a categorical variable encountering 50 kind of classes

eg : Dog, Cat, Turtle, Fish, Monkey, ...

then it will create 50 binary variables, which can cause complexity issues. In this case, you can create your own classes and manually change variable

eg : regroup Turtle, Fish, Dolphin, Shark in a same class called Sea Animals and then appy a OneHotEncoding.

How to concatenate variables into SQL strings

You can accomplish this (if I understand what you are trying to do) using dynamic SQL.

The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.

So you can use something like this approach:

SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue 
    + ' AS fld1 FROM tbl' + @KeyValue

EXEC (@stmt)

First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:

'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'

At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE (or EXEC for short).

The old-school sp_executesql procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.


FOLLOWUP

EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.

Consider what would happen if @KeyValue contained the string:

'1 AS foo; DROP TABLE students; -- '

The string we would produce as a SQL statement would be:

'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'

When we EXECUTE that string as a SQL statement:

INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...

And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)

One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'. If an illegal character is found, then reject the value, and exit without executing any SQL.

Get method arguments using Spring AOP?

If it's a single String argument, do: joinPoint.getArgs()[0];

How do I delete a Git branch locally and remotely?

A one-liner command to delete both local, and remote:

D=branch-name; git branch -D $D; git push origin :$D

Or add the alias below to your ~/.gitconfig. Usage: git kill branch-name

[alias]
    kill = "!f(){ git branch -D \"$1\";  git push origin --delete \"$1\"; };f"