Programs & Examples On #Plumtree

Sending emails in Node.js?

node-email-templates is a much better option: https://github.com/niftylettuce/node-email-templates

it has support for windows as well

Declaring array of objects

You can use fill().

let arr = new Array(5).fill('lol');

let arr2 = new Array(5).fill({ test: 'a' });
// or if you want different objects
let arr3 = new Array(5).fill().map((_, i) => ({ id: i }));

Will create an array of 5 items. Then you can use forEach for example.

arr.forEach(str => console.log(str));

Note that when doing new Array(5) it's just an object with length 5 and the array is empty. When you use fill() you fill each individual spot with whatever you want.

Stretch child div height to fill parent that has dynamic height

Add the following CSS:

For the parent div:

style="display: flex;"

For child div:

style="align-items: stretch;"

Android : change button text and background color

add below line in styles.xml

<style name="AppTheme.Gray" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorButtonNormal">@color/colorGray</item>
    </style>

in button, add android:theme="@style/AppTheme.Gray", example:

<Button
            android:theme="@style/AppTheme.Gray"
            android:textColor="@color/colorWhite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@android:string/cancel"/>

How to pass parameters on onChange of html select

JavaScript Solution

<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
 document.getElementById("comboA").onchange = function(){
    var value = document.getElementById("comboA").value;
 };
</script>

or

<script>
 document.getElementById("comboA").onchange = function(evt){
    var value = evt.target.value;
 };
</script>

or

<script>
 document.getElementById("comboA").onchange = handleChange;

 function handleChange(evt){
    var value = evt.target.value;
 };
</script>

Calculating how many minutes there are between two times

Try this

DateTime startTime = varValue
DateTime endTime = varTime

TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes );

Edit: If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.

Convert PDF to clean SVG?

You can use Inkscape on the commandline only, without opening a GUI. Try this:

inkscape \
  --without-gui \
  --file=input.pdf \
  --export-plain-svg=output.svg 

For a complete list of all commandline options, run inkscape --help.

How to display custom view in ActionBar?

This is how it worked for me (from above answers it was showing both default title and my custom view also).

ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// actionBar.setCustomView(view); //last view item must set to android:layout_alignParentRight="true" if few views are there 
actionBar.setCustomView(view, layout); // layout param width=fill/match parent
actionBar.setDisplayShowCustomEnabled(true);//must other wise its not showing custom view.

What I noticed is that both setCustomView(view) and setCustomView(view,params) the view width=match/fill parent. setDisplayShowCustomEnabled (boolean showCustom)

Slide right to left?

$("#slide").animate({width:'toggle'},350);

Reference: https://api.jquery.com/animate/

This compilation unit is not on the build path of a Java project

Since you imported the project as a General Project, it does not have the java nature and that is the problem.

Add the below lines in the .project file of your workspace and refresh.

<natures>
      <nature>org.eclipse.jdt.core.javanature</nature>
</natures>

How to count objects in PowerShell?

Just use parenthesis and 'count'. This applies to Powershell v3

(get-alias).count

How do I create a GUI for a windows application using C++?

by far the best C++ GUI library out there is Qt, it's comprehensive, easy to learn, really fast, and multiplattform.

ah, it recently got a LGPL license, so now you can download it for free and include on commercial programs

How to flip background image using CSS?

I found I way to flip only the background not whole element after seeing a clue to flip in Alex's answer. Thanks alex for your answer

HTML

<div class="prev"><a href="">Previous</a></div>
<div class="next"><a href="">Next</a></div>

CSS

.next a, .prev a {
    width:200px;
    background:#fff
}
 .next {
    float:left
}
 .prev {
    float:right
}
 .prev a:before, .next a:before {
    content:"";
    width:16px;
    height:16px;
    margin:0 5px 0 0;
    background:url(http://i.stack.imgur.com/ah0iN.png) no-repeat 0 0;
    display:inline-block 
}
 .next a:before {
    margin:0 0 0 5px;
    transform:scaleX(-1);
}

See example here http://jsfiddle.net/qngrf/807/

C: printf a float value

Try these to clarify the issue of right alignment in float point printing

printf(" 4|%4.1lf\n", 8.9);
printf("04|%04.1lf\n", 8.9);

the output is

 4| 8.9
04|08.9

How to use table variable in a dynamic sql statement?

Here is an example of using a dynamic T-SQL query and then extracting the results should you have more than one column of returned values (notice the dynamic table name):

DECLARE 
@strSQLMain nvarchar(1000),
@recAPD_number_key char(10),    
@Census_sub_code varchar(1),
@recAPD_field_name char(100),
@recAPD_table_name char(100),
@NUMBER_KEY varchar(10),

if object_id('[Permits].[dbo].[myTempAPD_Txt]') is not null 

    DROP TABLE [Permits].[dbo].[myTempAPD_Txt]

CREATE TABLE [Permits].[dbo].[myTempAPD_Txt]
(
    [MyCol1] char(10) NULL,
    [MyCol2] char(1) NULL,

)   
-- an example of what @strSQLMain is : @strSQLMain = SELECT @recAPD_number_key = [NUMBER_KEY], @Census_sub_code=TEXT_029 FROM APD_TXT0 WHERE Number_Key = '01-7212' 
SET @strSQLMain = ('INSERT INTO myTempAPD_Txt SELECT [NUMBER_KEY], '+ rtrim(@recAPD_field_name) +' FROM '+ rtrim(@recAPD_table_name) + ' WHERE Number_Key = '''+ rtrim(@Number_Key) +'''')      
EXEC (@strSQLMain)  
SELECT @recAPD_number_key = MyCol1, @Census_sub_code = MyCol2 from [Permits].[dbo].[myTempAPD_Txt]

DROP TABLE [Permits].[dbo].[myTempAPD_Txt]  

How to break lines in PowerShell?

Try "`n" with double quotes. (not single quotes '`n' )

For a complete list of escaping characters see:

Help about_Escape_character

The code should be

$str += "`n"

How to check existence of user-define table type in SQL Server 2008?

You can use also system table_types view

IF EXISTS (SELECT *
           FROM   [sys].[table_types]
           WHERE  user_type_id = Type_id(N'[dbo].[UdTableType]'))
  BEGIN
      PRINT 'EXISTS'
  END 

C# Interfaces. Implicit implementation versus Explicit implementation

To quote Jeffrey Richter from CLR via C#
(EIMI means Explicit Interface Method Implementation)

It is critically important for you to understand some ramifications that exist when using EIMIs. And because of these ramifications, you should try to avoid EIMIs as much as possible. Fortunately, generic interfaces help you avoid EIMIs quite a bit. But there may still be times when you will need to use them (such as implementing two interface methods with the same name and signature). Here are the big problems with EIMIs:

  • There is no documentation explaining how a type specifically implements an EIMI method, and there is no Microsoft Visual Studio IntelliSense support.
  • Value type instances are boxed when cast to an interface.
  • An EIMI cannot be called by a derived type.

If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.

EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.

Android: checkbox listener

You could use this code.

public class MySampleActivity extends Activity {
    CheckBox cb1, cb2, cb3, cb4;
    LinearLayout l1, l2, l3, l4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cb1 = (CheckBox) findViewById(R.id.cb1);
        cb2 = (CheckBox) findViewById(R.id.cb2);
        cb3 = (CheckBox) findViewById(R.id.cb3);
        cb4 = (CheckBox) findViewById(R.id.cb4);
        l1 = (LinearLayout) findViewById(R.id.l1);
        l2 = (LinearLayout) findViewById(R.id.l2);
        l3 = (LinearLayout) findViewById(R.id.l3);
        l4 = (LinearLayout) findViewById(R.id.l4);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(1));
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(2));
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(3));
        cb1.setOnCheckedChangeListener(new MyCheckedChangeListener(4));
    }

    public class MyCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
        int position;

        public MyCheckedChangeListener(int position) {
            this.position = position;
        }

        private void changeVisibility(LinearLayout layout, boolean isChecked) {
            if (isChecked) {
                l1.setVisibility(View.VISIBLE);
            } else {
                l1.setVisibility(View.GONE);
            }

        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (position) {
                case 1:
                    changeVisibility(l1, isChecked);
                    break;
                case 2:
                    changeVisibility(l2, isChecked);
                    break;
                case 3:
                    changeVisibility(l3, isChecked);
                    break;
                case 4:
                    changeVisibility(l4, isChecked);
                    break;
            }
        }
    }
}

Dynamically add child components in React

You need to pass your components as children, like this:

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
    <App>
        <SampleComponent name="SomeName"/> 
    <App>, 
    document.body
);

And then append them in the component's body:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                {
                    this.props.children
                }
            </div>
        );
    }
});

You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:

var App = React.createClass({

    getInitialState: function(){
        return [
            {id:1,name:"Some Name"}
        ]
    },

    addChild: function() {
        // State change will cause component re-render
        this.setState(this.state.concat([
            {id:2,name:"Another Name"}
        ]))
    }

    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <button onClick={this.addChild}>Add component</button>
                {
                    this.state.map((item) => (
                        <SampleComponent key={item.id} name={item.name}/>
                    ))
                }
            </div>
        );
    }

});

Gulp command not found after install

In my case adding sudo before npm install solved gulp command not found problem

sudo npm install

What is the difference between Select and Project Operations

Select Operation : This operation is used to select rows from a table (relation) that specifies a given logic, which is called as a predicate. The predicate is a user defined condition to select rows of user's choice.

Project Operation : If the user is interested in selecting the values of a few attributes, rather than selection all attributes of the Table (Relation), then one should go for PROJECT Operation.

See more : Relational Algebra and its operations

How can I remove space (margin) above HTML header?

This css allowed chrome and firefox to render all other elements on my page normally and remove the margin above my h1 tag. Also, as a page is resized em can work better than px.

h1 {
  margin-top: -.3em;
  margin-bottom: 0em;
}

What is the difference between JDK and JRE?

If you want to run Java programs, but not develop them, download the Java Run-time Environment, or JRE. If you want to develop them, download the Java Development kit, or JDK

JDK

Let's called JDK is a kit, which include what are those things need to developed and run java applications.

JDK is given as development environment for building applications, component s and applets.

JRE

It contains everything you need to run Java applications in compiled form. You don't need any libraries and other stuffs. All things you need are compiled.

JRE is can not used for development, only used for run the applications.

How to push both key and value into an Array in Jquery

You might mean this:

var unEnumeratedArray = [];
var wtfObject = {
                 key    : 'val', 
                 0      : (undefined = 'Look, I\'m defined'),
                 'new'  : 'keyword', 
                 '{!}'  : 'use bracket syntax',
                 '        ': '8 spaces'
                };

for(var key in wtfObject){
    unEnumeratedArray[key] = wtfObject[key];
}
console.log('HAS KEYS PER VALUE NOW:', unEnumeratedArray, unEnumeratedArray[0], 
             unEnumeratedArray.key, unEnumeratedArray['new'], 
             unEnumeratedArray['{!}'], unEnumeratedArray['        ']);

You can set an enumerable for an Object like: ({})[0] = 'txt'; and you can set a key for an Array like: ([])['myKey'] = 'myVal';

Hope this helps :)

How do I get DOUBLE_MAX?

DBL_MAX is defined in <float.h>. Its availability in <limits.h> on unix is what is marked as "(LEGACY)".

(linking to the unix standard even though you have no unix tag since that's probably where you found the "LEGACY" notation, but much of what is shown there for float.h is also in the C standard back to C89)

GDB: break if variable equal value

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

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

then just run you code with your favourite debugger

$ gdb ./ex1

show me the code.

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

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

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

checking breakpoints

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

running the program

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

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

Convert generic list to dataset in C#

Have you tried binding the list to the datagridview directly? If not, try that first because it will save you lots of pain. If you have tried it already, please tell us what went wrong so we can better advise you. Data binding gives you different behaviour depending on what interfaces your data object implements. For example, if your data object only implements IEnumerable (e.g. List), you will get very basic one-way binding, but if it implements IBindingList as well (e.g. BindingList, DataView), then you get two-way binding.

How can I use the python HTMLParser library to extract data from a specific div tag?

class LinksParser(HTMLParser.HTMLParser):
  def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.recording = 0
    self.data = []

  def handle_starttag(self, tag, attributes):
    if tag != 'div':
      return
    if self.recording:
      self.recording += 1
      return
    for name, value in attributes:
      if name == 'id' and value == 'remository':
        break
    else:
      return
    self.recording = 1

  def handle_endtag(self, tag):
    if tag == 'div' and self.recording:
      self.recording -= 1

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

self.recording counts the number of nested div tags starting from a "triggering" one. When we're in the sub-tree rooted in a triggering tag, we accumulate the data in self.data.

The data at the end of the parse are left in self.data (a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.

The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above, 'div', 'id', and 'remository', instance attributes self.tag, self.attname and self.attvalue, set by __init__ from arguments passed to it -- I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).

MySQL: Quick breakdown of the types of joins

Full Outer join don't exist in mysql , you might need to use a combination of left and right join.

How to edit log message already committed in Subversion?

svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt

How to include a quote in a raw Python string

Python has more than one way to do strings. The following string syntax would allow you to use double quotes:

'''what"ever'''

Default SQL Server Port

The default port for SQL Server Database Engine is 1433.

And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.

How to make EditText not editable through XML in Android?

This combination worked for me:

<EditText ... >
    android:longClickable="false"
    android:cursorVisible="false"
    android:focusableInTouchMode="false"
</EditText>

POST string to ASP.NET Web Api application - returns null

i meet this problem, and find this article. http://www.jasonwatmore.com/post/2014/04/18/Post-a-simple-string-value-from-AngularJS-to-NET-Web-API.aspx

The solution I found was to simply wrap the string value in double quotes in your js post

works like a charm! FYI

The split() method in Java does not work on a dot (.)

The documentation on split() says:

Splits this string around matches of the given regular expression.

(Emphasis mine.)

A dot is a special character in regular expression syntax. Use Pattern.quote() on the parameter to split() if you want the split to be on a literal string pattern:

String[] words = temp.split(Pattern.quote("."));

mssql '5 (Access is denied.)' error during restoring database

Well, In my case the solution was quite simple and straight.

I had to change just the value of log On As value.

Steps to Resolve-

  1. Open Sql Server Configuration manager
  2. Right click on SQL Server (MSSQLSERVER)
  3. Go to Properties

enter image description here

  1. change log On As value to LocalSystem

enter image description here

Hoping this will help you too :)

HTTP POST using JSON in Java

You can use the following code with Apache HTTP:

String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));

