Programs & Examples On #Screensharing

How to add font-awesome to Angular 2 + CLI project

I wasted several hours trying to get the latest version of FontAwesome 5.2.0 working with AngularCLI 6.0.3 and Material Design. I followed the npm installation instructions off of the FontAwesome website

Their latest docs instruct you do install using the following:

npm install @fortawesome/fontawesome-free

After wasting several hours I finally uninstalled it and installed font awesome using the following command (this installs FontAwesome v4.7.0):

npm install font-awesome --save

Now it's working fine using:

$fa-font-path: "~font-awesome/fonts" !default;
@import "~font-awesome/scss/font-awesome.scss";
<mat-icon fontSet="fontawesome" fontIcon="fa-android"></mat-icon>

JPA : How to convert a native query result set to POJO class collection

Using "Database View" like entity a.k.a immutable entity is super easy for this case.

Normal entity

@Entity
@Table(name = "people")
data class Person(
  @Id
  val id: Long = -1,
  val firstName: String = "",
  val lastName: String? = null
)

View like entity

@Entity
@Immutable
@Subselect("""
select
    p.id,
    concat(p.first_name, ' ', p.last_name) as full_name
from people p
""")
data class PersonMin(
  @Id
  val id: Long,
  val fullName: String,
)

In any repository we can create query function/method just like:

@Query(value = "select p from PersonMin p")
fun findPeopleMinimum(pageable: Pageable): Page<PersonMin>

log4j vs logback

Your decision should be based on

  • your actual need for these "more features"; and
  • your expected cost of implementing the change.

You should resist the urge to change APIs just because it's "newer, shinier, better." I follow a policy of "if it's not broken, don't kick it."

If your application requires a very sophisticated logging framework, you may want to consider why.

Checkbox for nullable boolean

Checkbox only offer you 2 values (true, false). Nullable boolean has 3 values (true, false, null) so it's impossible to do it with a checkbox.

A good option is to use a drop down instead.

Model

public bool? myValue;
public List<SelectListItem> valueList;

Controller

model.valueList = new List<SelectListItem>();
model.valueList.Add(new SelectListItem() { Text = "", Value = "" });
model.valueList.Add(new SelectListItem() { Text = "Yes", Value = "true" });
model.valueList.Add(new SelectListItem() { Text = "No", Value = "false" });

View

@Html.DropDownListFor(m => m.myValue, valueList)

How to add 30 minutes to a JavaScript Date object?

Here is the ES6 version:

let getTimeAfter30Mins = () => {
  let timeAfter30Mins = new Date();
  timeAfter30Mins = new Date(timeAfter30Mins.setMinutes(timeAfter30Mins.getMinutes() + 30));
};

Call it like:

getTimeAfter30Mins();

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

You have upgraded to Razor 3. Remember that VS 12 (until update 4) doesn't support it. Install The Razor 3 from nuget or downgrade it through these step

geekswithblogs.net/anirugu/archive/2013/11/04/how-to-downgrade-razor-3-and-fix-the-issue-that.aspx

Print raw string from variable? (not getting the answers)

I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com. But when I print it in the interactive mode I get double slash - '\\w' as @Jimmynoarms said:

The Solution for python 3x:

print(r'%s' % your_variable_pattern_str)

How to set environment variables in Python?

When you play with environment variables (add/modify/remove variables), a good practice is to restore the previous state at function completion.

You may need something like the modified_environ context manager describe in this question to restore the environment variables.

Classic usage:

with modified_environ(DEBUSSY="1"):
    call_my_function()

How to show multiline text in a table cell

I added only <br> inside the <td> and it works good, break the line!

How to select bottom most rows?

First, create an index in a subquery according to the table's original order using:

ROW_NUMBER () OVER (ORDER BY (SELECT NULL) ) AS RowIndex

Then order the table descending by the RowIndex column you've created in the main query:

ORDER BY RowIndex DESC

And finally use TOP with your wanted quantity of rows:

    SELECT TOP 1 * --(or 2, or 5, or 34)
    FROM   (SELECT ROW_NUMBER() OVER (ORDER BY  (SELECT NULL) ) AS RowIndex, * 
            FROM MyTable) AS SubQuery
    ORDER BY RowIndex DESC

Programmatically Creating UILabel

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];

How to hide app title in android?

You can do it programatically:

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class ActivityName extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

Or you can do it via your AndroidManifest.xml file:

<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>

Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

On Windows I had solved this problem in the following way :

1) uninstalled Python

2) navigated to C:\Users\MyName\AppData\Local\Programs(your should turn on hidden files visibility Show hidden files instruction)

3) deleted 'Python' folder

4) installed Python

C# string does not contain possible?

Use Enumerable.Contains function:

var result =
    !(compareString.Contains(firstString) || compareString.Contains(secondString));

Remove columns from DataTable in C#

To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.

DataTable dt;
int desiredSize = 10;

while (dt.Columns.Count > desiredSize)
{
   dt.Columns.RemoveAt(desiredSize);
}

standard size for html newsletter template

Bdizzle,

I would recommend that you read this link

You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.

Be happy, Julian

Init array of structs in Go

You can have it this way:

It is important to mind the commas after each struct item or set of items.

earnings := []LineItemsType{

        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
    }

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

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

Also, you should try this:

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

Java : How to determine the correct charset encoding of a stream

check this out: http://site.icu-project.org/ (icu4j) they have libraries for detecting charset from IOStream could be simple like this:

BufferedInputStream bis = new BufferedInputStream(input);
CharsetDetector cd = new CharsetDetector();
cd.setText(bis);
CharsetMatch cm = cd.detect();

if (cm != null) {
   reader = cm.getReader();
   charset = cm.getName();
}else {
   throw new UnsupportedCharsetException()
}

git-diff to ignore ^M

GitHub suggests that you should make sure to only use \n as a newline character in git-handled repos. There's an option to auto-convert:

$ git config --global core.autocrlf true

Of course, this is said to convert crlf to lf, while you want to convert cr to lf. I hope this still works …

And then convert your files:

# Remove everything from the index
$ git rm --cached -r .

# Re-add all the deleted files to the index
# You should get lots of messages like: "warning: CRLF will be replaced by LF in <file>."
$ git diff --cached --name-only -z | xargs -0 git add

# Commit
$ git commit -m "Fix CRLF"

core.autocrlf is described on the man page.

What are all codecs and formats supported by FFmpeg?

You can see the list of supported codecs in the official documentation:

Supported video codecs

Supported audio codecs

How to access the contents of a vector from a pointer to the vector in C++?

vector <int> numbers {10,20,30,40};
vector <int> *ptr {nullptr};

ptr = &numbers;

for(auto num: *ptr){
 cout << num << endl;
}


cout << (*ptr).at(2) << endl; // 20

cout << "-------" << endl;

cout << ptr -> at(2) << endl; // 20

"Invalid JSON primitive" in Ajax processing

these answers just had me bouncing back and forth between invalid parameter and missing parameter.

this worked for me , just wrap string variables in quotes...

data: { RecordId: RecordId,
            UserId: UId,
            UserProfileId: UserProfileId,
            ItemType: '"' +  ItemType + '"',
            FileName: '"' +  XmlName + '"'
    }

Java generating Strings with placeholders

You won't need a library; if you are using a recent version of Java, have a look at String.format:

String.format("Hello %s!", "world");

How to select different app.config for several build configurations

SlowCheetah and FastKoala from the VisualStudio Gallery seem to be very good tools that help out with this problem.

However, if you want to avoid addins or use the principles they implement more extensively throughout your build/integration processes then adding this to your msbuild *proj files is a shorthand fix.

Note: this is more or less a rework of the No. 2 of @oleksii's answer.

This works for .exe and .dll projects:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
  </Target>

This works for web projects:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
  </Target>

Note that this step happens even before the build proper begins. The transformation of the config file happens in the project folder. So that the transformed web.config is available when you are debugging (a drawback of SlowCheetah).

Do remember that if you create the App_Config folder (or whatever you choose to call it), the various intermediate config files should have a Build Action = None, and Copy to Output Directory = Do not copy.

This combines both options into one block. The appropriate one is executed based on conditions. The TransformXml task is defined first though:

<Project>
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Condition="Exists('App_Config\app.Base.config')" Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
    <TransformXml Condition="Exists('App_Config\Web.Base.config')" Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
</Target>

Angular 2: How to style host element of the component?

Try the :host > /deep/ :

Add the following to the parent.component.less file

:host {
    /deep/ app-child-component {
       //your child style
    }
}

Replace the app-child-component by your child selector

What's the best way to add a full screen background image in React Native

An another easy solution:

<Image source={require('../assets/background.png')}
      style={{position: 'absolute', zIndex: -1}}/>

<View style={{flex: 1, position: 'absolute'}}>

  {/*rest of your content*/}
</View>

Programmatically change the height and width of a UIImageView Xcode Swift

A faster / alternative way to change the height and/or width of a UIView is by setting its width/height through frame.size:

let neededHeight = UIScreen.main.bounds.height * 0.2
yourView.frame.size.height = neededHeight

Make $JAVA_HOME easily changable in Ubuntu

I know this is a long cold question, but it comes up every time there is a new or recent major Java release. Now this would easily apply to 6 and 7 swapping.

I have done this in the past with update-java-alternatives: http://manpages.ubuntu.com/manpages/hardy/man8/update-java-alternatives.8.html

Determining if Swift dictionary contains key and obtaining any of its values

The accepted answer let keyExists = dict[key] != nil will not work if the Dictionary contains the key but has a value of nil.

If you want to be sure the Dictionary does not contain the key at all use this (tested in Swift 4).

if dict.keys.contains(key) {
  // contains key
} else { 
  // does not contain key
}

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

failed to find target with hash string android-23

I had this issue when using windows. It turned out that the SDK location in my profiles was the issue. So I had to relocate my SDK folder to documents and then it worked.

How to make a movie out of images in python

Thanks , but i found an alternative solution using ffmpeg:

def save():
    os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")

But thank you for your help :)

$(window).height() vs $(document).height

you need know what it is mean about document and window.

  1. The window object represents an open window in a browser.click here
  2. The Document object is the root of a document tree.click here

How to write a stored procedure using phpmyadmin and how to use it through php?

Since a stored procedure is created, altered and dropped using queries you actually CAN manage them using phpMyAdmin.

To create a stored procedure, you can use the following (change as necessary) :

CREATE PROCEDURE sp_test()
BEGIN
  SELECT 'Number of records: ', count(*) from test;
END//

And make sure you set the "Delimiter" field on the SQL tab to //.

Once you created the stored procedure it will appear in the Routines fieldset below your tables (in the Structure tab), and you can easily change/drop it.

To use the stored procedure from PHP you have to execute a CALL query, just like you would do in plain SQL.

SQL Server add auto increment primary key to existing table

alter table /** paste the tabal's name **/ add id int IDENTITY(1,1)

delete from /** paste the tabal's name **/ where id in

(

select a.id FROM /** paste the tabal's name / as a LEFT OUTER JOIN ( SELECT MIN(id) as id FROM / paste the tabal's name / GROUP BY / paste the columns c1,c2 .... **/

) as t1 
ON a.id = t1.id