response = client.execute(request);

Additionally you can create a json object and put in fields into the object like this

HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));

How to change a table name using an SQL query?

Syntex for latest MySQL versions has been changed.

So try RENAME command without SINGLE QUOTES in table names.

RENAME TABLE old_name_of_table TO new_name_of_table;

javascript: Disable Text Select

One might also use, works ok in all browsers, require javascript:

onselectstart = (e) => {e.preventDefault()}

Example:

_x000D_
_x000D_
onselectstart = (e) => {_x000D_
  e.preventDefault()_x000D_
  console.log("nope!")_x000D_
  }
_x000D_
Select me!
_x000D_
_x000D_
_x000D_


One other js alternative, by testing CSS supports, and disable userSelect, or MozUserSelect for Firefox.

_x000D_
_x000D_
let FF_x000D_
if (CSS.supports("( -moz-user-select: none )")){FF = 1} else {FF = 0}_x000D_
(FF===1) ? document.body.style.MozUserSelect="none" : document.body.style.userSelect="none"
_x000D_
Select me!
_x000D_
_x000D_
_x000D_


Pure css, same logic. Warning you will have to extend those rules to every browser, this can be verbose.

_x000D_
_x000D_
@supports (user-select:none) {_x000D_
  div {_x000D_
    user-select:none_x000D_
  }_x000D_
}_x000D_
_x000D_
@supports (-moz-user-select:none) {_x000D_
  div {_x000D_
    -moz-user-select:none_x000D_
  }_x000D_
}
_x000D_
<div>Select me!</div>
_x000D_
_x000D_
_x000D_

Is it necessary to use # for creating temp tables in SQL server?

The difference between this two tables ItemBack1 and #ItemBack1 is that the first on is persistent (permanent) where as the other is temporary.

Now if take a look at your question again

Is it necessary to Use # for creating temp table in sql server?

The answer is Yes, because without this preceding # the table will not be a temporary table, it will be independent of all sessions and scopes.

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

On windows Power Shell, you can use the following command:

New-Item <filename.extension>

or

New-Item <filename.extension> -type file

Note: New-Item can be replaced with its alias ni

How do I set vertical space between list items?

I would be inclined to this which has the virtue of IE8 support.

li{
    margin-top: 10px;
    border:1px solid grey;
}

li:first-child {
    margin-top:0;
}

JSFiddle

\r\n, \r and \n what is the difference between them?

All 3 of them represent the end of a line. But...

  • \r (Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line
  • \n (Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n moves to the beginning of the line.
  • \r\n (End Of Line) → a combination of \r and \n

How can you print a variable name in python?

If you are trying to do this, it means you are doing something wrong. Consider using a dict instead.

def show_val(vals, name):
    print "Name:", name, "val:", vals[name]

vals = {'a': 1, 'b': 2}
show_val(vals, 'b')

Output:

Name: b val: 2

A general tree implementation?

A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree.

class Node(object):
    def __init__(self, data):
        self.data = data
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)

Then interact:

>>> n = Node(5)
>>> p = Node(6)
>>> q = Node(7)
>>> n.add_child(p)
>>> n.add_child(q)
>>> n.children
[<__main__.Node object at 0x02877FF0>, <__main__.Node object at 0x02877F90>]
>>> for c in n.children:
...   print c.data
... 
6
7
>>> 

This is a very basic skeleton, not abstracted or anything. The actual code will depend on your specific needs - I'm just trying to show that this is very simple in Python.

How to get UTC value for SYSDATE on Oracle

select sys_extract_utc(systimestamp) from dual;

Won't work on Oracle 8, though.

Convert a number to 2 decimal places in Java

DecimalFormat df=new DecimalFormat("0.00");

Use this code to get exact two decimal points. Even if the value is 0.0 it will give u 0.00 as output.

Instead if you use:

DecimalFormat df=new DecimalFormat("#.00");  

It wont convert 0.2659 into 0.27. You will get an answer like .27.

Get an array of list element contents in jQuery

And in clean javascript:

var texts = [], lis = document.getElementsByTagName("li");
for(var i=0, im=lis.length; im>i; i++)
  texts.push(lis[i].firstChild.nodeValue);

alert(texts);

Ubuntu says "bash: ./program Permission denied"

Try this:

sudo chmod +x program_name
./program_name 

How to disable all <input > inside a form with jQuery?

In older versions you could use attr. As of jQuery 1.6 you should use prop instead:

$("#target :input").prop("disabled", true);

To disable all form elements inside 'target'. See :input:

Matches all input, textarea, select and button elements.

If you only want the <input> elements:

$("#target input").prop("disabled", true);

What is the difference between a data flow diagram and a flow chart?

A DFD shows how the data moves through a system, a flowchart is closer to the operations that system does.

In the classic make a cup of tea example, a DFD would show where the water, tea, milk, sugar were going, whereas the flowchart shows the process.

How to update gradle in android studio?

For those who still have this problem (for example to switch from 2.8.0 to 2.10.0), move to the file gradle-wrapper.properties and set distributionUrl like that.

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

I changed 2.8.0 to 2.10.0 and don't forget to Sync after

Creating a very simple 1 username/password login in php

Your code could look more like:

<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
  $validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
  if(!$validUser) $errorMsg = "Invalid username or password.";
  else $_SESSION["login"] = true;
}
if($validUser) {
   header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <title>Login</title>
</head>
<body>
  <form name="input" action="" method="post">
    <label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
    <label for="password">Password:</label><input type="password" value="" id="password" name="password" />
    <div class="error"><?= $errorMsg ?></div>
    <input type="submit" value="Home" name="sub" />
  </form>
</body>
</html>

Now, when the page is redirected based on the header('LOCATION:wherever.php), put session_start() at the top of the page and test to make sure $_SESSION['login'] === true. Remember that == would be true if $_SESSION['login'] == 1 as well. Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.

how to install gcc on windows 7 machine?

EDIT Since not so recently by now, MinGW-w64 has "absorbed" one of the toolchain building projects. The downloads can be found here. The installer should work, and allow you to pick a version that you need.

Note the Qt SDK comes with the same toolchain. So if you are developing in Qt and using the SDK, just use the toolchain it comes with.

Another alternative that has up to date toolchains comes from... harhar... a Microsoft developer, none other than STL (Stephan T. Lavavej, isn't that a spot-on name for the maintainer of MSVC++ Standard Library!). You can find it here. It includes Boost.

Another option which is highly useful if you care for prebuilt dependencies is MSYS2, which provides a Unix shell (a Cygwin fork modified to work better with Windows pathnames and such), also provides a GCC. It usually lags a bit behind, but that is compensated for by its good package management system and stability. They also provide a functional Clang with libc++ if you care for such thing.

I leave the below for reference, but I strongly suggest against using MinGW.org, due to limitations detailed below. TDM-GCC (the MinGW-w64 version) provides some hacks that you may find useful in your specific situation, although I recommend using vanilla GCC at all times for maximum compatibility.


GCC for Windows is provided by two projects currently. They both provide a very own implementation of the Windows SDK (headers and libraries) which is necessary because GCC does not work with Visual Studio files.

  1. The older mingw.org, which @Mat already pointed you to. They provide only a 32-bit compiler. See here for the downloads you need:

    • Binutils is the linker and resource compiler etc.
    • GCC is the compiler, and is split in core and language packages
    • GDB is the debugger.
    • runtime library is required only for mingw.org
    • You might need to download mingw32-make seperately.
    • For support, you can try (don't expect friendly replies) [email protected]

    Alternatively, download mingw-get and use that.

  2. The newer mingw-w64, which as the name predicts, also provides a 64-bit variant, and in the future hopefully some ARM support. I use it and built toolchains with their CRT. Personal and auto builds are found under "Toolchains targetting Win32/64" here. They also provide Linux to Windows cross-compilers. I suggest you try a personal build first, they are more complete. Try mine (rubenvb) for GCC 4.6 to 4.8, or use sezero's for GCC 4.4 and 4.5. Both of us provide 32-bit and 64-bit native toolchains. These packages include everything listed above. I currently recommend the "MinGW-Builds" builds, as these are currently sanctioned as "official builds", and come with an installer (see above).

    For support, send an email to [email protected] or post on the forum via sourceforge.net.

Both projects have their files listed on sourceforge, and all you have to do is either run the installer (in case of mingw.org) or download a suitable zipped package and extract it (in the case of mingw-w64).

There are a lot of "non-official" toolchain builders, one of the most popular is TDM-GCC. They may use patches that break binary compatibility with official/unpatched toolchains, so be careful using them. It's best to use the official releases.

Delete forked repo from GitHub

Deleting your forked repository will not affect the master(original) repository.

Like I have shown an example by deleting a forked repo

This is my forked repo (Image)

Deleting the forked repo

And no changes to the original repository.

The master repo is something like an original one.

Forking is same as creating a xerox copy of the original one. Even if you get your xeroxed paper damaged, will it be that the original document also gets damaged. Obviously No.

So its the same as that.

Hope this helps.

How to change the color of a SwitchCompat from AppCompat library

Ok, so I'm sorry but most of these answers are incomplete or have some minor bug in them. The very complete answer from @austyn-mahoney is correct and the source for this answer, but it's complicated and you probably just want to style a switch. 'Styling' controls across different versions of Android is an epic pain in the ass. After pulling my hair out for days on a project with very tight design constraints I finally broke down and wrote a test app and then really dug in and tested the various solutions out there for styling switches and check-boxes, since when a design has one it frequently has the other. Here's what I found...

First: You can't actually style either of them, but you can apply a theme to all of them, or just one of them.

Second: You can do it all from XML and you don't need a second values-v21/styles.xml.

Third: when it comes to switches you have two basic choices if you want to support older versions of Android (like I'm sure you do)...

  1. You can use a SwitchCompat and you will be able to make it look the same across platforms.
  2. You can use a Switch and you will be able to theme it with the rest of your theme, or just that particular switch and on older versions of Android you'll just see an unstyled older square switch.

Ok now for the simple reference code. Again if you create a simple Hello World! and drop this code in you can play to your hearts content. All of that is boiler plate here so I'm just going to include the XML for the activity and the style...

activity_main.xml...

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="'Styled' SwitchCompat" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_item"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:textOff="OFF"
        android:textOn="ON"
        app:switchTextAppearance="@style/BrandedSwitch.text"
        app:theme="@style/BrandedSwitch.control"
        app:showText="true" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themed SwitchCompat" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_item2"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themed Switch" />

    <Switch
        android:id="@+id/switch_item3"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:textOff="OFF"
        android:textOn="ON"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="'Styled' Switch" />

    <Switch
        android:id="@+id/switch_item4"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:textOff="OFF"
        android:textOn="ON"
        android:theme="@style/BrandedSwitch"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="'Styled' CheckBox" />

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:theme="@style/BrandedCheckBox"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themed CheckBox" />

    <CheckBox
        android:id="@+id/checkbox2"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"/>

</RelativeLayout>

styles.xml...

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#3F51B5</item>
    <item name="colorPrimaryDark">#303F9F</item>
    <item name="colorAccent">#FF4081</item>
</style>

<style name="BrandedSwitch.control" parent="Theme.AppCompat.Light">
    <!-- active thumb & track color (30% transparency) -->
    <item name="colorControlActivated">#e6e600</item>
    <item name="colorSwitchThumbNormal">#cc0000</item>
</style>

<style name="BrandedSwitch.text" parent="Theme.AppCompat.Light">
    <item name="android:textColor">#ffa000</item>
    <item name="android:textSize">9dp</item>
</style>

<style name="BrandedCheckBox" parent="AppTheme">
    <item name="colorAccent">#aaf000</item>
    <item name="colorControlNormal">#ff0000</item>
</style>

<style name="BrandedSwitch" parent="AppTheme">
    <item name="colorAccent">#39ac39</item>
</style>

I know, I know, you are too lazy to build this, you just want to get your code written and check it in so you can close this pain in the ass Android compatibility nightmare bug so that the designer on your team will finally be happy. I get it. Here's what it looks like when you run it...

API_21:

API 21

API_18:

API18

Passing a local variable from one function to another

Adding to @pranay-rana's list:

Third way is:

function passFromValue(){
    var x = 15;
    return x;  
}
function passToValue() {
    var y = passFromValue();
    console.log(y);//15
}
passToValue(); 

c# search string in txt file

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

How to use 'hover' in CSS

If you want the underline to be present while the mouse hovers over the link, then:

a:hover {text-decoration: underline; }

is sufficient, however you can also use a class-name of 'hover' if you wish, and the following would be equally applicable:

a.hover:hover {text-decoration: underline; }

Incidentally it may be worth pointing out that the class name of 'hover' doesn't really add anything to the element, as the psuedo-element of a:hover does the same thing as that of a.hover:hover. Unless it's just a demonstration of using a class-name.

C# Switch-case string starting with

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

Getting scroll bar width using JavaScript

// offsetWidth includes width of scroll bar and clientWidth doesn't. As rule, it equals 14-18px. so:

 var scrollBarWidth = element.offsetWidth - element.clientWidth;

Convert array of JSON object strings to array of JS objects

If you have a JS array of JSON objects:

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');

See the speed tests for browser comparisons.


If you have a single JSON string representing an array of objects:

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = JSON.parse(s);

If you have an array of objects:

// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];

…and you want JSON representation for it, then:

// JSON string representing an array of objects
var json = JSON.stringify(s);

…or if you want a JavaScript array of JSON strings, then:

// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);

// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

you can try something like this, or just copy and past below piece.

boolean exception = true;
Charset charset = Charset.defaultCharset(); //Try the default one first.        
int index = 0;

while(exception) {
    try {
        lines = Files.readAllLines(f.toPath(),charset);
          for (String line: lines) {
              line= line.trim();
              if(line.contains(keyword))
                  values.add(line);
              }           
        //No exception, just returns
        exception = false; 
    } catch (IOException e) {
        exception = true;
        //Try the next charset
        if(index<Charset.availableCharsets().values().size())
            charset = (Charset) Charset.availableCharsets().values().toArray()[index];
        index ++;
    }
}

java.io.FileNotFoundException: the system cannot find the file specified

Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:

import java.io.File;
import java.util.*;

public class Hangman1 {

    public static void main(String[] args) throws Exception {
        File myFile = new File("word.txt");
        System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());

        Scanner input = new Scanner(myFile);
        String in = "";
        in = input.nextLine();
    }

}

This code should print the folder where it is looking for. Place the file there and you'll be good to go.

How can I access global variable inside class in Python

You need to move the global declaration inside your function:

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print(g_c)

The statement tells the Python compiler that any assignments (and other binding actions) to that name are to alter the value in the global namespace; the default is to put any name that is being assigned to anywhere in a function, in the local namespace. The statement only applies to the current scope.

Since you are never assigning to g_c in the class body, putting the statement there has no effect. The global statement only ever applies to the scope it is used in, never to any nested scopes. See the global statement documentation, which opens with:

The global statement is a declaration which holds for the entire current code block.

Nested functions and classes are not part of the current code block.

I'll insert the obligatory warning against using globals to share changing state here: don't do it, this makes it harder to reason about the state of your code, harder to test, harder to refactor, etc. If you must share a changing singleton state (one value in the whole program) then at least use a class attribute:

class TestClass():
    g_c = 0

    def run(self):
        for i in range(10):
            TestClass.g_c = 1
            print(TestClass.g_c)  # or print(self.g_c)

t = TestClass()
t.run()

print(TestClass.g_c)

Note how we can still access the same value from the outside, namespaced to the TestClass namespace.

Can I set a TTL for @Cacheable

See http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#cache-specific-config:

How can I set the TTL/TTI/Eviction policy/XXX feature?

Directly through your cache provider. The cache abstraction is... well, an abstraction not a cache implementation

So, if you use EHCache, use EHCache's configuration to configure the TTL.

You could also use Guava's CacheBuilder to build a cache, and pass this cache's ConcurrentMap view to the setStore method of the ConcurrentMapCacheFactoryBean.

A cycle was detected in the build path of project xxx - Build Path Problem

I have this problem,too.I just disable Workspace resolution,and then all was right.enter image description here

Java Date - Insert into database

pst.setDate(6, new java.sql.Date(txtDate.getDate().getTime()));

this is the code I used to save date into the database using jdbc works fine for me

  • pst is a variable for preparedstatement
  • txtdate is the name for the JDateChooser

How can I get the length of text entered in a textbox using jQuery?

You need to only grab the element with an appropriate jQuery selector and then the .val() method to get the string contained in the input textbox and then call the .length on that string.

$('input:text').val().length

However, be warned that if the selector matches multiple inputs, .val() will only return the value of the first textbox. You can also change the selector to get a more specific element but keep the :text to ensure it's an input textbox.

On another note, to get the length of a string contained in another, non-input element, you can use the .text() function to get the string and then use .length on that string to find its length.

How to keep the spaces at the end and/or at the beginning of a String?

There is possible to space with different widths:

<string name="space_demo">|&#x20;|&#x2009;|&#x200A;||</string>

| SPACE | THIN SPACE | HAIR SPACE | no space |

Visualisation:

enter image description here

How to set menu to Toolbar in Android

Also you need this, to implement some action to every options of menu.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_help:
            Toast.makeText(this, "This is teh option help", Toast.LENGTH_LONG).show();
            break;
        default:
            break;
    }
    return true;
}

Show Youtube video source into HTML5 video tag?

I have created a realtively small (4.89 KB) javascript library for this exact functionality.

Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/

It's as simple as:

<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>

<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>

Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/

What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=. It decodes the response which includes streaming information we can use to add a source to the <video> tag.

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Custom fonts and XML layouts (Android)

You can't extend TextView to create a widget or use one in a widgets layout: http://developer.android.com/guide/topics/appwidgets/index.html

How can I perform a short delay in C# without using sleep?

You can probably use timers : http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

Timers can provide you a precision up to 1 millisecond. Depending on the tick interval an event will be generated. Do your stuff inside the tick event.

Convert String to Type in C#

use following LoadType method to use System.Reflection to load all registered(GAC) and referenced assemblies and check for typeName

public Type[] LoadType(string typeName)
{
    return LoadType(typeName, true);
}

public Type[] LoadType(string typeName, bool referenced)
{
    return LoadType(typeName, referenced, true);
}

private Type[] LoadType(string typeName, bool referenced, bool gac)
{
    //check for problematic work
    if (string.IsNullOrEmpty(typeName) || !referenced && !gac)
        return new Type[] { };

    Assembly currentAssembly = Assembly.GetExecutingAssembly();

    List<string> assemblyFullnames = new List<string>();
    List<Type> types = new List<Type>();

    if (referenced)
    {            //Check refrenced assemblies
        foreach (AssemblyName assemblyName in currentAssembly.GetReferencedAssemblies())
        {
            //Load method resolve refrenced loaded assembly
            Assembly assembly = Assembly.Load(assemblyName.FullName);

            //Check if type is exists in assembly
            var type = assembly.GetType(typeName, false, true);

            if (type != null && !assemblyFullnames.Contains(assembly.FullName))
            {
                types.Add(type);
                assemblyFullnames.Add(assembly.FullName);
            }
        }
    }

    if (gac)
    {
        //GAC files
        string gacPath = Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\assembly";
        var files = GetGlobalAssemblyCacheFiles(gacPath);
        foreach (string file in files)
        {
            try
            {
                //reflection only
                Assembly assembly = Assembly.ReflectionOnlyLoadFrom(file);

                //Check if type is exists in assembly
                var type = assembly.GetType(typeName, false, true);

                if (type != null && !assemblyFullnames.Contains(assembly.FullName))
                {
                    types.Add(type);
                    assemblyFullnames.Add(assembly.FullName);
                }
            }
            catch
            {
                //your custom handling
            }
        }
    }

    return types.ToArray();
}

public static string[] GetGlobalAssemblyCacheFiles(string path)
{
    List<string> files = new List<string>();

    DirectoryInfo di = new DirectoryInfo(path);

    foreach (FileInfo fi in di.GetFiles("*.dll"))
    {
        files.Add(fi.FullName);
    }

    foreach (DirectoryInfo diChild in di.GetDirectories())
    {
        var files2 = GetGlobalAssemblyCacheFiles(diChild.FullName);
        files.AddRange(files2);
    }

    return files.ToArray();
}

how to get list of port which are in use on the server

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.

http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx

onclick or inline script isn't working in extension

Reason

This does not work, because Chrome forbids any kind of inline code in extensions via Content Security Policy.

Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

How to detect

If this is indeed the problem, Chrome would produce the following error in the console:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

To access a popup's JavaScript console (which is useful for debug in general), right-click your extension's button and select "Inspect popup" from the context menu.

More information on debugging a popup is available here.

How to fix

One needs to remove all inline JavaScript. There is a guide in Chrome documentation.

Suppose the original looks like:

<a onclick="handler()">Click this</a> <!-- Bad -->

One needs to remove the onclick attribute and give the element a unique id:

<a id="click-this">Click this</a> <!-- Fixed -->

And then attach the listener from a script (which must be in a .js file, suppose popup.js):

// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("click-this").addEventListener("click", handler);
});