WHERE t1.id IS NULL

)

alter table /** paste the tabal's name **/ DROP COLUMN id

Which is better, return value or out parameter?

Return values are almost always the right choice when the method doesn't have anything else to return. (In fact, I can't think of any cases where I'd ever want a void method with an out parameter, if I had the choice. C# 7's Deconstruct methods for language-supported deconstruction acts as a very, very rare exception to this rule.)

Aside from anything else, it stops the caller from having to declare the variable separately:

int foo;
GetValue(out foo);

vs

int foo = GetValue();

Out values also prevent method chaining like this:

Console.WriteLine(GetValue().ToString("g"));

(Indeed, that's one of the problems with property setters as well, and it's why the builder pattern uses methods which return the builder, e.g. myStringBuilder.Append(xxx).Append(yyy).)

Additionally, out parameters are slightly harder to use with reflection and usually make testing harder too. (More effort is usually put into making it easy to mock return values than out parameters). Basically there's nothing I can think of that they make easier...

Return values FTW.

EDIT: In terms of what's going on...

Basically when you pass in an argument for an "out" parameter, you have to pass in a variable. (Array elements are classified as variables too.) The method you call doesn't have a "new" variable on its stack for the parameter - it uses your variable for storage. Any changes in the variable are immediately visible. Here's an example showing the difference:

using System;

class Test
{
    static int value;

    static void ShowValue(string description)
    {
        Console.WriteLine(description + value);
    }

    static void Main()
    {
        Console.WriteLine("Return value test...");
        value = 5;
        value = ReturnValue();
        ShowValue("Value after ReturnValue(): ");

        value = 5;
        Console.WriteLine("Out parameter test...");
        OutParameter(out value);
        ShowValue("Value after OutParameter(): ");
    }

    static int ReturnValue()
    {
        ShowValue("ReturnValue (pre): ");
        int tmp = 10;
        ShowValue("ReturnValue (post): ");
        return tmp;
    }

    static void OutParameter(out int tmp)
    {
        ShowValue("OutParameter (pre): ");
        tmp = 10;
        ShowValue("OutParameter (post): ");
    }
}

Results:

Return value test...
ReturnValue (pre): 5
ReturnValue (post): 5
Value after ReturnValue(): 10
Out parameter test...
OutParameter (pre): 5
OutParameter (post): 10
Value after OutParameter(): 10

The difference is at the "post" step - i.e. after the local variable or parameter has been changed. In the ReturnValue test, this makes no difference to the static value variable. In the OutParameter test, the value variable is changed by the line tmp = 10;

Case Function Equivalent in Excel

If you don't have a SWITCH statement in your Excel version (pre-Excel-2016), here's a VBA implementation for it:

Public Function SWITCH(ParamArray args() As Variant) As Variant
    Dim i As Integer
    Dim val As Variant
    Dim tmp As Variant

    If ((UBound(args) - LBound(args)) = 0) Or (((UBound(args) - LBound(args)) Mod 2 = 0)) Then
        Error 450       'Invalid arguments
    Else
        val = args(LBound(args))
        i = LBound(args) + 1
        tmp = args(UBound(args))

        While (i < UBound(args))
            If val = args(i) Then
                tmp = args(i + 1)
            End If
            i = i + 2
        Wend
    End If

    SWITCH = tmp
End Function

It works exactly like expected, a drop-in replacement for example for Google Spreadsheet's SWITCH function.

Syntax:

=SWITCH(selector; [keyN; valueN;] ...  defaultvalue)

where

  • selector is any expression that is compared to keys
  • key1, key2, ... are expressions that are compared to the selector
  • value1, value2, ... are values that are selected if the selector equals to the corresponding key (only)
  • defaultvalue is used if no key matches the selector

Examples:

=SWITCH("a";"?")                       returns "?"
=SWITCH("a";"a";"1";"?")               returns "1"
=SWITCH("x";"a";"1";"?")               returns "?"
=SWITCH("b";"a";"1";"b";TRUE;"?")      returns TRUE
=SWITCH(7;7;1;7;2;0)                   returns 2
=SWITCH("a";"a";"1")                   returns #VALUE!

To use it, open your Excel, go to Develpment tools tab, click Visual Basic, rightclick on ThisWorkbook, choose Insert, then Module, finally copy the code into the editor. You have to save as a macro-friendly Excel workbook (xlsm).

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

Flushing footer to bottom of the page, twitter bootstrap

A working example for Twitter bootstrap NOT STICKY FOOTER

<script>
$(document).ready(function() {

    var docHeight = $(window).height();
    var footerHeight = $('#footer').height();
    var footerTop = $('#footer').position().top + footerHeight;

    if (footerTop < docHeight)
        $('#footer').css('margin-top', 10+ (docHeight - footerTop) + 'px');
});
</script>

Version that always updates in case user opens devtools or resizes window.

<script>
    $(document).ready(function() {
        setInterval(function() {
            var docHeight = $(window).height();
            var footerHeight = $('#footer').height();
            var footerTop = $('#footer').position().top + footerHeight;
            var marginTop = (docHeight - footerTop + 10);

            if (footerTop < docHeight)
                $('#footer').css('margin-top', marginTop + 'px'); // padding of 30 on footer
            else
                $('#footer').css('margin-top', '0px');
            // console.log("docheight: " + docHeight + "\n" + "footerheight: " + footerHeight + "\n" + "footertop: " + footerTop + "\n" + "new docheight: " + $(window).height() + "\n" + "margintop: " + marginTop);
        }, 250);
    });
</script>

You need at least an element with a #footer

When not want the scrollbar if content would fit to screen just change the value of 10 to 0
The scrollbar will show up if content not fits to screen.

jQuery checkbox event handling

Use the change event.

$('#myform :checkbox').change(function() {
    // this represents the checkbox that was checked
    // do something with it
});

Changing the highlight color when selecting text in an HTML text input

I guess this can help :

selection styles

It's possible to define color and background for text the user selects.

Try it below. If you select something and it looks like this, your browser supports selection styles.

This is the paragraph with normal ::selection.

This is the paragraph with ::-moz-selection.

This is the paragraph with ::-webkit-selection.

Testsheet:

p.normal::selection {
  background:#cc0000;
  color:#fff;
}

p.moz::-moz-selection {
  background:#cc0000;
  color:#fff;
}

p.webkit::-webkit-selection {
  background:#cc0000;
  color:#fff;
}

Quoted from Quirksmode

Standardize data columns in R

You can easily normalize the data also using data.Normalization function in clusterSim package. It provides different method of data normalization.

    data.Normalization (x,type="n0",normalization="column")

Arguments

x
vector, matrix or dataset type
type of normalization: n0 - without normalization

n1 - standardization ((x-mean)/sd)

n2 - positional standardization ((x-median)/mad)

n3 - unitization ((x-mean)/range)

n3a - positional unitization ((x-median)/range)

n4 - unitization with zero minimum ((x-min)/range)

n5 - normalization in range <-1,1> ((x-mean)/max(abs(x-mean)))

n5a - positional normalization in range <-1,1> ((x-median)/max(abs(x-median)))

n6 - quotient transformation (x/sd)

n6a - positional quotient transformation (x/mad)

n7 - quotient transformation (x/range)

n8 - quotient transformation (x/max)

n9 - quotient transformation (x/mean)

n9a - positional quotient transformation (x/median)

n10 - quotient transformation (x/sum)

n11 - quotient transformation (x/sqrt(SSQ))

n12 - normalization ((x-mean)/sqrt(sum((x-mean)^2)))

n12a - positional normalization ((x-median)/sqrt(sum((x-median)^2)))

n13 - normalization with zero being the central point ((x-midrange)/(range/2))

normalization
"column" - normalization by variable, "row" - normalization by object

How to sort a dataFrame in python pandas by two or more columns?

For large dataframes of numeric data, you may see a significant performance improvement via numpy.lexsort, which performs an indirect sort using a sequence of keys:

import pandas as pd
import numpy as np

np.random.seed(0)

df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1 = pd.concat([df1]*100000)

def pdsort(df1):
    return df1.sort_values(['a', 'b'], ascending=[True, False])

def lex(df1):
    arr = df1.values
    return pd.DataFrame(arr[np.lexsort((-arr[:, 1], arr[:, 0]))])

assert (pdsort(df1).values == lex(df1).values).all()

%timeit pdsort(df1)  # 193 ms per loop
%timeit lex(df1)     # 143 ms per loop

One peculiarity is that the defined sorting order with numpy.lexsort is reversed: (-'b', 'a') sorts by series a first. We negate series b to reflect we want this series in descending order.

Be aware that np.lexsort only sorts with numeric values, while pd.DataFrame.sort_values works with either string or numeric values. Using np.lexsort with strings will give: TypeError: bad operand type for unary -: 'str'.

SQL Error: ORA-00922: missing or invalid option

there's nothing wrong with using CHAR like that.. I think your problem is that you have a space in your tablename. It should be: charteredflight or chartered_flight..

nvm is not compatible with the npm config "prefix" option:

I had this issue after moving my home folder to a new drive on linux. It was fixed by removing .nvm folder and reinstalling nvm

Concatenate columns in Apache Spark DataFrame

Here's how you can do custom naming

import pyspark
from pyspark.sql import functions as sf
sc = pyspark.SparkContext()
sqlc = pyspark.SQLContext(sc)
df = sqlc.createDataFrame([('row11','row12'), ('row21','row22')], ['colname1', 'colname2'])
df.show()

gives,

+--------+--------+
|colname1|colname2|
+--------+--------+
|   row11|   row12|
|   row21|   row22|
+--------+--------+

create new column by concatenating:

df = df.withColumn('joined_column', 
                    sf.concat(sf.col('colname1'),sf.lit('_'), sf.col('colname2')))
df.show()

+--------+--------+-------------+
|colname1|colname2|joined_column|
+--------+--------+-------------+
|   row11|   row12|  row11_row12|
|   row21|   row22|  row21_row22|
+--------+--------+-------------+

Multiple HttpPost method in Web API controller

use:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

it's not a RESTful approach anymore, but you can now call your actions by name (rather than let the Web API automatically determine one for you based on the verb) like this:

[POST] /api/VTRouting/TSPRoute

[POST] /api/VTRouting/Route

Contrary to popular belief, there is nothing wrong with this approach, and it's not abusing Web API. You can still leverage on all the awesome features of Web API (delegating handlers, content negotiation, mediatypeformatters and so on) - you just ditch the RESTful approach.

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You don't have to do anything special, it should just be working.

When I have a fresh rails app with this controller:

class FooController < ApplicationController
  def index
    raise "error"
  end
end

and go to http://127.0.0.1:3000/foo/

I am seeing the exception with a stack trace.

You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.

See config/initializers/backtrace_silencers.rb in your Rails project

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

For me this error appears after cloning the project from a repository. Someone removed a white space from the projects name (renamed: "The Project" to "TheProject") which caused some Build Settings errors to unvalid paths.

Sometimes reading the whole error logs is not a bad idea....