// The handler also must go in a .js file
function handler() {
  /* ... */
}

Note the wrapping in a DOMContentLoaded event. This ensures that the element exists at the time of execution. Now add the script tag, for instance in the <head> of the document:

<script src="popup.js"></script>

Alternative if you're using jQuery:

// jQuery
$(document).ready(function() {
  $("#click-this").click(handler);
});

Relaxing the policy

Q: The error mentions ways to allow inline code. I don't want to / can't change my code, how do I enable inline scripts?

A: Despite what the error says, you cannot enable inline script:

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.

Update: Since Chrome 46, it's possible to whitelist specific inline code blocks:

As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for <script> elements for an example.

However, I do not readily see a reason to use this, and it will not enable inline attributes like onclick="code".

How to Create Multiple Where Clause Query Using Laravel Eloquent?

You may use in several ways,

$results = User::where([
    ['column_name1', '=', $value1],
    ['column_name2', '<', $value2],
    ['column_name3', '>', $value3]
])->get();

You can also use like this,

$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<',  $value2);
$results = $results->where('column3','>',  $value3);
$results = $results->get();

How to load CSS Asynchronously

If you have a strict content security policy that doesn't allow @vladimir-salguero's answer, you can use this (please make note of the script nonce):

<script nonce="(your nonce)" async>
$(document).ready(function() {
    $('link[media="none"]').each(function(a, t) {
        var n = $(this).attr("data-async"),
            i = $(this);
        void 0 !== n && !1 !== n && ("true" == n || n) && i.attr("media", "all")
    })
});
</script>

Just add the following to your stylesheet reference: media="none" data-async="true". Here's an example:

<link rel="stylesheet" href="../path/script.js" media="none" data-async="true" />

Example for jQuery:

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" media="none" data-async="true" crossorigin="anonymous" /><noscript><link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" /></noscript>

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

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

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

        <p>Please log in</p>

    </div>
</div>

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

How do I resolve a TesseractNotFoundError?

I face this same issue. I just use this command that will help me.

sudo apt install tesseract-ocr

Note that this will only work on Ubuntu.
sudo is a Unix exclusive command (Linux, Mac, Rasbian, etc.) while apt is Ubuntu specific.

jQuery textbox change event doesn't fire until textbox loses focus?

Try the below Code:

$("#textbox").on('change keypress paste', function() {
  console.log("Handler for .keypress() called.");
});

Bootstrap - 5 column layout

The best way to honestly do this is to change the number of columns you have instead of trying to bodge 5 into 12.

The best number you could probably use is 20 as it's divisble by 2, 4 & 5.

So in your variables.less look for: @grid-columns: 12 and change this to 20.

Then change your html to:

      <div class="row">
        <div class="col-xs-20">
          <div class="col-xs-4" id="p1">One</div>
          <div class="col-xs-4" id="p2">Two</div>
          <div class="col-xs-4" id="p3">Three</div>
          <div class="col-xs-4" id="p4">Four</div>
          <div class="col-xs-4" id="p5">Five</div>
        </div>
        <!-- //col-lg-20 -->
      </div>

I'd personally use display: flex for this as bootstrap isn't designed greatly for a 5 column split.

Android: Scale a Drawable or background image?

You can use one of following:

android:gravity="fill_horizontal|clip_vertical"

Or

android:gravity="fill_vertical|clip_horizontal"

What is the most efficient way to get first and last line of a text file?

Here's a modified version of SilentGhost's answer that will do what you want.

with open(fname, 'rb') as fh:
    first = next(fh)
    offs = -100
    while True:
        fh.seek(offs, 2)
        lines = fh.readlines()
        if len(lines)>1:
            last = lines[-1]
            break
        offs *= 2
    print first
    print last

No need for an upper bound for line length here.

Instagram API - How can I retrieve the list of people a user is following on Instagram

You can use Phantombuster. Instagram has set some rate limit, so you will have to use either multiple accounts or wait for 15 minutes for the next run.

Does GPS require Internet?

There are two issues:

  1. Getting the current coordinates (longitude, latitude, perhaps altitude) based on some external signals received by your device, and
  2. Deriving a human-readable position (address) from the coordinates.

To get the coordinates you don't need the Internet. GPS is satellite-based. But to derive street/city information from the coordinates, you'd need either to implement the map and the corresponding algorithms yourself on the device (a lot of work!) or to rely on proven services, e.g. by Google, in which case you'd need an Internet connection.

As of recently, Google allows for caching the maps, which would at least allow you to show your current position on the map even without a data connection, provided, you had cached the map in advance, when you could access the Internet.

MySQL count occurrences greater than 2

SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1

"undefined" function declared in another file?

Please read "How to Write Go Code".

Use go build or go install within the package directory, or supply an import path for the package. Do not use file arguments for build or install.

While you can use file arguments for go run, you should build a package instead, usually with go run ., though you should almost always use go install, or go build.

I want to show all tables that have specified column name

Pretty simple on a per database level

Use DatabaseName
Select * From INFORMATION_SCHEMA.COLUMNS Where column_name = 'ColName'

Requery a subform from another form?

I tried several solutions above, but none solved my problem. Solution to refresh a subform in a form after saving data to database:

Me.subformname.Requery

It worked fine for me. Good luck.

CORS with POSTMAN

If you use a website and you fill out a form to submit information (your social security number for example) you want to be sure that the information is being sent to the site you think it's being sent to. So browsers were built to say, by default, 'Do not send information to a domain other than the domain being visited).

Eventually that became too limiting but the default idea still remains in browsers. Don't let the web page send information to a different domain. But this is all browser checking. Chrome and firefox, etc have built in code that says 'before send this request, we're going to check that the destination matches the page being visited'.

Postman (or CURL on the cmd line) doesn't have those built in checks. You're manually interacting with a site so you have full control over what you're sending.

How do I replace a character in a string in Java?

The simple answer is:

token = token.replace("&", "&amp;");

Despite the name as compared to replaceAll, replace does do a replaceAll, it just doesn't use a regular expression, which seems to be in order here (both from a performance and a good practice perspective - don't use regular expressions by accident as they have special character requirements which you won't be paying attention to).

Sean Bright's answer is probably as good as is worth thinking about from a performance perspective absent some further target requirement on performance and performance testing, if you already know this code is a hot spot for performance, if that is where your question is coming from. It certainly doesn't deserve the downvotes. Just use StringBuilder instead of StringBuffer unless you need the synchronization.

That being said, there is a somewhat deeper potential problem here. Escaping characters is a known problem which lots of libraries out there address. You may want to consider wrapping the data in a CDATA section in the XML, or you may prefer to use an XML library (including the one that comes with the JDK now) to actually generate the XML properly (so that it will handle the encoding).

Apache also has an escaping library as part of Commons Lang.

jquery fill dropdown with json data

This should do the trick:

$($.parseJSON(data.msg)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');

Here's the distinction between ajax and getJSON (from the jQuery documentation):

[getJSON] is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:

{
    "msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}

...So that msg property needed to be parsed manually using $.parseJSON().

JQuery get all elements by class name

With the code in the question, you're only dealing interacting with the first of the four entries returned by that selector.

Code below as a fiddle: https://jsfiddle.net/c4nhpqgb/

I want to be overly clear that you have four items that matched that selector, so you need to deal with each explicitly. Using eq() is a little more explicit making this point than the answers using map, though map or each is what you'd probably use "in real life" (jquery docs for eq here).

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
    </head>

    <body>
        <div class="mbox">Block One</div>
        <div class="mbox">Block Two</div>
        <div class="mbox">Block Three</div>
        <div class="mbox">Block Four</div>

        <div id="outige"></div>
        <script>
            // using the $ prefix to use the "jQuery wrapped var" convention
            var i, $mvar = $('.mbox');

            // convenience method to display unprocessed html on the same page
            function logit( string )
            {
                var text = document.createTextNode( string );
                $('#outige').append(text);
                $('#outige').append("<br>");
            }

            logit($mvar.length);

            for (i=0; i<$mvar.length; i++)    {
                logit($mvar.eq(i).html());
            }
        </script>
    </body>

</html>

Output from logit calls (after the initial four div's display):

4
Block One
Block Two
Block Three
Block Four

TypeError: ObjectId('') is not JSON serializable

SOLUTION for: mongoengine + marshmallow

If you use mongoengine and marshamallow then this solution might be applicable for you.

Basically, I imported String field from marshmallow, and I overwritten default Schema id to be String encoded.

from marshmallow import Schema
from marshmallow.fields import String

class FrontendUserSchema(Schema):

    id = String()

    class Meta:
        fields = ("id", "email")

How to prevent custom views from losing state across screen orientation changes

I think this is a much simpler version. Bundle is a built-in type which implements Parcelable

public class CustomView extends View
{
  private int stuff; // stuff

  @Override
  public Parcelable onSaveInstanceState()
  {
    Bundle bundle = new Bundle();
    bundle.putParcelable("superState", super.onSaveInstanceState());
    bundle.putInt("stuff", this.stuff); // ... save stuff 
    return bundle;
  }

  @Override
  public void onRestoreInstanceState(Parcelable state)
  {
    if (state instanceof Bundle) // implicit null check
    {
      Bundle bundle = (Bundle) state;
      this.stuff = bundle.getInt("stuff"); // ... load stuff
      state = bundle.getParcelable("superState");
    }
    super.onRestoreInstanceState(state);
  }
}

How to create a directory if it doesn't exist using Node.js?

Using async / await:

const mkdirP = async (directory) => {
  try {
    return await fs.mkdirAsync(directory);
  } catch (error) {
    if (error.code != 'EEXIST') {
      throw e;
    }
  }
};

You will need to promisify fs:

import nodeFs from 'fs';
import bluebird from 'bluebird';

const fs = bluebird.promisifyAll(nodeFs);

PHPExcel how to set cell value dynamically

I don't have much experience working with php but from a logic standpoint this is what I would do.

  1. Loop through your result set from MySQL
  2. In Excel you should already know what A,B,C should be because those are the columns and you know how many columns you are returning.
  3. The row number can just be incremented with each time through the loop.

Below is some pseudocode illustrating this technique:

    for (int i = 0; i < MySQLResults.count; i++){
         $objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name); 
        // Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
         $objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
         $objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
    }

Difference between signed / unsigned char

Representation is the same, the meaning is different. e.g, 0xFF, it both represented as "FF". When it is treated as "char", it is negative number -1; but it is 255 as unsigned. When it comes to bit shifting, it is a big difference since the sign bit is not shifted. e.g, if you shift 255 right 1 bit, it will get 127; shifting "-1" right will be no effect.

Removing "bullets" from unordered list <ul>

Try this it works

<ul class="sub-menu" type="none">
           <li class="sub-menu-list" ng-repeat="menu in list.components">
               <a class="sub-menu-link">
                   {{ menu.component }}
               </a>
           </li>
        </ul>

How do I select text nodes with jQuery?

For me, plain old .contents() appeared to work to return the text nodes, just have to be careful with your selectors so that you know they will be text nodes.

For example, this wrapped all the text content of the TDs in my table with pre tags and had no problems.

jQuery("#resultTable td").content().wrap("<pre/>")

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

Why is NULL undeclared?

NULL isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef> or #include <stddef.h> should be sufficient.

The definition of NULL is guaranteed to be available if you include cstddef or stddef.h. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

You can use navigator.mimeTypes.

if (navigator.mimeTypes ["application/x-shockwave-flash"] == undefined)
    $("#someDiv").show ();

What's the proper way to compare a String to an enum value?

You can compare a string to an enum item as follow,

public class Main {

    enum IaaSProvider{
        aws,
        microsoft,
        google
    }

    public static void main(String[] args){

        IaaSProvider iaaSProvider = IaaSProvider.google;

        if("google".equals(iaaSProvider.toString())){
            System.out.println("The provider is google");
        }

    }
}

Using number_format method in Laravel

If you are using Eloquent the best solution is:

public function getFormattedPriceAttribute()
{
    return number_format($this->attributes['price'], 2);
}

So now you must append formattedPrice in your model and you can use both, price (at its original state) and formattedPrice.

Get querystring from URL using jQuery

We do it this way...

String.prototype.getValueByKey = function (k) {
    var p = new RegExp('\\b' + k + '\\b', 'gi');
    return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p) + k.length + 1).substr(0, this.substr(this.search(p) + k.length + 1).search(/(&|;|$)/))) : "";
};

How can I return to a parent activity correctly?

Try this solution use NavUtils.navigateUpFromSameTask(this); in the child activity: https://stackoverflow.com/a/49980835/7308789

@HostBinding and @HostListener: what do they do and what are they for?

A quick tip that helps me remember what they do -

HostBinding('value') myValue; is exactly the same as [value]="myValue"

And

HostListener('click') myClick(){ } is exactly the same as (click)="myClick()"


HostBinding and HostListener are written in directives and the other ones (...) and [..] are written inside templates (of components).

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

 $("#test").keyup(
     function () {
         this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();
     }
 );

React Hooks useState() with Object

I think best solution is Immer. It allows you to update object like you are directly modifying fields (masterField.fieldOne.fieldx = 'abc'). But it will not change actual object of course. It collects all updates on a draft object and gives you a final object at the end which you can use to replace original object.

How to list files in a directory in a C program?

Here is a complete program how to recursively list folder's contents:

#include <dirent.h> 
#include <stdio.h> 
#include <string.h>

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

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

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

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

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Get Value From Select Option in Angular 4

You just need to put [(ngModel)] on your select element:

<select class="form-control col-lg-8" #corporation required [(ngModel)]="selectedValue">

What is "Advanced" SQL?

At my previous job, we had a technical test which all candidates were asked to sit. 10ish questions, took about an hour. In all honesty though, 90% of failures could be screened out because they couldn't write an INNER JOIN statement. Not even an outer.

I'd consider that a prerequisite for any job description involving SQL and would leave well alone until that was mastered. From there though, talk to them - any further info on what they're actually looking for will, worst case scenario, be a useful list of things to learn as part of your professional development.

Get type of a generic parameter in Java with reflection

You cannot get a generic parameter from a variable. But you can from a method or field declaration:

Method method = getClass().getDeclaredMethod("chill", List.class);
Type[] params = method.getGenericParameterTypes();
ParameterizedType firstParam = (ParameterizedType) params[0];
Type[] paramsOfFirstGeneric = firstParam.getActualTypeArguments();

afxwin.h file is missing in VC++ Express Edition

Including the header afxwin.h signalizes use of MFC. The following instructions (based on those on CodeProject.com) could help to get MFC code compiling:

  1. Download and install the Windows Driver Kit.

  2. Select menu Tools > Options… > Projects and Solutions > VC++ Directories.

  3. In the drop-down menu Show directories for select Include files.

  4. Add the following paths (replace $(WDK_directory) with the directory where you installed Windows Driver Kit in the first step):

    $(WDK_directory)\inc\mfc42
    $(WDK_directory)\inc\atl30
    

  5. In the drop-down menu Show directories for select Library files and add (replace $(WDK_directory) like before):

    $(WDK_directory)\lib\mfc\i386
    $(WDK_directory)\lib\atl\i386
    

  6. In the $(WDK_directory)\inc\mfc42\afxwin.inl file, edit the following lines (starting from 1033):

    _AFXWIN_INLINE CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    to

    _AFXWIN_INLINE BOOL CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE BOOL CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    In other words, add BOOL after _AFXWIN_INLINE.

Cannot find module cv2 when using OpenCV

I had the same problem, just couldn't figure it out with opencv2 and opencv3 installed into /opt/opencv and opencv3 respectively. Turned out that bloody anaconda install of opencv in my home directory was first on path and mangled opencv. Removed it and started using /opt/opencv3/lib as defined in /etc/ld.so.conf.d/opencv.conf. Worked perfectly first go. Do you have anaconda installed? Could be the issue.

How to parse JSON in Java

First you need to select an implementation library to do that.

The Java API for JSON Processing (JSR 353) provides portable APIs to parse, generate, transform, and query JSON using object model and streaming APIs.

The reference implementation is here: https://jsonp.java.net/

Here you can find a list of implementations of JSR 353:

What are the API that does implement JSR-353 (JSON)

And to help you decide... I found this article as well:

http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/

If you go for Jackson, here is a good article about conversion between JSON to/from Java using Jackson: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