How do I calculate tables size in Oracle

First off, I would generally caution that gathering table statistics in order to do space analysis is a potentially dangerous thing to do. Gathering statistics may change query plans, particularly if the DBA has configured a statistics gathering job that uses non-default parameters that your call is not using, and will cause Oracle to re-parse queries that utilize the table in question which can be a performance hit. If the DBA has intentionally left some tables without statistics (common if your OPTIMIZER_MODE is CHOOSE), gathering statistics can cause Oracle to stop using the rule-based optimizer and start using the cost-based optimizer for a set of queries which can be a major performance headache if it is done unexpectedly in production. If your statistics are accurate, you can query USER_TABLES (or ALL_TABLES or DBA_TABLES) directly without calling GATHER_TABLE_STATS. If your statistics are not accurate, there is probably a reason for that and you don't want to disturb the status quo.

Second, the closest equivalent to the SQL Server sp_spaceused procedure is likely Oracle's DBMS_SPACE package. Tom Kyte has a nice show_space procedure that provides a simple interface to this package and prints out information similar to what sp_spaceused prints out.

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

  1. Right-click on your project, select Maven -> Remove Maven Nature.

  2. Open you terminal, go to your project folder and do mvn eclipse:clean

  3. Right click on your Project and select “Configure -> Convert into Maven Project”

Now you got “Unsupported IClasspathEntry kind=4 Eclipse Scala” disappear.

How to create a bash script to check the SSH connection?

You can use something like this

$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1)

This will output "ok" if ssh connection is ok

Alternative to deprecated getCellType

The accepted answer shows the reason for the deprecation but misses to name the alternative:

CellType    getCellTypeEnum()

where the CellType is the enum decribing the type of the cell.

The plan is to rename getCellTypeEnum() back to getCellType() in POI 4.0.

How to test which port MySQL is running on and whether it can be connected to?

grep port /etc/mysql/my.cnf ( at least in debian/ubuntu works )

or

netstat -tlpn | grep mysql

verify

bind-address 127.0.0.1

in /etc/mysql/my.cnf to see possible restrictions

Getting the computer name in Java

I'm not so thrilled about the InetAddress.getLocalHost().getHostName() solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:

  1. What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.

  2. What if the host is not connected to any network and has no network interfaces ?

All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME on all versions of Windows and the environment variable HOSTNAME on Unix/Linux/MacOS (or alternatively the output from host command hostname if the HOSTNAME environment variable is not available as is the case in old shells like Bourne and Korn).

I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName() method. But that's just me.

UPDATE (Unices)

As others have pointed out the HOSTNAME environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?

Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec() to capture the output from the hostname command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).

Long read

I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName() solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.

It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.

git: 'credential-cache' is not a git command

For the sake of others who come on this issue, I had this same problem in Ubuntu (namely that my passwords weren't caching, despite having set the option correctly, and getting the error git: 'credential-cache' is not a git command.), until I found out that this feature is only available in Git 1.7.9 and above.

Being on an older distribution of Ubuntu (Natty; I'm a stubborn Gnome 2 user) the version in the repo was git version 1.7.4.1. I used the following PPA to upgrade: https://launchpad.net/~git-core/+archive/ppa

How do you get the string length in a batch file?

If you insist on having this trivial function in pure batch I suggest this:

@echo off

set x=somestring
set n=0
set m=255

:loop
if "!x:~%m%,1!" == "" (
    set /a "m>>=1"
    goto loop
) else (
    set /a n+=%m%+1
    set x=!x:~%m%!
    set x=!x:~1!
    if not "!x!" == "" goto loop
)

echo %n%

PS. You must have delayed variable expansion enabled to run this.

EDIT. Now I have made an improved version:

@echo off

set x=somestring
set n=0

for %%m in (4095 2047 1023 511 255 127 63 31 15 7 3 1 0) do (
    if not "!x:~%%m,1!" == "" (
        set /a n+=%%m+1
        set x=!x:~%%m!
        set x=!x:~1!
        if "!x!" == "" goto done
    )
)

:done
echo %n%

EDIT2. If you have a C compiler or something on your system you can create the programs you need and miss on the fly if they don't exist. This method is very general. Take string length as an example:

@echo off

set x=somestring

if exist strlen.exe goto comp
echo #include "string.h" > strlen.c
echo int main(int argc, char* argv[]) { return strlen(argv[1]); } >> strlen.c
CL strlen.c 

:comp
strlen "%x%"
set n=%errorlevel%
echo %n%

You have to set up PATH, INCLUDE and LIB appropriately. This too can be done on the fly from the batch script. Even if you don't know whether you've got a compiler or don't know where it is you can search for it in your script.

Finding non-numeric rows in dataframe in pandas?

I'm thinking something like, just give an idea, to convert the column to string, and work with string is easier. however this does not work with strings containing numbers, like bad123. and ~ is taking the complement of selection.

df['a'] = df['a'].astype(str)
df[~df['a'].str.contains('0|1|2|3|4|5|6|7|8|9')]
df['a'] = df['a'].astype(object)

and using '|'.join([str(i) for i in range(10)]) to generate '0|1|...|8|9'

or using np.isreal() function, just like the most voted answer

df[~df['a'].apply(lambda x: np.isreal(x))]

Make Axios send cookies in its requests automatically

So I had this exact same issue and lost about 6 hours of my life searching, I had the

withCredentials: true

But the browser still didn't save the cookie until for some weird reason I had the idea to shuffle the configuration setting:

Axios.post(GlobalVariables.API_URL + 'api/login', {
        email,
        password,
        honeyPot
    }, {
        withCredentials: true,
        headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
    }});

Seems like you should always send the 'withCredentials' Key first.

Identifying country by IP address

Amazon's CloudFront content delivery network can now be configured to pass this information through as a header. Given Amazon's size (they're big and stable, not going anywhere) and this is configuration over code (no third-party API to learn or code to maintain), all around believe this to be the best option.

If you do not use AWS CloudFront, I'd look into seeing if your CDN has a similar header option that can be turned on. Usually the large providers are quick to push for feature parity. And if you are not using a CDN, you could put CloudFront in front of your infrastructure and simply set the origin to resolve to whatever you are currently using.

Additionally, it also makes sense to resolve this at the CDN level. Your CDN is already having to figure out geo location to route the user to the nearest content node, might as well pass this information along and not figure it out twice through a third party API (this becomes chokepoint for your app, waiting for a geo location lookup to resolve). No need to do this work twice (and the second time, arguably less resilient [e.g., 3rd party geo lookup]).

https://aws.amazon.com/blogs/aws/enhanced-cloudfront-customization/

Geo-Targeting – CloudFront will detect the user’s country of origin and pass along the county code to you in the CloudFront-Viewer-Country header. You can use this information to customize your responses without having to use URLs that are specific to each country.

What does -XX:MaxPermSize do?

The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).

This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :

The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.

Note that this other Oracle documentation lists the other HotSpot arguments.

Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.

Can you autoplay HTML5 videos on the iPad?

iOS 10 update

The ban on autoplay has been lifted as of iOS 10 - but with some restrictions (e.g. A can be autoplayed if there is no audio track).

To see a full list of these restrictions, see the official docs: https://webkit.org/blog/6784/new-video-policies-for-ios/

iOS 9 and before

As of iOS 6.1, it is no longer possible to auto-play videos on the iPad.

My assumption as to why they've disabled the auto-play feature?

Well, as many device owners have data usage/bandwidth limits on their devices, I think Apple felt that the user themselves should decide when they initiate bandwidth usage.


After a bit of research I found the following extract in the Apple documentation in regard to auto-play on iOS devices to confirm my assumption:

"Apple has made the decision to disable the automatic playing of video on iOS devices, through both script and attribute implementations.

In Safari, on iOS (for all devices, including iPad), where the user may be on a cellular network and be charged per data unit, preload and auto-play are disabled. No data is loaded until the user initiates it." - Apple documentation.

Here is a separate warning featured on the Safari HTML5 Reference page about why embedded media cannot be played in Safari on iOS:

Warning: To prevent unsolicited downloads over cellular networks at the user’s expense, embedded media cannot be played automatically in Safari on iOS—the user always initiates playback. A controller is automatically supplied on iPhone or iPod touch once playback in initiated, but for iPad you must either set the controls attribute or provide a controller using JavaScript.


What this means (in terms of code) is that Javascript's play() and load() methods are inactive until the user initiates playback, unless the play() or load() method is triggered by user action (e.g. a click event).

Basically, a user-initiated play button works, but an onLoad="play()" event does not.

For example, this would play the movie:

<input type="button" value="Play" onclick="document.myMovie.play()">

Whereas the following would do nothing on iOS:

<body onload="document.myMovie.play()">

Jetty: HTTP ERROR: 503/ Service Unavailable

2012-04-20 11:14:32.617:WARN:oejx.XmlParser:FATAL@file:/C:/Users/***/workspace/Test/WEB-INF/web.xml line:1 col:7 : org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

You Log says, that you web.xml is malformed. Line 1, colum 7. It may be a UTF-8 Byte-Order-Marker

Try to verify, that your xml is wellformed and does not have a BOM. Java doesn't use BOMs.

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:

x='some
thing'

y=${x%$'\n'*}

After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

If the issue is a missing intermediate certificate, you can enable Oracle JRE to automatically download the missing intermediate certificate as explained in this answer.

Just set the Java system property -Dcom.sun.security.enableAIAcaIssuers=true

For this to work the server's certificate must provide the URI to the intermediate certificate (the certificate's issuer). As far as I can tell, this is what browsers do as well and should be just as secure - I'm not a security expert though.

Edit: If I recall correctly, this seems to work at least with Java 8 and is documented here for Java 9.

recursion versus iteration

Short answer: the trade off is recursion is faster and for loops take up less memory in almost all cases. However there are usually ways to change the for loop or recursion to make it run faster

How to render a DateTime in a specific format in ASP.NET MVC 3?

works for me

<%=Model.MyDateTime.ToString("dd-MMM-yyyy")%>

Annotations from javax.validation.constraints not working

I came across this problem recently in a very similar situation: Met all requirements as the top-rated answer listed but still got the wrong result.

So I looked at my dependencies and found I was missing some of them. I corrected it by adding the missing dependencies.

I was using hibernate, the required dependencies were: Dependencies Snapshot

*Snapshot taken in class "Spring & Hibernate for Beginners" @ Udemy

Android getResources().getDrawable() deprecated API 22

Edit: see my blog post on the subject for a more complete explanation


You should use the following code from the support library instead:

ContextCompat.getDrawable(context, R.drawable.***)

Using this method is equivalent to calling:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}

As of API 21, you should use the getDrawable(int, Theme) method instead of getDrawable(int), as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int) method is equivalent to calling getDrawable(int, null).

How to create a generic array in Java?

I found a sort of a work around to this problem.

The line below throws generic array creation error

List<Person>[] personLists=new ArrayList<Person>()[10];

However if I encapsulate List<Person> in a separate class, it works.

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


public class PersonList {

    List<Person> people;