Hope it helps!

How to clone git repository with specific revision/changeset?

Just to sum things up (git v. 1.7.2.1):

  1. do a regular git clone where you want the repo (gets everything to date — I know, not what is wanted, we're getting there)
  2. git checkout <sha1 rev> of the rev you want
  3. git reset --hard
  4. git checkout -b master

How to determine if binary tree is balanced?

Bonus exercise response. The simple solution. Obviously in a real implementation one might wrap this or something to avoid requiring the user to include height in their response.

IsHeightBalanced(tree, out height)
    if (tree is empty)
        height = 0
        return true
    balance = IsHeightBalanced(tree.left, heightleft) and IsHeightBalanced(tree.right, heightright)
    height = max(heightleft, heightright)+1
    return balance and abs(heightleft - heightright) <= 1     

Create a Maven project in Eclipse complains "Could not resolve archetype"

i found the easiest way was to just remove/delete the .m2 folder and recreate it, putting back your settings.xml configuration details(if applicable).

javascript compare strings without being case sensitive

You can also use string.match().

var string1 = "aBc";
var match = string1.match(/AbC/i);

if(match) {
}

To find first N prime numbers in python

Hi! I am very new to coding, just started 4 days back. I wrote a code to give back the first 1000 prime numbers including 1. Have a look

n=1
c=0
while n>0:
   for i in range(2,n):
      if n%i == 0:
         break
   else:
      print(n,'is a prime')
      c=c+1
   n=n+1
   if c==1000:
      break

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

Select records from NOW() -1 Day

Be aware that the result may be slightly different than you expect.

NOW() returns a DATETIME.

And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.

So if your script is cron'd to run at 03:00, it will miss the first three hours of records from the 'oldest' day.

To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get back to the beginning of the previous day regardless of when the script is run.

How to send only one UDP packet with netcat?

I had the same problem but I use -w 0 option to send only one packet and quit. You should use this command :

echo -n "hello" | nc -4u -w0 localhost 8000

How to embed YouTube videos in PHP?

This YouTube embed generator solve all my problems with video embedding.

Setting public class variables

For overloading you'd need a subclass:

class ChildTestclass extends Testclass {
    public $testvar = "newVal";
}

$obj = new ChildTestclass();
$obj->dosomething();

This code would echo newVal.

How to insert data into SQL Server

I think you lack to pass Connection object to your command object. and it is much better if you will use command and parameters for that.

using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;            // <== lacking
        command.CommandType = CommandType.Text;
        command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
        command.Parameters.AddWithValue("@staffName", name);
        command.Parameters.AddWithValue("@userID", userId);
        command.Parameters.AddWithValue("@idDepart", idDepart);

        try
        {
            connection.Open();
            int recordsAffected = command.ExecuteNonQuery();
        }
        catch(SqlException)
        {
            // error here
        }
        finally
        {
            connection.Close();
        }
    }
}

How to find whether MySQL is installed in Red Hat?

rpmquery <package Name> By this command you can check which package is installed.

For Example: rpmquery mysql

python-pandas and databases like mysql

For Postgres users

import psycopg2
import pandas as pd

conn = psycopg2.connect("database='datawarehouse' user='user1' host='localhost' password='uberdba'")

customers = 'select * from customers'

customers_df = pd.read_sql(customers,conn)

customers_df

Is there a decent wait function in C++?

Well, this is an old post but I will just contribute to the question -- someone may find it useful later:

adding 'cin.get();' function just before the return of the main() seems to always stop the program from exiting before printing the results: see sample code below:

int main(){ string fname, lname;

  //ask user to enter name first and last name
  cout << "Please enter your first name: ";
  cin >> fname;

  cout << "Please enter your last name: ";
  cin >> lname;     
  cout << "\n\n\n\nyour first name is: " << fname << "\nyour last name is: " 
  << lname <<endl;

  //stop program from exiting before printing results on the screen
  cin.get();
  return 0;

}

How to sort a collection by date in MongoDB?

db.getCollection('').find({}).sort({_id:-1}) 

This will sort your collection in descending order based on the date of insertion

Refresh Page and Keep Scroll Position

If you don't want to use local storage then you could attach the y position of the page to the url and grab it with js on load and set the page offset to the get param you passed in, i.e.:

//code to refresh the page
var page_y = $( document ).scrollTop();
window.location.href = window.location.href + '?page_y=' + page_y;


//code to handle setting page offset on load
$(function() {
    if ( window.location.href.indexOf( 'page_y' ) != -1 ) {
        //gets the number from end of url
        var match = window.location.href.split('?')[1].match( /\d+$/ );
        var page_y = match[0];

        //sets the page offset 
        $( 'html, body' ).scrollTop( page_y );
    }
});

Single Line Nested For Loops

First of all, your first code doesn't use a for loop per se, but a list comprehension.

  1. Would be equivalent to

    for j in range(0, width): for i in range(0, height): m[i][j]

  2. Much the same way, it generally nests like for loops, right to left. But list comprehension syntax is more complex.

  3. I'm not sure what this question is asking


  1. Any iterable object that yields iterable objects that yield exactly two objects (what a mouthful - i.e [(1,2),'ab'] would be valid )

  2. The order in which the object yields upon iteration. i goes to the first yield, j the second.

  3. Yes, but not as pretty. I believe it is functionally equivalent to:

    l = list()
    for i,j in object:
        l.append(function(i,j))
    

    or even better use map:

    map(function, object)
    

    But of course function would have to get i, j itself.

  4. Isn't this the same question as 3?

How to convert string to double with proper cultureinfo

You can change your UI culture to anything you want, but you should change the number separator like this:

CultureInfo info = new CultureInfo("fa-IR");
info.NumberFormat.NumberDecimalSeparator = ".";
Thread.CurrentThread.CurrentCulture = info;
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

With this, your strings converts like this: "12.49" instead of "12,49" or "12/49"

How can I simulate an anchor click via jquery?

You can create a form via jQuery or in the HTML page code with an action that mimics your link href:

<a id="anchor_link" href="somepath.php">click here</a>.

var link = $('#anchor_link').attr('href');
$('body').append('<form id="new_form" action="'+link+'"></form>');
$('#new_form').submit();

Which method performs better: .Any() vs .Count() > 0?

Since this is a rather popular topic and answers differ, I had to take a fresh look on the problem.

Testing env: EF 6.1.3, SQL Server, 300k records

Table model:

class TestTable
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Surname { get; set; }
}

Test code:

class Program
{
    static void Main()
    {
        using (var context = new TestContext())
        {
            context.Database.Log = Console.WriteLine;

            context.TestTables.Where(x => x.Surname.Contains("Surname")).Any(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Any(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname")).Count(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Count(x => x.Id > 1000);

            Console.ReadLine();
        }
    }
}

Results:

Any() ~ 3ms

Count() ~ 230ms for first query, ~ 400ms for second

Remarks:

For my case, EF didn't generate SQL like @Ben mentioned in his post.

How to pass a value from one jsp to another jsp page?

Use below code for passing string from one jsp to another jsp

A.jsp

   <% String userid="Banda";%>
    <form action="B.jsp" method="post">
    <%
    session.setAttribute("userId", userid);
        %>
        <input type="submit"
                            value="Login">
    </form>

B.jsp

    <%String userid = session.getAttribute("userId").toString(); %>
    Hello<%=userid%>

SSH to Vagrant box in Windows?

Now I have a much better solution that enables painless Vagrant upgrade. It is based on patched file.

The first line of a vagrantfile should be:

load "vagrantfile_ssh" if Vagrant::Util::Platform.windows?

And the patched vagrantfile_ssh file (originaly named ssh.rb) should exist in the same directory as vagrantfile. This is both elegant and functional.

Download the patched vagrantfile_ssh.

Get json value from response

If the response is in json then it would be like:

alert(response.id);

Otherwise

var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

How to pass all arguments passed to my bash script to a function of mine?

Use the $@ variable, which expands to all command-line parameters separated by spaces.

abc "$@"

How to stop tracking and ignore changes to a file in Git?

As pointed out in other answers, the selected answer is wrong.

The answer to another question suggests that it may be skip-worktree that would be required.

git update-index --skip-worktree <file>

How to make Visual Studio copy a DLL file to the output directory?

(This answer only applies to C# not C++, sorry I misread the original question)

I've got through DLL hell like this before. My final solution was to store the unmanaged DLLs in the managed DLL as binary resources, and extract them to a temporary folder when the program launches and delete them when it gets disposed.

This should be part of the .NET or pinvoke infrastructure, since it is so useful.... It makes your managed DLL easy to manage, both using Xcopy or as a Project reference in a bigger Visual Studio solution. Once you do this, you don't have to worry about post-build events.

UPDATE:

I posted code here in another answer https://stackoverflow.com/a/11038376/364818

how to prevent adding duplicate keys to a javascript array

A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.

var array = new Set();
array.add(1);
array.add(2);
array.add(3);

console.log(array);
// Prints: Set(3) {1, 2, 3}

array.add(2); // does not add any new element

console.log(array);
// Still Prints: Set(3) {1, 2, 3}

How to make a query with group_concat in sql server

This can also be achieved using the Scalar-Valued Function in MSSQL 2008
Declare your function as following,

CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500) 
AS
BEGIN

    DECLARE @SchoolName varchar(500)                        

    SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', ' 
    FROM maskdetails MD WITH (NOLOCK)       
    AND MD.MaskId=@MaskId

    RETURN @SchoolName

END

And then your final query will be like

SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid 
ORDER BY m.maskname ;

Note: You may have to change the function, as I don't know the complete table structure.

Gradle proxy configuration

An update to @sourcesimian 's and @kunal-b's answer which dynamically sets the username and password if configured in the system properties.

The following sets the username and password if provided or just adds the host and port if no username and password is set.

task setHttpProxyFromEnv {
    def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
    for (e in System.getenv()) {
        def key = e.key.toUpperCase()
        if (key in map) {
            def base = map[key]
            //Get proxyHost,port, username, and password from http system properties 
            // in the format http://username:password@proxyhost:proxyport
            def (val1,val2) = e.value.tokenize( '@' )
            def (val3,val4) = val1.tokenize( '//' )
            def(userName, password) = val4.tokenize(':')
            def url = e.value.toURL()
            //println " - systemProp.${base}.proxy=${url.host}:${url.port}"
            System.setProperty("${base}.proxyHost", url.host.toString())
            System.setProperty("${base}.proxyPort", url.port.toString())
            System.setProperty("${base}.proxyUser", userName.toString())
            System.setProperty("${base}.proxyPassword", password.toString())
        }
    }
}

jQuery .val() vs .attr("value")

Example more... attr() is various, val() is just one! Prop is boolean are different.

_x000D_
_x000D_
//EXAMPLE 1 - RESULT_x000D_
$('div').append($('input.idone').attr('value')).append('<br>');_x000D_
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');_x000D_
$('div').append($('input#idtwo').attr('name')).append('<br>');_x000D_
$('div').append($('input[name=nameone]').attr('value'));_x000D_
_x000D_
$('div').append('<hr>'); //EXAMPLE 2_x000D_
$('div').append($('input.idone').val()).append('<br>');_x000D_
_x000D_
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL_x000D_
$('div').append($('input.idone').val('idonenew')).append('<br>');_x000D_
$('input.idone').attr('type','initial');_x000D_
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE_x000D_
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');_x000D_
$('input#idtwo').attr('type','initial');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">_x000D_
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">_x000D_
<br>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

`React/RCTBridgeModule.h` file not found

Latest releases of react-native libraries as explained in previous posts and here have breaking compatibility changes. If you do not plan to upgrade to react-native 0.40+ yet you can force install previous version of the library, for example with react-native-fs:

npm install --save -E [email protected]

How can you run a Java program without main method?

Up to and including Java 6 it was possible to do this using the Static Initialization Block as was pointed out in the question Printing message on Console without using main() method. For instance using the following code:

public class Foo {
    static {
         System.out.println("Message");
         System.exit(0);
    } 
}

The System.exit(0) lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:

Exception in thread "main" java.lang.NoSuchMethodError: main

In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:

The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).

Here an alternative is to write your own launcher, this way you can define entry points as you want.

In the article JVM Launcher you will find the necessary information to get started:

This article explains how can we create a Java Virtual Machine Launcher (like java.exe or javaw.exe). It explores how the Java Virtual Machine launches a Java application. It gives you more ideas on the JDK or JRE you are using. This launcher is very useful in Cygwin (Linux emulator) with Java Native Interface. This article assumes a basic understanding of JNI.

How can I enter latitude and longitude in Google Maps?

You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.

How do I determine if a port is open on a Windows server?

On a Windows machine you can use PortQry from Microsoft to check whether an application is already listening on a specific port using the following command:

portqry -n 11.22.33.44 -p tcp -e 80

"webxml attribute is required" error in Maven

Make sure to run mvn install before you compile your war.

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

condition: =K21+$F22

That is not a CONDITION. That is a VALUE. A CONDITION, evaluates as a BOOLEAN value (True/False) If True, then the format is applied.

This would be a CONDITION, for instance

condition: =K21+$F22>0

In general, when applying a CF to a range,

1) select the entire range that you want the Conditional FORMAT to be applied to.

2) enter the CONDITION, as it relates to the FIRST ROW of your selection.

The CF accordingly will be applied thru the range.

How can I make a div stick to the top of the screen once it's been scrolled to?

This is how i did it with jquery. This was all cobbled together from various answers on stack overflow. This solution caches the selectors for faster performance and also solves the "jumping" issue when the sticky div becomes sticky.

Check it out on jsfiddle: http://jsfiddle.net/HQS8s/

CSS:

.stick {
    position: fixed;
    top: 0;
}

JS:

$(document).ready(function() {
    // Cache selectors for faster performance.
    var $window = $(window),
        $mainMenuBar = $('#mainMenuBar'),
        $mainMenuBarAnchor = $('#mainMenuBarAnchor');

    // Run this on scroll events.
    $window.scroll(function() {
        var window_top = $window.scrollTop();
        var div_top = $mainMenuBarAnchor.offset().top;
        if (window_top > div_top) {
            // Make the div sticky.
            $mainMenuBar.addClass('stick');
            $mainMenuBarAnchor.height($mainMenuBar.height());
        }
        else {
            // Unstick the div.
            $mainMenuBar.removeClass('stick');
            $mainMenuBarAnchor.height(0);
        }
    });
});

Find provisioning profile in Xcode 5

The following works for me at a command prompt

cd ~/Library/MobileDevice/Provisioning\ Profiles/
for f in *.mobileprovision; do echo $f; openssl asn1parse -inform DER -in $f | grep -A1 application-identifier; done

Finding out which signing keys are used by a particular profile is harder to do with a shell one-liner. Basically you need to do:

openssl asn1parse -inform DER -in your-mobileprovision-filename

then cut-and-paste each block of base64 data after the DeveloperCertificates entry into its own file. You can then use:

openssl asn1parse -inform PEM -in file-with-base64

to dump each certificate. The line after the second commonName in the output will be the key name e.g. "iPhone Developer: Joe Bloggs (ABCD1234X)".

How can I check if char* variable points to empty string?

Check the pointer for NULL and then using strlen to see if it returns 0.
NULL check is important because passing NULL pointer to strlen invokes an Undefined Behavior.

Most efficient way to find smallest of 3 numbers Java?

If you will call min() around 1kk times with different a, b, c, then use my method:

Here only two comparisons. There is no way to calc faster :P

public static double min(double a, double b, double c) {
    if (a > b) {     //if true, min = b
        if (b > c) { //if true, min = c
            return c;
        } else {     //else min = b
            return b; 
        }
    }          //else min = a
    if (a > c) {  // if true, min=c
        return c;
    } else {
        return a;
    }
}

std::vector versus std::array in C++

A vector is a container class while an array is an allocated memory.

Adding link a href to an element using css

You cannot simply add a link using CSS. CSS is used for styling.

You can style your using CSS.

If you want to give a link dynamically to then I will advice you to use jQuery or Javascript.

You can accomplish that very easily using jQuery.

I have done a sample for you. You can refer that.

URL : http://jsfiddle.net/zyk9w/

$('#link').attr('href','http://www.google.com');

This single line will do the trick.

Eclipse Indigo - Cannot install Android ADT Plugin

Execute eclipse with root level

$sudo /opt/eclipse/eclipse

How to generate Javadoc from command line

You can refer the javadoc 8 documentation

I think what you are looking at is something like this:

javadoc -d C:\javadoc\test com.test

Error QApplication: no such file or directory

In Qt5 you should use QtWidgets instead of QtGui

#include <QtGui/QComboBox>     // incorrect in QT5
#include <QtWidgets/QComboBox>    // correct in QT5

Or

#include <QtGui/QStringListModel>    // incorrect in QT5
#include <QtCore/QStringListModel>    // correct in QT5

python dataframe pandas drop column using int

You need to identify the columns based on their position in dataframe. For example, if you want to drop (del) column number 2,3 and 5, it will be,

df.drop(df.columns[[2,3,5]], axis = 1)

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

remove url parameters with javascript or jquery

This worked for me:

window.location.replace(window.location.pathname)

Why use deflate instead of gzip for text files served by Apache?

mod_deflate requires fewer resources on your server, although you may pay a small penalty in terms of the amount of compression.

If you are serving many small files, I'd recommend benchmarking and load testing your compressed and uncompressed solutions - you may find some cases where enabling compression will not result in savings.

Vertical dividers on horizontal UL menu

This can also be done via CSS:pseudo-classes. Support isn't quite as wide and the answer above gives you the same result, but it's pure CSS-y =)

.ULHMenu li { border-left: solid 2px black; }
.ULHMenu li:first-child { border: 0px; }

OR:

.ULHMenu li { border-right: solid 2px black; }
.ULHMenu li:last-child { border: 0px; }

See: http://www.quirksmode.org/css/firstchild.html
Or: http://www.w3schools.com/cssref/sel_firstchild.asp

nginx missing sites-available directory

Well, I think nginx by itself doesn't have that in its setup, because the Ubuntu-maintained package does it as a convention to imitate Debian's apache setup. You could create it yourself if you wanted to emulate the same setup.

Create /etc/nginx/sites-available and /etc/nginx/sites-enabled and then edit the http block inside /etc/nginx/nginx.conf and add this line