    public PersonList()
    {
        people=new ArrayList<Person>();
    }
}

You can expose people in the class PersonList thru a getter. The line below will give you an array, that has a List<Person> in every element. In other words array of List<Person>.

PersonList[] personLists=new PersonList[10];

I needed something like this in some code I was working on and this is what I did to get it to work. So far no problems.

How to do joins in LINQ on multiple fields in single join

Just to complete this with an equivalent method chain syntax:

entity.Join(entity2, x => new {x.Field1, x.Field2},
                     y => new {y.Field1, y.Field2}, (x, y) => x);

While the last argument (x, y) => x is what you select (in the above case we select x).

Why dividing two integers doesn't get a float?

This is because of implicit conversion. The variables b, c, d are of float type. But the / operator sees two integers it has to divide and hence returns an integer in the result which gets implicitly converted to a float by the addition of a decimal point. If you want float divisions, try making the two operands to the / floats. Like follows.

#include <stdio.h>

int main() {
    int a;
    float b, c, d;
    a = 750;
    b = a / 350.0f;
    c = 750;
    d = c / 350;
    printf("%.2f %.2f", b, d);
    // output: 2.14 2.14
    return 0;
}

List of lists into numpy array

As this is the top search on Google for converting a list of lists into a Numpy array, I'll offer the following despite the question being 4 years old:

>>> x = [[1, 2], [1, 2, 3], [1]]
>>> y = numpy.hstack(x)
>>> print(y)
[1 2 1 2 3 1]

When I first thought of doing it this way, I was quite pleased with myself because it's soooo simple. However, after timing it with a larger list of lists, it is actually faster to do this:

>>> y = numpy.concatenate([numpy.array(i) for i in x])
>>> print(y)
[1 2 1 2 3 1]

Note that @Bastiaan's answer #1 doesn't make a single continuous list, hence I added the concatenate.

Anyway...I prefer the hstack approach for it's elegant use of Numpy.

"Cannot GET /" with Connect on Node.js

The easiest way to serve static files is to use "harp". It can be found here. You can serve up your files from the location you want via node is:

var harp = require("harp")
harp.server(projectPath [,args] [,callback])

Hope this helps.

Password encryption/decryption code in .NET

I use RC2CryptoServiceProvider.

    public static string EncryptText(string openText)
    {
        RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
        ICryptoTransform encryptor = rc2CSP.CreateEncryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv));
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                byte[] toEncrypt = Encoding.Unicode.GetBytes(openText);

                csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
                csEncrypt.FlushFinalBlock();

                byte[] encrypted = msEncrypt.ToArray();

                return Convert.ToBase64String(encrypted);
            }
        }
    }

    public static string DecryptText(string encryptedText)
    {
        RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
        ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv));
        using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText)))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                List<Byte> bytes = new List<byte>();
                int b;
                do
                {
                    b = csDecrypt.ReadByte();
                    if (b != -1)
                    {
                        bytes.Add(Convert.ToByte(b));
                    }

                }
                while (b != -1);

                return Encoding.Unicode.GetString(bytes.ToArray());
            }
        }
    }

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

if while In visual studio with IIS express working and when published failed try this:enter image description here

C++: Rounding up to the nearest multiple of a number

Here is a super simple solution to show the concept of elegance. It's basically for grid snaps.

(pseudo code)

nearestPos = Math.Ceil( numberToRound / multiple ) * multiple;

Objective-C for Windows

If you just want to experiment, there's an Objective-C compiler for .NET (Windows) here: qckapp

Printing all global variables/local variables?

In addition, since info locals does not display the arguments to the function you're in, use

(gdb) info args

For example:

int main(int argc, char *argv[]) {
    argc = 6*7;    //Break here.
    return 0;
}

argc and argv won't be shown by info locals. The message will be "No locals."

Reference: info locals command.

Remove Safari/Chrome textinput/textarea glow

Carl W:

This effect can occur on non-input elements, too. I've found the following works as a more general solution

:focus {
  outline-color: transparent;
  outline-style: none;
}

I’ll explain this:

  • :focus means it styles the elements that are in focus. So we are styling the elements in focus.
  • outline-color: transparent; means that the blue glow is transparent.
  • outline-style: none; does the same thing.

How to run a class from Jar which is not the Main-Class in its Manifest file

You can create your jar without Main-Class in its Manifest file. Then :

java -cp MyJar.jar com.mycomp.myproj.dir2.MainClass2 /home/myhome/datasource.properties /home/myhome/input.txt

Run Bash Command from PHP

Your shell_exec is executed by www-data user, from its directory. You can try

putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");

Where your script is located in /home/user/bin Later on you can

$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;

To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh

How can I disable all views inside the layout?

I personally use something like this (vertical tree traversal using recursion)

fun ViewGroup.deepForEach(function: View.() -> Unit) {
    this.forEach { child ->
        child.function()
        if (child is ViewGroup) {
            child.deepForEach(function)
        }
    }
}

usage :

   viewGroup.deepForEach { isEnabled = false }

Is there an XSL "contains" directive?

there is indeed an xpath contains function it should look something like:

<xsl:for-each select="item">
<xsl:variable name="hhref" select="link" />
<xsl:variable name="pdate" select="pubDate" />
<xsl:if test="not(contains(hhref,'1234'))">
  <li>
    <a href="{$hhref}" title="{$pdate}">
      <xsl:value-of select="title"/>
    </a>
  </li>
</xsl:if>

Why and when to use angular.copy? (Deep Copy)

In that case, you don't need to use angular.copy()

Explanation :

  • = represents a reference whereas angular.copy() creates a new object as a deep copy.

  • Using = would mean that changing a property of response.data would change the corresponding property of $scope.example or vice versa.

  • Using angular.copy() the two objects would remain seperate and changes would not reflect on each other.

HTML input arrays

There are some references and pointers in the comments on this page at PHP.net:

Torsten says

"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."

Jetboy says

"according to this: http://www.w3.org/TR/xhtml1/#C_8 the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."

Is there Unicode glyph Symbol to represent "Search"

You can simply add this CSS to your header

<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>

next add this code in place where you want to display a glyph symbol.

<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->

Have fun.

How to multi-line "Replace in files..." in Notepad++

Actually it's way easier to use ToolBucket plugin for Notepad++ to multiline replace.

To activate it just go to N++ menu:

Plugins > Plugin Manager > Show Plugin Manager > Check ToolBucket > Install.

Restart N++ and press ALT + SHIFT + F to multiline edit.

Jenkins Pipeline Wipe Out Workspace

Like @gotgenes pointed out with Jenkins Version. 2.74, the below works, not sure since when, maybe if some one can edit and add the version above

cleanWs()

With, Jenkins Version 2.16 and the Workspace Cleanup Plugin, that I have, I use

step([$class: 'WsCleanup'])

to delete the workspace.

You can view it by going to

JENKINS_URL/job/<any Pipeline project>/pipeline-syntax

Then selecting "step: General Build Step" from Sample step and then selecting "Delete workspace when build is done" from Build step

Auto code completion on Eclipse

I had a similar issue when I switched from IntellijIDEA to Eclipse. It can be done in the following steps. Go to Window > Preferences > Java > Editor > Content Assist and type ._abcdefghijklmnopqrstuvwxyzS in the Auto activation triggers for Java field

How to have comments in IntelliSense for function in Visual Studio?

All these others answers make sense, but are incomplete. Visual Studio will process XML comments but you have to turn them on. Here's how to do that:

Intellisense will use XML comments you enter in your source code, but you must have them enabled through Visual Studio Options. Go to Tools > Options > Text Editor. For Visual Basic, enable the Advanced > Generate XML documentation comments for ''' setting. For C#, enable the Advanced > Generate XML documentation comments for /// setting. Intellisense will use the summary comments when entered. They will be available from other projects after the referenced project is compiled.

To create external documentation, you need to generate an XML file through the Project Settings > Build > XML documentation file: path that controls the compiler's /doc option. You will need an external tool that will take the XML file as input and generate the documentation in your choice of output formats.

Be aware that generating the XML file can noticeably increase your compile time.

How to create an empty DataFrame with a specified schema?

Java version to create empty DataSet:

public Dataset<Row> emptyDataSet(){

    SparkSession spark = SparkSession.builder().appName("Simple Application")
                .config("spark.master", "local").getOrCreate();

    Dataset<Row> emptyDataSet = spark.createDataFrame(new ArrayList<>(), getSchema());

    return emptyDataSet;
}

public StructType getSchema() {

    String schemaString = "column1 column2 column3 column4 column5";

    List<StructField> fields = new ArrayList<>();

    StructField indexField = DataTypes.createStructField("column0", DataTypes.LongType, true);
    fields.add(indexField);

    for (String fieldName : schemaString.split(" ")) {
        StructField field = DataTypes.createStructField(fieldName, DataTypes.StringType, true);
        fields.add(field);
    }

    StructType schema = DataTypes.createStructType(fields);

    return schema;
}

Maven plugin in Eclipse - Settings.xml file is missing

Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/

But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing

-rw-r--r--@

thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:

-rw-r--rw-@

This did it. The message disappeared.

Get table names using SELECT statement in MySQL

I think it may be helpful to point out that if you want to select tables that contain specific words you can easily do it using the SELECT (instead of SHOW). Below query easily narrows down the search to tables that contain "keyword"

SELECT *
FROM information_schema.tables
WHERE table_name like "%keyword%"

Run bash script as daemon

You can go to /etc/init.d/ - you will see a daemon template called skeleton.

You can duplicate it and then enter your script under the start function.

How to use putExtra() and getExtra() for string data

This is what i have been using, hopfully it helps someone.. simple and affective.

send data

    intent = new Intent(getActivity(), CheckinActivity.class);
    intent.putExtra("mealID", meal.Meald);
    startActivity(intent);

get data

    int mealId;

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();

    if(bundle != null){
        mealId = bundle.getInt("mealID");
    }

cheers!

Should I put input elements inside a label element?

I greatly prefer to wrap elements inside my <label> because I don't have to generate the ids.

I am a Javascript developer, and React or Angular are used to generate components that can be reused by me or others. It would be then easy to duplicate an id in the page, leading there to strange behaviours.

Generate a random letter in Python

import string
import random

def random_char(y):
    return ''.join(random.choice(string.ascii_letters+string.digits+li) for x in range(y))
no=int(input("Enter the number of character for your password=  "))
li = random.choice('!@#$%^*&( )_+}{')
print(random_char(no)+li)

Query to get only numbers from a string

T-SQL function to read all the integers from text and return the one at the indicated index, starting from left or right, also using a starting search term (optional):

create or alter function dbo.udf_number_from_text(
    @text nvarchar(max),
    @search_term nvarchar(1000) = N'',
    @number_position tinyint = 1,
    @rtl bit = 0
) returns int
as
    begin
        declare @result int = 0;
        declare @search_term_index int = 0;

        if @text is null or len(@text) = 0 goto exit_label;
        set @text = trim(@text);
        if len(@text) = len(@search_term) goto exit_label;

        if len(@search_term) > 0
            begin
                set @search_term_index = charindex(@search_term, @text);
                if @search_term_index = 0 goto exit_label;
            end;

        if @search_term_index > 0
            if @rtl = 0
                set @text = trim(right(@text, len(@text) - @search_term_index - len(@search_term) + 1));
            else
                set @text = trim(left(@text, @search_term_index - 1));
        if len(@text) = 0 goto exit_label;

        declare @patt_number nvarchar(10) = '%[0-9]%';
        declare @patt_not_number nvarchar(10) = '%[^0-9]%';
        declare @number_start int = 1;
        declare @number_end int;
        declare @found_numbers table (id int identity(1,1), val int);

        while @number_start > 0
        begin
            set @number_start = patindex(@patt_number, @text);
            if @number_start > 0
                begin
                    if @number_start = len(@text)
                        begin
                            insert into @found_numbers(val)
                            select cast(substring(@text, @number_start, 1) as int);

                            break;
                        end;
                    else
                        begin
                            set @text = right(@text, len(@text) - @number_start + 1);
                            set @number_end = patindex(@patt_not_number, @text);

                            if @number_end = 0
                                begin
                                    insert into @found_numbers(val)
                                    select cast(@text as int);

                                    break;
                                end;
                            else
                                begin
                                    insert into @found_numbers(val)
                                    select cast(left(@text, @number_end - 1) as int);

                                    if @number_end = len(@text)
                                        break;
                                    else
                                        begin
                                            set @text = trim(right(@text, len(@text) - @number_end));
                                            if len(@text) = 0 break;
                                        end;
                                end;
                        end;
                end;
        end;

        if @rtl = 0
            select @result = coalesce(a.val, 0)
            from (select row_number() over (order by m.id asc) as c_row, m.val
                    from @found_numbers as m) as a
            where a.c_row = @number_position;
        else
            select @result = coalesce(a.val, 0)
            from (select row_number() over (order by m.id desc) as c_row, m.val
                    from @found_numbers as m) as a
            where a.c_row = @number_position;


        exit_label:
            return @result;
    end;

Example:

select dbo.udf_number_from text(N'Text text 10 text, 25 term', N'term',2,1);

returns 10;

Anaconda version with Python 3.5

According to the official docu it's recommended to downgrade the whole Python environment:

conda install python=3.5

Android: remove left margin from actionbar's custom layout

I did not find a solution for my issue (first picture) anywhere, but at last I end up with a simplest solution after a few hours of digging. Please note that I tried with a lot of xml attributes like app:setInsetLeft="0dp", etc.. but none of them helped in this case.

Picture 1 enter image description here

the following code solved this issue as in the Picture 2

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    //NOTE THAT: THE PART SOLVED THE PROBLEM.
    android.support.design.widget.AppBarLayout abl = (AppBarLayout)
            findViewById(R.id.app_bar_main_app_bar_layout);

    abl.setPadding(0,0,0,0);
}

Picture 2

enter image description here

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

How to write text in ipython notebook?

Adding to Matt's answer above (as I don't have comment privileges yet), one mouse-free workflow would be:

Esc then m then Enter so that you gain focus again and can start typing.

Without the last Enter you would still be in Escape mode and would otherwise have to use your mouse to activate text input in the cell.

Another way would be to add a new cell, type out your markdown in "Code" mode and then change to markdown once you're done typing everything you need, thus obviating the need to refocus.

You can then move on to your next cells. :)

How to cherry-pick from a remote branch?

Just as an addendum to OP accepted answer:

If you having issues with

fatal: bad object xxxxx

that's because you don't have access to that commit. Which means you don't have that repo stored locally. Then:

git remote add LABEL_FOR_THE_REPO REPO_YOU_WANT_THE_COMMIT_FROM
git fetch LABEL_FOR_THE_REPO
git cherry-pick xxxxxxx

Where xxxxxxx is the commit hash you want.

numpy get index where value is true

To get the row numbers where at least one item is larger than 15:

>>> np.where(np.any(e>15, axis=1))
(array([1, 2], dtype=int64),)

mysql stored-procedure: out parameter

SET out_number=SQRT(input_number); 

Instead of this write:

select SQRT(input_number); 

Please don't write SET out_number and your input parameter should be:

PROCEDURE `test`.`my_sqrt`(IN input_number INT, OUT out_number FLOAT) 

EOFError: EOF when reading a line

**The best is to use try except block to get rid of EOF **

try:
    width = input()
    height = input()
    def rectanglePerimeter(width, height):
       return ((width + height)*2)
    print(rectanglePerimeter(width, height))
except EOFError as e:
    print(end="")

StringIO in Python3

try this

from StringIO import StringIO

x="1 3\n 4.5 8"

numpy.genfromtxt(StringIO(x))

Removing the fragment identifier from AngularJS urls (# symbol)

To remove the Hash tag for a pretty URL and also for your code to work after minification you need to structure your code like the example below:

jobApp.config(['$routeProvider','$locationProvider',
    function($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'views/job-list.html',
                controller: 'JobListController'
            }).
            when('/menus', {
                templateUrl: 'views/job-list.html',
                controller: 'JobListController'
            }).
            when('/menus/:id', {
                templateUrl: 'views/job-detail.html',
                controller: 'JobDetailController'
            });

         //you can include a fallback by  including .otherwise({
          //redirectTo: '/jobs'
        //});


        //check browser support
        if(window.history && window.history.pushState){
            //$locationProvider.html5Mode(true); will cause an error $location in HTML5 mode requires a  tag to be present! Unless you set baseUrl tag after head tag like so: <head> <base href="/">

         // to know more about setting base URL visit: https://docs.angularjs.org/error/$location/nobase

         // if you don't wish to set base URL then use this
         $locationProvider.html5Mode({
                 enabled: true,
                 requireBase: false
          });
        }
    }]);

Python module for converting PDF to text

Additionally there is PDFTextStream which is a commercial Java library that can also be used from Python.

How to convert String to long in Java?

public class StringToLong {

   public static void main (String[] args) {

      // String s = "fred";    // do this if you want an exception

      String s = "100";

      try {
         long l = Long.parseLong(s);
         System.out.println("long l = " + l);
      } catch (NumberFormatException nfe) {
         System.out.println("NumberFormatException: " + nfe.getMessage());
      }

   }
}

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

below answer worked for me, you can try:

sudo apt-get install python3-lxml

Can you target an elements parent element using event.target?

$(document).on("click", function(event){
   var a = $(event.target).parents();
   var flaghide = true;
    a.each(function(index, val){
       if(val == $(container)[0]){
           flaghide = false;
        }
    });
    if(flaghide == true){
        //required code
    }
})

How to assign a heredoc value to a variable in Bash?

You can avoid a useless use of cat and handle mismatched quotes better with this:

$ read -r -d '' VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF

If you don't quote the variable when you echo it, newlines are lost. Quoting it preserves them:

$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

If you want to use indentation for readability in the source code, use a dash after the less-thans. The indentation must be done using only tabs (no spaces).

$ read -r -d '' VAR <<-'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
    EOF
$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

If, instead, you want to preserve the tabs in the contents of the resulting variable, you need to remove tab from IFS. The terminal marker for the here doc (EOF) must not be indented.

$ IFS='' read -r -d '' VAR <<'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
EOF
$ echo "$VAR"
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''

Tabs can be inserted at the command line by pressing Ctrl-V Tab. If you are using an editor, depending on which one, that may also work or you may have to turn off the feature that automatically converts tabs to spaces.

SELECT INTO USING UNION QUERY

You can also try:

create table new_table as
select * from table1
union
select * from table2

Get the current language in device

The others have given good answers for the device language,

if you wish the app language the easiest way to do it is by adding an app_lang key to your strings.xml file, and specify the lang for each of the langs as well.

That way, if your app's default language is different from the device language, you can chose to send that as parameter for your services.

Exporting PDF with jspdf not rendering CSS

jspdf does not work with css but it can work along with html2canvas. You can use jspdf along with html2canvas.

include these two files in script on your page :

<script type="text/javascript" src="html2canvas.js"></script>
  <script type="text/javascript" src="jspdf.min.js"></script>
  <script type="text/javascript">
  function genPDF()
  {
   html2canvas(document.body,{
   onrendered:function(canvas){

   var img=canvas.toDataURL("image/png");
   var doc = new jsPDF();
   doc.addImage(img,'JPEG',20,20);
   doc.save('test.pdf');
   }

   });

  }
  </script>

You need to download script files such as https://github.com/niklasvh/html2canvas/releases https://cdnjs.com/libraries/jspdf

make clickable button on page so that it will generate pdf and it will be seen same as that of original html page.

<a href="javascript:genPDF()">Download PDF</a>  

It will work perfectly.

How to select rows with NaN in particular column?

Try the following:

df[df['Col2'].isnull()]

Float a div in top right corner without overlapping sibling header

This worked for me:

h1 {
    display: inline;
    overflow: hidden;
}
div {
    position: relative;
    float: right;
}

It's similar to the approach of the media object, by Stubbornella.

Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)

AngularJS - Any way for $http.post to send request parameters instead of JSON?

Modify the default headers:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";

Then use JQuery's $.param method:

var payload = $.param({key: value});
$http.post(targetURL, payload);

Force “landscape” orientation mode

It is now possible with the HTML5 webapp manifest. See below.


Original answer:

You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.

You can detect the device orientation with CSS3 media queries like this:

@media screen and (orientation:portrait) {
    // CSS applied when the device is in portrait mode
}

@media screen and (orientation:landscape) {
    // CSS applied when the device is in landscape mode
}

Or by binding a JavaScript orientation change event like this:

document.addEventListener("orientationchange", function(event){
    switch(window.orientation) 
    {  
        case -90: case 90:
            /* Device is in landscape mode */
            break; 
        default:
            /* Device is in portrait mode */
    }
});

Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.

As explained on html5rocks.com, you can now force the orientation mode using a manifest.json file.

You need to include those line into the json file:

{
    "display":      "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
    "orientation":  "landscape", /* Could be "landscape" or "portrait" */
    ...
}

And you need to include the manifest into your html file like this:

<link rel="manifest" href="manifest.json">

Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.

What parameters should I use in a Google Maps URL to go to a lat-lon?

This is current accepted way to link to a specific lat lon (rather than search for the nearest object).

http://maps.google.com/maps?z=12&t=m&q=loc:38.9419+-78.3020
  • z is the zoom level (1-20)
  • t is the map type ("m" map, "k" satellite, "h" hybrid, "p" terrain, "e" GoogleEarth)
  • q is the search query, if it is prefixed by loc: then google assumes it is a lat lon separated by a +

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

It is important to define an id in the model

.DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Model(model => model.Id(p => p.id))
    )

Playing a video in VideoView in Android

VideoView videoView =(VideoView) findViewById(R.id.videoViewId);

Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo");

 videoView.setVideoURI(uri);
videoView.start();

Instead of using setVideoPath use setVideoUri. you can get path of your video stored in external storage by using (Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo")and parse it into Uri. If your video is stored in sdcard/MyVideo/video.mp4 replace "/yourvideo" in code by "/MyVideo/video.mp4"

This works fine for me :) `

Best practice for partial updates in a RESTful service

Things to add to your augmented question. I think you can often perfectly design more complicated business actions. But you have to give away the method/procedure style of thinking and think more in resources and verbs.

mail sendings


POST /customers/123/mails

payload:
{from: [email protected], subject: "foo", to: [email protected]}

The implementation of this resource + POST would then send out the mail. if necessary you could then offer something like /customer/123/outbox and then offer resource links to /customer/mails/{mailId}.

customer count

You could handle it like a search resource (including search metadata with paging and num-found info, which gives you the count of customers).


GET /customers

response payload:
{numFound: 1234, paging: {self:..., next:..., previous:...} customer: { ...} ....}

Modelling an elevator using Object-Oriented Analysis and Design

I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.

A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:

  1. Representation of the central controller (assuming there is one).

  2. Representations of elevators

  3. Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.

  4. Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).

  5. Representation of a human and cargo (may be important for factoring in maximal loads)

  6. Representation of the building (in some cases, as certain floors may be blocked at times, etc.)

Multiple select in Visual Studio?

There is supposedly a way to do it now with Ctrl + Alt + Click but I use this extension because it has a bunch of other nice features that I use: https://marketplace.visualstudio.com/items?itemName=thomaswelen.SelectNextOccurrence

Append String in Swift

According to Swift 4 Documentation, String values can be added together (or concatenated) with the addition operator (+) to create a new String value:

let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"

You can also append a String value to an existing String variable with the addition assignment operator (+=):

var instruction = "look over"
instruction += string2
// instruction now equals "look over there"

You can append a Character value to a String variable with the String type’s append() method:

let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"

Merging Cells in Excel using C#

You can use NPOI to do it.

Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue("This is a test of merging");

sheet.addMergedRegion(new CellRangeAddress(
        1, //first row (0-based)
        1, //last row  (0-based)
        1, //first column (0-based)
        2  //last column  (0-based)
));

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

How do I find the version of Apache running without access to the command line?

Use this PHP script:

 $version = apache_get_version();
    echo "$version\n";

Se apache_get_version.

wait process until all subprocess finish?

A Popen object has a .wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).

If you use this method, you'll prevent that the process zombies are lying around for too long.

(Alternatively, you can use subprocess.call() or subprocess.check_call() for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_)call().)

If you have several subprocesses to wait for, you can do

exit_codes = [p.wait() for p in p1, p2]

which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.

Rollback transaction after @Test

The answers mentioning adding @Transactional are correct, but for simplicity you could just have your test class extends AbstractTransactionalJUnit4SpringContextTests.

Why do we need the "finally" clause in Python?

In your first example, what happens if run_code1() raises an exception that is not TypeError? ... other_code() will not be executed.

Compare that with the finally: version: other_code() is guaranteed to be executed regardless of any exception being raised.

Deleting Row in SQLite in Android

The only way that worked for me was this

fun removeCart(mCart: Cart) {
    val db = dbHelper.writableDatabase
    val deleteLineWithThisValue = mCart.f
    db.delete(cons.tableNames[3], Cart.KEY_f + "  LIKE  '%" + deleteLineWithThisValue + "%' ", null)
}


class Cart {
    var a: String? = null
    var b: String? = null
    var c: String? = null
    var d: String? = null
    var e: Int? = null
    var f: String? = null

companion object {
    // Labels Table Columns names
    const val rowIdKey = "_id"
    const val idKey = "id"
    const val KEY_a = "a"
    const val KEY_b = "b"
    const val KEY_c = "c"
    const val KEY_d = "d"
    const val KEY_e = "e"
    const val KEY_f = "f"
   }
}

object cons {
    val tableNames = arrayOf(
            /*0*/ "shoes",
            /*1*/ "hats",
            /*2*/ "shirt",
            /*3*/ "car"
         )
 }

TypeError: Cannot read property 'then' of undefined

TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.

If you are calling a Python service, the code will look like below:

this.updateTalentSupplier=function(supplierObj){
  var promise = $http({
    method: 'POST',
      url: bbConfig.BWS+'updateTalentSupplier/',
      data:supplierObj,
      withCredentials: false,
      contentType:'application/json',
      dataType:'json'
    });
    return promise; //Promise is returned 
}

We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.

Reading CSV file and storing values into an array

Hi all, I created a static class for doing this. + column check + quota sign removal

public static class CSV
{
    public static List<string[]> Import(string file, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
    {
        return ReadCSVFile(file, csvDelimiter, ignoreHeadline, removeQuoteSign);
    }

    private static List<string[]> ReadCSVFile(string filename, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
    {
        string[] result = new string[0];
        List<string[]> lst = new List<string[]>();

        string line;
        int currentLineNumner = 0;
        int columnCount = 0;

        // Read the file and display it line by line.  
        using (System.IO.StreamReader file = new System.IO.StreamReader(filename))
        {
            while ((line = file.ReadLine()) != null)
            {
                currentLineNumner++;
                string[] strAr = line.Split(csvDelimiter);
                // save column count of dirst line
                if (currentLineNumner == 1)
                {
                    columnCount = strAr.Count();
                }
                else
                {
                    //Check column count of every other lines
                    if (strAr.Count() != columnCount)
                    {
                        throw new Exception(string.Format("CSV Import Exception: Wrong column count in line {0}", currentLineNumner));
                    }
                }

                if (removeQuoteSign) strAr = RemoveQouteSign(strAr);

                if (ignoreHeadline)
                {
                    if(currentLineNumner !=1) lst.Add(strAr);
                }
                else
                {
                    lst.Add(strAr);
                }
            }

        }

        return lst;
    }
    private static string[] RemoveQouteSign(string[] ar)
    {
        for (int i = 0;i< ar.Count() ; i++)
        {
            if (ar[i].StartsWith("\"") || ar[i].StartsWith("'")) ar[i] = ar[i].Substring(1);
            if (ar[i].EndsWith("\"") || ar[i].EndsWith("'")) ar[i] = ar[i].Substring(0,ar[i].Length-1);

        }
        return ar;
    }

}

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Delete a row in DataGridView Control in VB.NET

For Each row As DataGridViewRow In yourDGV.SelectedRows
    yourDGV.Rows.Remove(row)
Next

This will delete all rows that had been selected.

Python: Fetch first 10 results from a list

The itertools module has lots of great stuff in it. So if a standard slice (as used by Levon) does not do what you want, then try the islice function:

from itertools import islice
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
iterator = islice(l, 10)
for item in iterator:
    print item

TCP: can two different sockets share a port?

Theoretically, yes. Practice, not. Most kernels (incl. linux) doesn't allow you a second bind() to an already allocated port. It weren't a really big patch to make this allowed.

Conceptionally, we should differentiate between socket and port. Sockets are bidirectional communication endpoints, i.e. "things" where we can send and receive bytes. It is a conceptional thing, there is no such field in a packet header named "socket".

Port is an identifier which is capable to identify a socket. In case of the TCP, a port is a 16 bit integer, but there are other protocols as well (for example, on unix sockets, a "port" is essentially a string).

The main problem is the following: if an incoming packet arrives, the kernel can identify its socket by its destination port number. It is a most common way, but it is not the only possibility:

  • Sockets can be identified by the destination IP of the incoming packets. This is the case, for example, if we have a server using two IPs simultanously. Then we can run, for example, different webservers on the same ports, but on the different IPs.
  • Sockets can be identified by their source port and ip as well. This is the case in many load balancing configurations.

Because you are working on an application server, it will be able to do that.

How to use global variables in React Native?

Set up a flux container

simple example

import alt from './../../alt.js';

    class PostActions {
        constructor(){
        this.generateActions('setMessages');
        }

        setMessages(indexArray){
            this.actions.setMessages(indexArray);
        }
    }


export default alt.createActions(PostActions);

store looks like this

class PostStore{

    constructor(){

       this.messages = [];

       this.bindActions(MessageActions);
    }




    setMessages(messages){
        this.messages = messages;
    }
}

export default alt.createStore(PostStore);

Then every component that listens to the store can share this variable In your constructor is where you should grab it

constructor(props){
    super(props);

   //here is your data you get from the store, do what you want with it 
    var messageStore = MessageStore.getState();

}


    componentDidMount() {
      MessageStore.listen(this.onMessageChange.bind(this));
    }

    componentWillUnmount() {
      MessageStore.unlisten(this.onMessageChange.bind(this));
    }

    onMessageChange(state){ 
        //if the data ever changes each component listining will be notified and can do the proper processing. 
   }

This way, you can share you data across the app without every component having to communicate with each other.

Replace contents of factor column in R dataframe

For the things that you are suggesting you can just change the levels using the levels:

levels(iris$Species)[3] <- 'new'

Adding IN clause List to a JPA Query

You must convert to List as shown below:

    String[] valores = hierarquia.split(".");       
    List<String> lista =  Arrays.asList(valores);

    String jpqlQuery = "SELECT a " +
            "FROM AcessoScr a " +
            "WHERE a.scr IN :param ";

    Query query = getEntityManager().createQuery(jpqlQuery, AcessoScr.class);                   
    query.setParameter("param", lista);     
    List<AcessoScr> acessos = query.getResultList();

Absolute and Flexbox in React Native

Ok, solved my problem, if anyone is passing by here is the answer:

Just had to add left: 0, and top: 0, to the styles, and yes, I'm tired.

position: 'absolute',
left:     0,
top:      0,

Extracting numbers from vectors of strings

A stringr pipelined solution:

library(stringr)
years %>% str_match_all("[0-9]+") %>% unlist %>% as.numeric

Is there a portable way to get the current username in Python?

psutil provides a portable way that doesn't use environment variables like the getpass solution. It is less prone to security issues, and should probably be the accepted answer as of today.

import psutil

def get_username():
    return psutil.Process().username()

Under the hood, this combines the getpwuid based method for unix and the GetTokenInformation method for Windows.

Find text string using jQuery?

Just adding to Tony Miller's answer as this got me 90% towards what I was looking for but still didn't work. Adding .length > 0; to the end of his code got my script working.

 $(function() {
    var foundin = $('*:contains("I am a simple string")').length > 0;
 });

How do I use cascade delete with SQL Server?

First To Enable ONCascade property:

1.Drop the existing foreign key constraint

2.add a new one with the ON DELETE CASCADE setting enabled

Ex:

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.Response'))
 BEGIN 

ALTER TABLE [dbo].[Response] DROP CONSTRAINT [FK_Response_Request]  

ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request]  FOREIGN KEY([RequestId])
REFERENCES [dbo].[Request] ([RequestId])
ON DELETE CASCADE
END

ELSE

 BEGIN 
 ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request]  FOREIGN KEY([RequestId])
REFERENCES [dbo].[Request] ([RequestId])
ON DELETE CASCADE
END

Second To Disable ONCascade property:

1.Drop the existing foreign key constraint

2.Add a new one with the ON DELETE NO ACTION setting enabled

Ex:

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.Response'))
 BEGIN 
ALTER TABLE [dbo].[Response] DROP CONSTRAINT [FK_Response_Request]  

ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request]  FOREIGN KEY([RequestId])
REFERENCES [dbo].[Request] ([RequestId])
ON DELETE CASCADE
END

ELSE

 BEGIN 
 ALTER TABLE [dbo].[Response] WITH CHECK ADD CONSTRAINT [FK_Response_Request]  FOREIGN KEY([RequestId])
REFERENCES [dbo].[Request] ([RequestId])
ON DELETE NO ACTION 
END

android button selector

Best way to implement the selector is by using the xml instead of using programatic way as its more easy to implemnt with xml.

    <?xml version="1.0" encoding="utf-8"?>    
<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/button_bg_selected" android:state_selected="true"></item>
        <item android:drawable="@drawable/button_bg_pressed" android:state_pressed="true"></item>
        <item android:drawable="@drawable/button_bg_normal"></item>

    </selector>

For more information i implemented using this link http://www.blazin.in/2016/03/how-to-use-selectors-for-botton.html

How to escape special characters in building a JSON string?

Using template literals...

var json = `{"1440167924916":{"id":1440167924916,"type":"text","content":"It's a test!"}}`;

Check if an element contains a class in JavaScript?

className is just a string so you can use the regular indexOf function to see if the list of classes contains another string.

printing all contents of array in C#

Another approach with the Array.ForEach<T> Method (T[], Action<T>) method of the Array class

Array.ForEach(myArray, Console.WriteLine);

That takes only one iteration compared to array.ToList().ForEach(Console.WriteLine) which takes two iterations and creates internally a second array for the List (double iteration runtime and double memory consumtion)

Easiest way to develop simple GUI in Python

Tkinter is simple but is too ugly. PyQT can do everything you want but is too big. Perhaps IronPython will be good for you. Take a look at this: Python guis

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

In my case it was a view (highly nested, view in view) insertion causing the error in :

CREATE TABLE tablename AS
  SELECT * FROM highly_nested_viewname
;

The workaround we ended up doing was simulating a materialized view (which is really a table) and periodically insert/update it using stored procedures.

Core Data: Quickest way to delete all instances of an entity

This is a similar question to the one here and someone suggested setting up a relationship delete rule so you only have to delete one object. So if you have or can make an entity with a to-many relationship to the cars and set the delete rule to cascade when you delete the higher entity all the cars will be deleted as well. This may save some processing time since you don't have to do the steps involved with loading ALL the cars. In a larger data set this could be absolutely necessary.

What does CultureInfo.InvariantCulture mean?

According to Microsoft:

The CultureInfo.InvariantCulture property is neither a neutral nor a specific culture. It is the third type of culture that is culture-insensitive. It is associated with the English language but not with a country or region.

(from http://msdn.microsoft.com/en-us/library/4c5zdc6a(vs.71).aspx)

So InvariantCulture is similair to culture "en-US" but not exactly the same. If you write:

var d = DateTime.Now;
var s1 = d.ToString(CultureInfo.InvariantCulture);   // "05/21/2014 22:09:28"
var s2 = d.ToString(new CultureInfo("en-US"));       // "5/21/2014 10:09:28 PM"

then s1 and s2 will have a similar format but InvariantCulture adds leading zeroes and "en-US" uses AM or PM.

So InvariantCulture is better for internal usage when you e.g save a date to a text-file or parses data. And a specified CultureInfo is better when you present data (date, currency...) to the end-user.

What are alternatives to document.write?

The reason that your HTML is replaced is because of an evil JavaScript function: document.write().

It is most definitely "bad form." It only works with webpages if you use it on the page load; and if you use it during runtime, it will replace your entire document with the input. And if you're applying it as strict XHTML structure it's not even valid code.


the problem:

document.write writes to the document stream. Calling document.write on a closed (or loaded) document automatically calls document.open which will clear the document.

-- quote from the MDN

document.write() has two henchmen, document.open(), and document.close(). When the HTML document is loading, the document is "open". When the document has finished loading, the document has "closed". Using document.write() at this point will erase your entire (closed) HTML document and replace it with a new (open) document. This means your webpage has erased itself and started writing a new page - from scratch.

I believe document.write() causes the browser to have a performance decrease as well (correct me if I am wrong).


an example:

This example writes output to the HTML document after the page has loaded. Watch document.write()'s evil powers clear the entire document when you press the "exterminate" button:

_x000D_
_x000D_
I am an ordinary HTML page.  I am innocent, and purely for informational purposes. Please do not <input type="button" onclick="document.write('This HTML page has been succesfully exterminated.')" value="exterminate"/>_x000D_
me!
_x000D_
_x000D_
_x000D_


the alternatives:

  • .innerHTML This is a wonderful alternative, but this attribute has to be attached to the element where you want to put the text.

Example: document.getElementById('output1').innerHTML = 'Some text!';

  • .createTextNode() is the alternative recommended by the W3C.

Example: var para = document.createElement('p'); para.appendChild(document.createTextNode('Hello, '));

NOTE: This is known to have some performance decreases (slower than .innerHTML). I recommend using .innerHTML instead.


the example with the .innerHTML alternative:

_x000D_
_x000D_
I am an ordinary HTML page. _x000D_
I am innocent, and purely for informational purposes. _x000D_
Please do not _x000D_
<input type="button" onclick="document.getElementById('output1').innerHTML = 'There was an error exterminating this page. Please replace <code>.innerHTML</code> with <code>document.write()</code> to complete extermination.';" value="exterminate"/>_x000D_
 me!_x000D_
<p id="output1"></p>
_x000D_
_x000D_
_x000D_

Negative weights using Dijkstra's Algorithm

The algorithm you have suggested will indeed find the shortest path in this graph, but not all graphs in general. For example, consider this graph:

A directed graph with four nodes, A, B, C, and D. Node A has an edge to B of cost 1, an edge to C of cost 0, and an edge to D of cost 99. Node B has an edge to cost 1 to node C. Node D has an edge of cost -300 to node B.

Let's trace through the execution of your algorithm.

  1. First, you set d(A) to 0 and the other distances to 8.
  2. You then expand out node A, setting d(B) to 1, d(C) to 0, and d(D) to 99.
  3. Next, you expand out C, with no net changes.
  4. You then expand out B, which has no effect.
  5. Finally, you expand D, which changes d(B) to -201.

Notice that at the end of this, though, that d(C) is still 0, even though the shortest path to C has length -200. This means that your algorithm doesn't compute the correct distances to all the nodes. Moreover, even if you were to store back pointers saying how to get from each node to the start node A, you'd end taking the wrong path back from C to A.

The reason for this is that Dijkstra's algorithm (and your algorithm) are greedy algorithms that assume that once they've computed the distance to some node, the distance found must be the optimal distance. In other words, the algorithm doesn't allow itself to take the distance of a node it has expanded and change what that distance is. In the case of negative edges, your algorithm, and Dijkstra's algorithm, can be "surprised" by seeing a negative-cost edge that would indeed decrease the cost of the best path from the starting node to some other node.

Hope this helps!

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

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

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

Bootstrap modal not displaying

As Paula, I had the same problem, my modal was not showing, and I realized that my button was in a '< form >' tag ... :

<button class="btn btn-danger" data-toggle="modal" data-target="#deleteItemModal">Delete</button>

I just replaced < button > by < a >, and my modal worked well

<a class="btn btn-danger" data-toggle="modal" data-target="#deleteItemModal">Delete</a>

How to execute an external program from within Node.js?

var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
    // result
});

AngularJS routing without the hash '#'

try

$locationProvider.html5Mode(true)

More info at $locationProvider
Using $location

Simple C example of doing an HTTP POST and consuming the response

After weeks of research. I came up with the following code. I believe this is the bare minimum needed to make a secure connection with SSL to a web server.

#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>

#define APIKEY "YOUR_API_KEY"
#define HOST "YOUR_WEB_SERVER_URI"
#define PORT "443"

int main() {

    //
    //  Initialize the variables
    //
    BIO* bio;
    SSL* ssl;
    SSL_CTX* ctx;

    //
    //   Registers the SSL/TLS ciphers and digests.
    //
    //   Basically start the security layer.
    //
    SSL_library_init();

    //
    //  Creates a new SSL_CTX object as a framework to establish TLS/SSL
    //  or DTLS enabled connections
    //
    ctx = SSL_CTX_new(SSLv23_client_method());

    //
    //  -> Error check
    //
    if (ctx == NULL)
    {
        printf("Ctx is null\n");
    }

    //
    //   Creates a new BIO chain consisting of an SSL BIO
    //
    bio = BIO_new_ssl_connect(ctx);

    //
    //  Use the variable from the beginning of the file to create a 
    //  string that contains the URL to the site that you want to connect
    //  to while also specifying the port.
    //
    BIO_set_conn_hostname(bio, HOST ":" PORT);

    //
    //   Attempts to connect the supplied BIO
    //
    if(BIO_do_connect(bio) <= 0)
    {
        printf("Failed connection\n");
        return 1;
    }
    else
    {
        printf("Connected\n");
    }

    //
    //  The bare minimum to make a HTTP request.
    //
    char* write_buf = "POST / HTTP/1.1\r\n"
                      "Host: " HOST "\r\n"
                      "Authorization: Basic " APIKEY "\r\n"
                      "Connection: close\r\n"
                      "\r\n";

    //
    //   Attempts to write len bytes from buf to BIO
    //
    if(BIO_write(bio, write_buf, strlen(write_buf)) <= 0)
    {
        //
        //  Handle failed writes here
        //
        if(!BIO_should_retry(bio))
        {
            // Not worth implementing, but worth knowing.
        }

        //
        //  -> Let us know about the failed writes
        //
        printf("Failed write\n");
    }

    //
    //  Variables used to read the response from the server
    //
    int size;
    char buf[1024];

    //
    //  Read the response message
    //
    for(;;)
    {
        //
        //  Get chunks of the response 1023 at the time.
        //
        size = BIO_read(bio, buf, 1023);

        //
        //  If no more data, then exit the loop
        //
        if(size <= 0)
        {
            break;
        }

        //
        //  Terminate the string with a 0, to let know C when the string 
        //  ends.
        //
        buf[size] = 0;

        //
        //  ->  Print out the response
        //
        printf("%s", buf);
    }

    //
    //  Clean after ourselves
    //
    BIO_free_all(bio);
    SSL_CTX_free(ctx);

    return 0;
}

The code above will explain in details how to establish a TLS connection with a remote server.

Important note: this code doesn't check if the public key was signed by a valid authority. Meaning I don't use root certificates for validation. Don't forget to implement this check otherwise you won't know if you are connecting the right website

When it comes to the request itself. It is nothing more then writing the HTTP request by hand.

You can also find under this link an explanation how to instal openSSL in your system, and how to compile the code so it uses the secure library.

This project references NuGet package(s) that are missing on this computer

For me it worked as I just copied a .nuget folder from a working solution to the existing one, and referenced it's content!

How to check queue length in Python

Use queue.rear+1 to get the length of the queue

Why does an onclick property set with setAttribute fail to work in IE?

In some cases the examples listed here didn't work out for me in Internet Explorer.

Since you have to set the property with a method like this (without brackets)

HtmlElement.onclick = myMethod;

it won't work if you have to pass an object-name or even parameters. For the Internet Explorer you should create a new object in runtime:

HtmlElement.onclick = new Function('myMethod(' + someParameter + ')');

Works also on other browsers.

Is it possible to have multiple styles inside a TextView?

Try Html.fromHtml(), and mark up your text with bold and italic HTML tags e.g:

Spanned text = Html.fromHtml("This mixes <b>bold</b> and <i>italic</i> stuff");
textView.setText(text);

How to generate JAXB classes from XSD?

1) You can use standard java utility xjc - ([your java home dir]\bin\xjc.exe). But you need to create .bat (or .sh) script for using it.

e.g. generate.bat:

[your java home dir]\bin\xjc.exe %1 %2 %3

e.g. test-scheme.xsd:

<?xml version="1.0"?>
<xs:schema version="1.0"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified" 
           targetNamespace="http://myprojects.net/xsd/TestScheme"
           xmlns="http://myprojects.net/xsd/TestScheme">
    <xs:element name="employee" type="PersonInfoType"/>

    <xs:complexType name="PersonInfoType">
        <xs:sequence>
            <xs:element name="firstname" type="xs:string"/>
            <xs:element name="lastname" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

Run .bat file with parameters: generate.bat test-scheme.xsd -d [your src dir]

For more info use this documentation - http://docs.oracle.com/javaee/5/tutorial/doc/bnazg.html

and this - http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html

2) JAXB (xjc utility) is installed together with JDK6 by default.

List comprehension on a nested list?

Here is how you would do this with a nested list comprehension:

[[float(y) for y in x] for x in l]

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].

How to force file download with PHP

header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\""); 
echo readfile($url);

is correct

or better one for exe type of files

header("Location: $url");

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

This answer, but with storyboard support.

class SwipeNavigationController: UINavigationController {

    // MARK: - Lifecycle

    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

        self.setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.setup()
    }

    private func setup() {
        delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // This needs to be in here, not in init
        interactivePopGestureRecognizer?.delegate = self
    }

    deinit {
        delegate = nil
        interactivePopGestureRecognizer?.delegate = nil
    }

    // MARK: - Overrides

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        duringPushAnimation = true

        super.pushViewController(viewController, animated: animated)
    }

    // MARK: - Private Properties

    fileprivate var duringPushAnimation = false
}

My Application Could not open ServletContext resource

If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet constructor:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

Fix it by adding the context as the constructor arg:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

c# regex matches example

    public void match2()
    {
        string input = "%download%#893434";
        Regex word = new Regex(@"\d+");
        Match m = word.Match(input);
        Console.WriteLine(m.Value);
    }

Angular expression if array contains

Somewhere in your initialisation put this code.

Array.prototype.contains = function contains(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

Then, you can use it this way:

<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>

Change a column type from Date to DateTime during ROR migration

There's a change_column method, just execute it in your migration with datetime as a new type.

change_column(:my_table, :my_column, :my_new_type)

How can I get the domain name of my site within a Django template?

from django.contrib.sites.models import Site
if Site._meta.installed:
    site = Site.objects.get_current()
else:
    site = RequestSite(request)

How to read a line from the console in C?

As suggested, you can use getchar() to read from the console until an end-of-line or an EOF is returned, building your own buffer. Growing buffer dynamically can occur if you are unable to set a reasonable maximum line size.

You can use also use fgets as a safe way to obtain a line as a C null-terminated string:

#include <stdio.h>

char line[1024];  /* Generously large value for most situations */

char *eof;

line[0] = '\0'; /* Ensure empty line if no input delivered */
line[sizeof(line)-1] = ~'\0';  /* Ensure no false-null at end of buffer */

eof = fgets(line, sizeof(line), stdin);

If you have exhausted the console input or if the operation failed for some reason, eof == NULL is returned and the line buffer might be unchanged (which is why setting the first char to '\0' is handy).

fgets will not overfill line[] and it will ensure that there is a null after the last-accepted character on a successful return.

If end-of-line was reached, the character preceding the terminating '\0' will be a '\n'.

If there is no terminating '\n' before the ending '\0' it may be that there is more data or that the next request will report end-of-file. You'll have to do another fgets to determine which is which. (In this regard, looping with getchar() is easier.)

In the (updated) example code above, if line[sizeof(line)-1] == '\0' after successful fgets, you know that the buffer was filled completely. If that position is proceeded by a '\n' you know you were lucky. Otherwise, there is either more data or an end-of-file up ahead in stdin. (When the buffer is not filled completely, you could still be at an end-of-file and there also might not be a '\n' at the end of the current line. Since you have to scan the string to find and/or eliminate any '\n' before the end of the string (the first '\0' in the buffer), I am inclined to prefer using getchar() in the first place.)

Do what you need to do to deal with there still being more line than the amount you read as the first chunk. The examples of dynamically-growing a buffer can be made to work with either getchar or fgets. There are some tricky edge cases to watch out for (like remembering to have the next input start storing at the position of the '\0' that ended the previous input before the buffer was extended).

Using Selenium Web Driver to retrieve value of a HTML input

For python bindings it will be :

element.get_attribute('value')

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

This version allows you to have more than one case y or Y, n or N

  1. Optionally: Repeat the question until an approve question is provided

  2. Optionally: Ignore any other answer

  3. Optionally: Exit the terminal if you want

    confirm() {
        echo -n "Continue? y or n? "
        read REPLY
        case $REPLY in
        [Yy]) echo 'yup y' ;; # you can change what you do here for instance
        [Nn]) break ;;        # exit case statement gracefully
        # Here are a few optional options to choose between
        # Any other answer:
    
        # 1. Repeat the question
        *) confirm ;;
    
        # 2. ignore
        # *) ;;
    
        # 3. Exit terminal
        # *) exit ;;
    
        esac
        # REPLY=''
    }
    

Notice this too: On the last line of this function clear the REPLY variable. Otherwise if you echo $REPLY you will see it is still set until you open or close your terminal or set it again.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

What is the difference between a port and a socket?

Port and socket can be compared to the Bank Branch.

The building number of the "Bank" is analogous to IP address. A bank has got different sections like:

  1. Savings account department
  2. Personal loan department
  3. Home loan department
  4. Grievance department

So 1 (savings account department), 2 (personal loan department), 3 (home loan department) and 4 (grievance department) are ports.

Now let us say you go to open a savings account, you go to the bank (IP address), then you go to "savings account department" (port number 1), then you meet one of the employees working under "savings account department". Let us call him SAVINGACCOUNT_EMPLOYEE1 for opening account.

SAVINGACCOUNT_EMPLOYEE1 is your socket descriptor, so there may be SAVINGACCOUNT_EMPLOYEE1 to SAVINGACCOUNT_EMPLOYEEN. These are all socket descriptors.

Likewise, other departments will be having employess working under them and they are analogous to socket.

Transparent color of Bootstrap-3 Navbar

.navbar {
   background-color: transparent;
   background: transparent;
   border-color: transparent;
}

.navbar li { color: #000 } 

http://bootply.com/106969

Make Https call using HttpClient

When connect to https I got this error too, I add this line before HttpClient httpClient = new HttpClient(); and connect successfully:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

I know it from This Answer and Another Similar Anwser and the comment mentions:

This is a hack useful in development so putting a #if DEBUG #endif statement around it is the least you should do to make this safer and stop this ending up in production

Besides, I didn't try the method in Another Answer that use new X509Certificate() or new X509Certificate2() to make a Certificate, I'm not sure simply create by new() will work or not.

EDIT: Some References:

Create a Self-Signed Server Certificate in IIS 7

Import and Export SSL Certificates in IIS 7

Convert .pfx to .cer

Best practices for using ServerCertificateValidationCallback

I find value of Thumbprint is equal to x509certificate.GetCertHashString():

Retrieve the Thumbprint of a Certificate

SQL Group By with an Order By

In Oracle, something like this works nicely to separate your counting and ordering a little better. I'm not sure if it will work in MySql 4.

select 'Tag', counts.cnt
from
  (
  select count(*) as cnt, 'Tag'
  from 'images-tags'
  group by 'tag'
  ) counts
order by counts.cnt desc

Retrieve all values from HashMap keys in an ArrayList Java

Suppose I have Hashmap with key datatype as KeyDataType and value datatype as ValueDataType

HashMap<KeyDataType,ValueDataType> list;

Add all items you needed to it. Now you can retrive all hashmap keys to a list by.

KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);

So, now you got your all keys in an array mkeys[]

you can now retrieve any value by calling

 list.get(mkeys[position]);

find filenames NOT ending in specific extensions on Unix?

$ find . -name \*.exe -o -name \*.dll -o -print

The first two -name options have no -print option, so they skipped. Everything else is printed.

CSV in Python adding an extra carriage return, on Windows

In Python 3 (I haven't tried this in Python 2), you can also simply do

with open('output.csv','w',newline='') as f:
    writer=csv.writer(f)
    writer.writerow(mystuff)
    ...

as per documentation.

More on this in the doc's footnote:

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this

SELECT IF(
      count(*) > 15,
      'good',
      IF(
          count(*) > 10,
          'average',
          'poor'
        ) 
      ) as data_count 
      FROM companies

Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

if your certificate is not valid, it will have a red "x" and state the reason why. Generally the reason is "This certificate has expired" or "This certificate was signed by an unknown authority.

to solve this you need to do the following step.

  1. If your certificate has expired, renew it at the iPhone Portal, download it, and double-click it to add it to your Keychain.
  2. If it's "signed by an unknown authority", download the "Apple Worldwide Developer Relations" certificate from the Certificates section of the iPhone Developer portal and double-click it to add it to your Keychain.
  3. If your certificate was revoked, delete the certificate from your Keychain, then follow the "Obtaining your iPhone Development Certificate" or "Obtaining your iPhone Distribution Certificate" section in the iPhone Developer Program Portal User Guide to generate a new certificate.
  4. Make sure you create a backup of your private key. The steps for doing this are described in the iPhone Developer Program Portal User Guide, under "Saving your Private Key and Transferring to other Systems".
  5. If you have the iPhone Developer (or iPhone Distribution) certificate and its associated private key, the Apple WWDR Intermediate certificate is installed, and your certificate is valid, confirm that Online Certificate Status Protocol (OCSP) and Certificate Revocation List (CRL) are set to "Off" in Keychain Access > Preferences > Certificates.
  6. if you still getting problem then contact support apple community.

How can I get relative path of the folders in my android project?

You can check this sample code to understand how you can access the relative path using the java sample code

import java.io.File;

public class MainClass {

  public static void main(String[] args) {

    File relative = new File("html/javafaq/index.html");

    System.out.println("relative: ");
    System.out.println(relative.getName());
    System.out.println(relative.getPath());
  }
}

Here getPath will display the relative path of the file.

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

In Python 3, you can only print as:

print("STRING")

But in Python 2, the parentheses are not necessary.

How to install Android app on LG smart TV?

Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/

Have you enabled 'unknown sources' from security and restrictions settings?

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.