include /etc/nginx/sites-enabled/*;

Of course, all the files will be inside sites-available, and you'd create a symlink for them inside sites-enabled for those you want enabled.

What size should TabBar images be?

According to the latest Apple Human Interface Guidelines:

In portrait orientation, tab bar icons appear above tab titles. In landscape orientation, the icons and titles appear side-by-side. Depending on the device and orientation, the system displays either a regular or compact tab bar. Your app should include custom tab bar icons for both sizes.

enter image description here

enter image description here

I suggest you to use the above link to understand the full concept. Because apple update it's document in regular interval

Efficient way to rotate a list in python

For an immutable implementation, you could use something like this:

def shift(seq, n):
    shifted_seq = []
    for i in range(len(seq)):
        shifted_seq.append(seq[(i-n) % len(seq)])
    return shifted_seq

print shift([1, 2, 3, 4], 1)

Explaining the 'find -mtime' command

+1 means 2 days ago. It's rounded.

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try this:

import matplotlib as plt

after importing the file we can use matplotlib library but remember to use it as plt

df.plt(kind='line',figsize=(10,5))

after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

How do I find an element position in std::vector?

You could use std::numeric_limits<size_t>::max() for elements that was not found. It is a valid value, but it is impossible to create container with such max index. If std::vector has size equal to std::numeric_limits<size_t>::max(), then maximum allowed index will be (std::numeric_limits<size_t>::max()-1), since elements counted from 0.

convert from Color to brush

Brush brush = new SolidColorBrush(color);

The other way around:

if (brush is SolidColorBrush colorBrush)
    Color color = colorBrush.Color;

Or something like that.

Point being not all brushes are colors but you could turn all colors into a (SolidColor)Brush.

Convert Mercurial project to Git

If you want to import your existing mercurial repository into a 'GitHub' repository, you can now simply use GitHub Importer available here [Login required]. No more messing around with fast-export etc. (although its a very good tool)

You will get all your commits, branches and tags intact. One more cool thing is that you can change the author's email-id as well. Check out below screenshots:

enter image description here

enter image description here

How to pass a variable from Activity to Fragment, and pass it back?

For all the Kotlin developers out there:

Here is the Android Studio proposed solution to send data to your Fragment (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").

Put this in your Fragment:

class MyFragment: Fragment {

...

    companion object {

            @JvmStatic
            fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
                arguments = Bundle().apply {
                    putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
                }
            }
     }
}

.apply is a nice trick to set data when an object is created, or as they state here:

Calls the specified function [block] with this value as its receiver and returns this value.

Then in your Activity or Fragment do:

val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here

and read the Arguments in your Fragment such as:

private var isMyBoolean = false

override fun onAttach(context: Context?) {
    super.onAttach(context)
    arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
        isMyBoolean = it
    }
}

To "send" data back to your Activity, simply define a function in your Activity and do the following in your Fragment:

(activity as? YourActivityClass)?.callYourFunctionLikeThis(date) // your function will not be called if your Activity is null or is a different Class

Enjoy the magic of Kotlin!

Why doesn't wireshark detect my interface?

In Windows, with Wireshark 2.0.4, running as Administrator did not solve this for me. What did was restarting the NetGroup Packet Filter Driver (npf) service:

  1. Open a Command Prompt with administrative privileges.
  2. Execute the command sc query npf and verify if the service is running.
  3. Execute the command sc stop npf followed by the command sc start npf.
  4. Open WireShark and press F5.

Source: http://dynamic-datacenter.be/?p=1279

SoapFault exception: Could not connect to host

The host is either down or very slow to respond. If it's slow to respond, you can try increasing the timeout via the connection_timeout option or via the default_socket_timeout setting and see if that reduces the failures.

http://www.php.net/manual/en/soapclient.soapclient.php

http://www.php.net/manual/en/filesystem.configuration.php#ini.default-socket-timeout

You can also include error handling as zanlok pointed out to retry a few times. If you have users actually waiting on these SOAP calls then you'll want to queue them up and process them in the background and notify the user when they're finished.

How to sort with a lambda?

Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>

struct Foo
{
    Foo() : _i(0) {};

    int _i;

    friend std::ostream& operator<<(std::ostream& os, const Foo& f)
    {
        os << f._i;
        return os;
    };
};

typedef std::vector<Foo> VectorT;

std::string toString(const VectorT& v)
{
    std::stringstream ss;
    std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
    return ss.str();
};

int main()
{

    VectorT v(10);
    std::for_each(v.begin(), v.end(),
            [](Foo& f)
            {
                f._i = rand() % 100;
            });

    std::cout << "before sort: " << toString(v) << "\n";

    sort(v.begin(), v.end(),
            [](const Foo& a, const Foo& b)
            {
                return a._i > b._i;
            });

    std::cout << "after sort:  " << toString(v) << "\n";
    return 1;
};

The output is:

before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,

How to find the installed pandas version

Run:

pip  list

You should get a list of packages (including panda) and their versions, e.g.:

beautifulsoup4 (4.5.1)
cycler (0.10.0)
jdcal (1.3)
matplotlib (1.5.3)
numpy (1.11.1)
openpyxl (2.2.0b1)
pandas (0.18.1)
pip (8.1.2)
pyparsing (2.1.9)
python-dateutil (2.2)
python-nmap (0.6.1)
pytz (2016.6.1)
requests (2.11.1)
setuptools (20.10.1)
six (1.10.0)
SQLAlchemy (1.0.15)
xlrd (1.0.0)

How to calculate age in T-SQL with years, months, and days

CREATE FUNCTION DBO.GET_AGE
(
@DATE AS DATETIME
)
RETURNS VARCHAR(MAX)
AS
BEGIN

DECLARE @YEAR  AS VARCHAR(50) = ''
DECLARE @MONTH AS VARCHAR(50) = ''
DECLARE @DAYS  AS VARCHAR(50) = ''
DECLARE @RESULT AS VARCHAR(MAX) = ''

SET @YEAR  = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) / 12 ))
SET @MONTH = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) % 12 ))
SET @DAYS = DATEDIFF(DD,DATEADD(MM,CONVERT(INT,CONVERT(INT,@YEAR)*12 + CONVERT(INT,@MONTH)),@DATE),GETDATE())

SET @RESULT = (RIGHT('00' + @YEAR, 2) + ' YEARS ' + RIGHT('00' + @MONTH, 2) + ' MONTHS ' + RIGHT('00' + @DAYS, 2) + ' DAYS')

RETURN @RESULT
END

SELECT DBO.GET_AGE('04/12/1986')

Link and execute external JavaScript file hosted on GitHub

GitHub Pages is GitHub’s official solution to this problem.

raw.githubusercontent makes all files use the text/plain MIME type, even if the file is a CSS or JavaScript file. So going to https://raw.githubusercontent.com/‹user›/‹repo›/‹branch›/‹filepath› will not be the correct MIME type but instead a plaintext file, and linking it via <link href="..."/> or <script src="..."></script> won’t work—the CSS won’t apply / the JS won’t run.

GitHub Pages hosts your repo at a special URL, so all you have to do is check-in your files and push. Note that in most cases, GitHub Pages requires you to commit to a special branch, gh-pages.

On your new site, which is usually https://‹user›.github.io/‹repo›, every file committed to the gh-pages branch (the most recent commit) is present at this url. So then you can link to your js file via <script src="https://‹user›.github.io/‹repo›/file.js"></script>, and this will be the correct MIME type.

Do you have build files?

Personally, my recommendation is to run this branch parallel to master. On the gh-pages branch, you can edit your .gitignore file to check in all the dist/build files you need for your site (e.g. if you have any minified/compiled files), while keeping them ignored on your master branch. This is useful because you typically don’t want to track changes in build files in your regular repo. Every time you want to update your hosted files, simply merge master into gh-pages, rebuild, commit, and then push.

(protip: you can merge and rebuild in the same commit with these steps:)

$ git checkout gh-pages
$ git merge --no-ff --no-commit master  # prepare the merge but don’t commit it (as if there were a merge conflict)
$ npm run build                         # (or whatever your build process is)
$ git add .                             # stage the newly built files
$ git merge --continue                  # commit the merge
$ git push origin gh-pages

How to use the command update-alternatives --config java

You will notice a big change when selecting options if you type in "java -version" after doing so. So if you run update-alternatives --config java and select option 3, you will be using the Sun implementation.
Also, with regards to auto vs manual mode, making a selection should take it out of auto mode per this page stating:

When using the --config option, alternatives will list all of the choices for the link group of which given name is the master link. You will then be prompted for which of the choices to use for the link group. Once you make a change, the link group will no longer be in auto mode. You will need to use the --auto option in order to return to the automatic state.

And I believe auto mode is set when you install the first/only JRE/JDK.

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

how to release localhost from Error: listen EADDRINUSE

[SOLVED]

It's might be too late but it's working like a charm.

You need pm2 to be installed

npm install -g pm2

To stoping the current running server (server.js):

pm2 stop -f server.js

How to convert float value to integer in php?

What do you mean by converting?

  • casting*: (int) $float or intval($float)
  • truncating: floor($float) (down) or ceil($float) (up)
  • rounding: round($float) - has additional modes, see PHP_ROUND_HALF_... constants

*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.

PHP_INT_MAX: The largest integer supported in this build of PHP. Usually int(2147483647).

But, you could use the BCMath, or the GMP extensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)

How to run multiple sites on one apache instance

Yes with Virtual Host you can have as many parallel programs as you want:

Open

/etc/httpd/conf/httpd.conf

Listen 81
Listen 82
Listen 83

<VirtualHost *:81>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site1/html
    ServerName site1.com
    ErrorLog logs/site1-error_log
    CustomLog logs/site1-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>

<VirtualHost *:82>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site2/html
    ServerName site2.com
    ErrorLog logs/site2-error_log
    CustomLog logs/site2-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>

<VirtualHost *:83>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site3/html
    ServerName site3.com
    ErrorLog logs/site3-error_log
    CustomLog logs/site3-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>

Restart apache

service httpd restart

You can now refer Site1 :

http://<ip-address>:81/ 
http://<ip-address>:81/cgi-bin/

Site2 :

http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/

Site3 :

http://<ip-address>:83/ 
http://<ip-address>:83/cgi-bin/

If path is not hardcoded in any script then your websites should work seamlessly.

Rename file with Git

As far as I can tell, GitHub does not provide shell access, so I'm curious about how you managed to log in in the first place.

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

You have to clone your repository locally, make the change there, and push the change to GitHub.

$ git clone [email protected]:username/reponame.git
$ cd reponame
$ git mv README README.md
$ git commit -m "renamed"
$ git push origin master

With arrays, why is it the case that a[5] == 5[a]?

One thing no-one seems to have mentioned about Dinah's problem with sizeof:

You can only add an integer to a pointer, you can't add two pointers together. That way when adding a pointer to an integer, or an integer to a pointer, the compiler always knows which bit has a size that needs to be taken into account.

Splitting a continuous variable into equal sized groups

cut, when not given explicit break points divides values into bins of same width, they won't contain an equal number of items in general:

x <- c(1:4,10)
lengths(split(x, cut(x, 2)))
# (0.991,5.5]    (5.5,10] 
#           4           1 

Hmisc::cut2 and ggplot2::cut_number use quantiles, which will usually create groups of same size (in term of number of elements) if the data is well spread and of decent size, it's not always the case however. mltools::bin_data can give different results but is also based on quantiles.

These functions don't always give neat results when the data contains a small number of distinct values :

x <- rep(c(1:20),c(15, 7, 10, 3, 9, 3, 4, 9, 3, 2,
                   23, 2, 4, 1, 1, 7, 18, 37, 6, 2))

table(x)
# x
#  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 
# 15  7 10  3  9  3  4  9  3  2 23  2  4  1  1  7 18 37  6  2   

table(Hmisc::cut2(x, g=4))
# [ 1, 6) [ 6,12) [12,19) [19,20] 
#      44      44      70       8

table(ggplot2::cut_number(x, 4))
# [1,5]  (5,11] (11,18] (18,20] 
#    44      44      70       8

table(mltools::bin_data(x, bins=4, binType = "quantile"))
# [1, 5)  [5, 11) [11, 18) [18, 20] 
#     35       30       56       45

This is not clear if the optimal solution has been found here.

What is the best binning approach is a subjective matter, but one reasonable way to approach it is to look for the bins that minimize the variance around the expected bin size.

The function smart_cut from (my) package cutr proposes such feature. It's computationally heavy though and should be reserved to cases where cut points and unique values are few (which happen to be usually the case where it matters).

# devtools::install_github("moodymudskipper/cutr")
table(cutr::smart_cut(x, list(4, "balanced"), "g"))
# [1,6)  [6,12) [12,18) [18,20] 
# 44      44      33      45 

We see the groups are much better balanced.

"balanced" in the call can in fact be replaced by a custom function to optimize or restrict the bins as desired if the method based on variance isn't enough.