Programs & Examples On #Opennetcf.ioc

how to select rows based on distinct values of A COLUMN only

I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:

select min(Id), distinct MailId, EmailAddress, Name
    from yourTableName
    group by MailId, EmailAddress, Name

I see that I am using a GROUP BY clause but you still won't have two rows against any particular MailId.

Splitting a list into N parts of approximately equal length

Rounding the linspace and using it as an index is an easier solution than what amit12690 proposes.

function chunks=chunkit(array,num)

index = round(linspace(0,size(array,2),num+1));

chunks = cell(1,num);

for x = 1:num
chunks{x} = array(:,index(x)+1:index(x+1));
end
end

Remove duplicates in the list using linq

var distinctItems = items.Distinct();

To match on only some of the properties, create a custom equality comparer, e.g.:

class DistinctItemComparer : IEqualityComparer<Item> {

    public bool Equals(Item x, Item y) {
        return x.Id == y.Id &&
            x.Name == y.Name &&
            x.Code == y.Code &&
            x.Price == y.Price;
    }

    public int GetHashCode(Item obj) {
        return obj.Id.GetHashCode() ^
            obj.Name.GetHashCode() ^
            obj.Code.GetHashCode() ^
            obj.Price.GetHashCode();
    }
}

Then use it like this:

var distinctItems = items.Distinct(new DistinctItemComparer());

How do you set the title color for the new Toolbar?

This was annoying me a while and I didn't like any of the answers given, so I had a look at the source to see how it works.

FractalWrench is on the right path, but it can be used below API 23 and doesn't have to be set on the toolbar it's self.

As others have said you can set a style on the toolbar with

app:theme="@style/ActionBar"

and in that style you can set the title text colour with

<item name="titleTextColor">#00f</item>

for pre API 23 or for 23+

<item name="android:titleTextColor">your colour</item>

Full xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="?attr/actionBarSize"
    android:layout_width="match_parent"
    app:theme="@style/ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"/>


<style name="ActionBar" parent="@style/ThemeOverlay.AppCompat.ActionBar">
    <item name="android:titleTextStyle">@style/ActionBarTextStyle</item>
    <item name="titleTextColor">your colour</item>
    <item name="android:background">#ff9900</item>
</style>

Heres all the attributes that can be set for a toolbar

<declare-styleable name="Toolbar">
    <attr name="titleTextAppearance" format="reference" />
    <attr name="subtitleTextAppearance" format="reference" />
    <attr name="title" />
    <attr name="subtitle" />
    <attr name="gravity" />
    <attr name="titleMargins" format="dimension" />
    <attr name="titleMarginStart" format="dimension" />
    <attr name="titleMarginEnd" format="dimension" />
    <attr name="titleMarginTop" format="dimension" />
    <attr name="titleMarginBottom" format="dimension" />
    <attr name="contentInsetStart" />
    <attr name="contentInsetEnd" />
    <attr name="contentInsetLeft" />
    <attr name="contentInsetRight" />
    <attr name="maxButtonHeight" format="dimension" />
    <attr name="navigationButtonStyle" format="reference" />
    <attr name="buttonGravity">
        <!-- Push object to the top of its container, not changing its size. -->
        <flag name="top" value="0x30" />
        <!-- Push object to the bottom of its container, not changing its size. -->
        <flag name="bottom" value="0x50" />
    </attr>
    <!-- Icon drawable to use for the collapse button. -->
    <attr name="collapseIcon" format="reference" />
    <!-- Text to set as the content description for the collapse button. -->
    <attr name="collapseContentDescription" format="string" />
    <!-- Reference to a theme that should be used to inflate popups
         shown by widgets in the toolbar. -->
    <attr name="popupTheme" format="reference" />
    <!-- Icon drawable to use for the navigation button located at
         the start of the toolbar. -->
    <attr name="navigationIcon" format="reference" />
    <!-- Text to set as the content description for the navigation button
         located at the start of the toolbar. -->
    <attr name="navigationContentDescription" format="string" />
    <!-- Drawable to set as the logo that appears at the starting side of
         the Toolbar, just after the navigation button. -->
    <attr name="logo" />
    <!-- A content description string to describe the appearance of the
         associated logo image. -->
    <attr name="logoDescription" format="string" />
    <!-- A color to apply to the title string. -->
    <attr name="titleTextColor" format="color" />
    <!-- A color to apply to the subtitle string. -->
    <attr name="subtitleTextColor" format="color" />
</declare-styleable>

How can I sort generic list DESC and ASC?

without linq, use Sort() and then Reverse() it.

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

PRINT statement in T-SQL

So, if you have a statement something like the following, you're saying that you get no 'print' result?

select * from sysobjects
PRINT 'Just selected * from sysobjects'

If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like

raiserror ('My Print Statement', 10,1) with nowait

This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.

Find the maximum value in a list of tuples in Python

In addition to max, you can also sort:

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

Escaping double quotes in JavaScript onClick event handler

It needs to be HTML-escaped, not Javascript-escaped. Change \" to &quot;

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

What are best practices that you use when writing Objective-C and Cocoa?

The Apple-provided samples I saw treated the App delegate as a global data store, a data manager of sorts. That's wrongheaded. Create a singleton and maybe instantiate it in the App delegate, but stay away from using the App delegate as anything more than application-level event handling. I heartily second the recommendations in this blog entry. This thread tipped me off.

Inserting into Oracle and retrieving the generated sequence ID

You can do this with a single statement - assuming you are calling it from a JDBC-like connector with in/out parameters functionality:

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

or, as a pl-sql script:

variable l_batchid number;

insert into batch(batchid, batchname) 
values (batch_seq.nextval, 'new batch')
returning batchid into :l_batchid;

select :l_batchid from dual;

How to convert int to date in SQL Server 2008

If your integer is timestamp in milliseconds use:

SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name

It will format milliseconds to yyyy-mm-dd string.

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp:

function AjaxFeed(){

    return $.ajax({
        url:            'http://somesite.com/somejsonfile.php',
        data:           {something: true},
        dataType:       'jsonp',

        /* Very important */
        contentType:    'application/json',
    });
}

function GetData() {
    AjaxFeed()

    /* Everything worked okay. Hooray */
    .done(function(data){
        return data;
    })

    /* Okay jQuery is stupid manually fix things */
    .fail(function(jqXHR) {

        /* Build HTML and update */
        var data = jQuery.parseJSON(jqXHR.responseText);

        return data;
    });
}

ImportError: No module named matplotlib.pyplot

The file permissions on my virtual environment directory and my project directory were not correct and, thus, would not allow me to install the proper packages. I upadated them by running:

sudo chown user:user -R [project folder]
sudo chown user:user -R [environment folder]

In the above your should use your own usernames in place of "user". The -R recurses through all subfolders and files.

How to analyse the heap dump using jmap in java

You should use jmap -heap:format=b <process-id> without any paths. So it creates a *.bin file which you can open with jvisualvm.exe (same path as jmap). It's a great tool to open such dump files.

Difference between \b and \B in regex

\b matches a word-boundary. \B matches non-word-boundaries, and is equivalent to [^\b](?!\b) (thanks to @Alan Moore for the correction!). Both are zero-width.

See http://www.regular-expressions.info/wordboundaries.html for details. The site is extremely useful for many basic regex questions.

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now

"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "

How can I start PostgreSQL on Windows?

If you have installed postgres via the Windows installer you can start it in Services like so:

enter image description here

CSS: How to position two elements on top of each other, without specifying a height?

Here's another solution using display: flex instead of position: absolute or display: grid.

_x000D_
_x000D_
.container_row{_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.layer1 {_x000D_
  width: 100%;_x000D_
  background-color: rgba(255,0,0,0.5);  // red_x000D_
}_x000D_
_x000D_
.layer2{_x000D_
  width: 100%;_x000D_
  margin-left: -100%;_x000D_
  background-color: rgba(0,0,255,0.5);  // blue_x000D_
}
_x000D_
<div class="container_row">_x000D_
    <div class="layer1">_x000D_
        <span>Lorem ipsum...</span>_x000D_
    </div>_x000D_
    <div class="layer2">_x000D_
        More lorem ipsum..._x000D_
    </div>_x000D_
</div>_x000D_
<div class="container_row">_x000D_
    ...same HTML as above. This one should never overlap the .container_row above._x000D_
</div>
_x000D_
_x000D_
_x000D_

How do we determine the number of days for a given month in python

Alternative solution:

>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29

Accessing an array out of bounds gives no error, why?

Hint

If you want to have fast constraint size arrays with range error check, try using boost::array, (also std::tr1::array from <tr1/array> it will be standard container in next C++ specification). It's much faster then std::vector. It reserve memory on heap or inside class instance, just like int array[].
This is simple sample code:

#include <iostream>
#include <boost/array.hpp>
int main()
{
    boost::array<int,2> array;
    array.at(0) = 1; // checking index is inside range
    array[1] = 2;    // no error check, as fast as int array[2];
    try
    {
       // index is inside range
       std::cout << "array.at(0) = " << array.at(0) << std::endl;

       // index is outside range, throwing exception
       std::cout << "array.at(2) = " << array.at(2) << std::endl; 

       // never comes here
       std::cout << "array.at(1) = " << array.at(1) << std::endl;  
    }
    catch(const std::out_of_range& r)
    {
        std::cout << "Something goes wrong: " << r.what() << std::endl;
    }
    return 0;
}

This program will print:

array.at(0) = 1
Something goes wrong: array<>: index out of range

SQL ROWNUM how to return rows between a specific range

SELECT  *
FROM    (
        SELECT  q.*, rownum rn
        FROM    (
                SELECT  *
                FROM    maps006
                ORDER BY
                        id
                ) q
        )
WHERE   rn BETWEEN 50 AND 100

Note the double nested view. ROWNUM is evaluated before ORDER BY, so it is required for correct numbering.

If you omit ORDER BY clause, you won't get consistent order.

ActivityCompat.requestPermissions not showing dialog box

No matter what you do, Check if you declare Permission you need in the Manifest file.


    <!--Declaring the required permissions-->
    <uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission
        android:name="android.permission.CAMERA" />


Then go to next steps..

What is boilerplate code?

You can refer to it as "snippets" or more accurately "collection of snippets" . The term I think was coined from the press and printing industry, where they used actual "plates" and then re-used them as chunks again.. In modern-day internet it is a part of an ongoing (annoying IMHO) trend of using fancy terms for simple things in order to look more trendy and sophisticated . see RESPONSIVE = adaptable / fluid.

How can I get the behavior of GNU's readlink -f on a Mac?

A lazy way that works for me,

$ brew install coreutils
$ ln -s /usr/local/bin/greadlink /usr/local/bin/readlink
$ which readlink
/usr/local/bin/readlink
/usr/bin/readlink

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

The correct answer is the following:

if [[ -n $var ]] ; then
  blah
fi

Note the use of the [[...]], which correctly handles quoting the variables for you.

Get day of week in SQL Server 2005/2008

Even though SQLMenace's answer has been accepted, there is one important SET option you should be aware of

SET DATEFIRST

DATENAME will return correct date name but not the same DATEPART value if the first day of week has been changed as illustrated below.

declare @DefaultDateFirst int
set @DefaultDateFirst = @@datefirst
--; 7 First day of week is "Sunday" by default
select  [@DefaultDateFirst] = @DefaultDateFirst 

set datefirst @DefaultDateFirst
select datename(dw,getdate()) -- Saturday
select datepart(dw,getdate()) -- 7

--; Set the first day of week to * TUESDAY * 
--; (some people start their week on Tuesdays...)
set datefirst 2
select datename(dw,getdate()) -- Saturday
--; Returns 5 because Saturday is the 5th day since Tuesday.
--; Tue 1, Wed 2, Th 3, Fri 4, Sat 5
select datepart(dw,getdate()) -- 5 <-- It's not 7!
set datefirst @DefaultDateFirst

XAMPP Start automatically on Windows 7 startup

Try following Steps for Apache

  • Go to your XAMPP installation folder. Right-click xampp-control.exe. Click "Run as administrator"
  • Stop Apache service action port
  • Tick this (in snapshot) check box. It will ask if you want to install as service. Click "Yes".
  • Go to Windows Services by typing Window + R, then typing services.msc

  • Enter a new service name as Apache2 (or similar)

  • Set it as automatic, if you want it to run as startup.

Repeat the steps for the MySQL service

enter image description here

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

  1. Delete all temp files
    • search %TEMP%
    • delete all
  2. Perform a clean boot. see How to perform a clean boot in Windows
  3. Install vc_redist.x64 see Download Visual C++ Redistributable for Visual Studio 2015
  4. Restart without clean boot

What is meant by the term "hook" in programming?

Simple said:

A hook is a means of executing custom code (function) either before, after, or instead of existing code. For example, a function may be written to "hook" into the login process in order to execute a Captcha function before continuing on to the normal login process.

Chart.js v2 - hiding grid lines

options: {
    scales: {
        xAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }],
        yAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }]
    }
}

Getting a union of two arrays in JavaScript

_x000D_
_x000D_
function unique(arrayName)_x000D_
{_x000D_
  var newArray=new Array();_x000D_
  label: for(var i=0; i<arrayName.length;i++ )_x000D_
  {  _x000D_
    for(var j=0; j<newArray.length;j++ )_x000D_
    {_x000D_
      if(newArray[j]==arrayName[i]) _x000D_
        continue label;_x000D_
    }_x000D_
    newArray[newArray.length] = arrayName[i];_x000D_
  }_x000D_
  return newArray;_x000D_
}_x000D_
_x000D_
var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);_x000D_
var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);_x000D_
var union = unique(arr1.concat(arr2));_x000D_
console.log(union);
_x000D_
_x000D_
_x000D_

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.

int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();

Hope this answers the question.

Applying an ellipsis to multiline text

_x000D_
_x000D_
p {_x000D_
    width:100%;_x000D_
    overflow: hidden;_x000D_
    display: -webkit-box;_x000D_
    -webkit-line-clamp: 2;_x000D_
    -webkit-box-orient: vertical;_x000D_
    background:#fff;_x000D_
    position:absolute;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>
_x000D_
_x000D_
_x000D_

Python Binomial Coefficient

So, this question comes up first if you search for "Implement binomial coefficients in Python". Only this answer in its second part contains an efficient implementation which relies on the multiplicative formula. This formula performs the bare minimum number of multiplications. The function below does not depend on any built-ins or imports:

def fcomb0(n, k):
    '''
    Compute the number of ways to choose $k$ elements out of a pile of $n.$

    Use an iterative approach with the multiplicative formula:
    $$\frac{n!}{k!(n - k)!} =
    \frac{n(n - 1)\dots(n - k + 1)}{k(k-1)\dots(1)} =
    \prod_{i = 1}^{k}\frac{n + 1 - i}{i}$$

    Also rely on the symmetry: $C_n^k = C_n^{n - k},$ so the product can
    be calculated up to $\min(k, n - k).$

    :param n: the size of the pile of elements
    :param k: the number of elements to take from the pile
    :return: the number of ways to choose k elements out of a pile of n
    '''

    # When k out of sensible range, should probably throw an exception.
    # For compatibility with scipy.special.{comb, binom} returns 0 instead.
    if k < 0 or k > n:
        return 0

    if k == 0 or k == n:
        return 1

    total_ways = 1
    for i in range(min(k, n - k)):
        total_ways = total_ways * (n - i) // (i + 1)

    return total_ways

Finally, if you need even larger values and do not mind trading some accuracy, Stirling's approximation is probably the way to go.

How to run C program on Mac OS X using Terminal?

1) First you need to install a GCC Compiler for mac (Google it and install it from the net )

2) Remember the path where you are storing the C file

3) Go to Terminal and set the path

e.g- if you have saved in a new folder ProgramC in Document folder

   then type this in Terminal
    cd Document
    cd ProgramC

4) Now you can see that you are in folder where you have saved your C program (let you saved your program as Hello.c)

5) Now Compile your program

   make Hello
   ./hello

Execute function after Ajax call is complete

You should set async = false in head. Use post/get instead of ajax.

jQuery.ajaxSetup({ async: false });

    $.post({
        url: 'api.php',
        data: 'id1=' + q + '',
        dataType: 'json',
        success: function (data) {

            id = data[0];
            vname = data[1];

        }
    });

Egit rejected non-fast-forward

Applicable for Eclipse Luna + Eclipse Git 3.6.1

I,

  1. cloned git repository
  2. made some changes in source code
  3. staged changes from Git Staging View
  4. finally, commit and Push!

And I faced this issue with EGit and here is how I fixed it..

Yes, someone committed the changes before I commit my changes. So the changes are rejected. After this error, the changes gets actually committed to local repository. I did not want to just Pull the changes because I wanted to maintain linear history as pointed out in - In what cases could `git pull` be harmful?

So, I executed following steps

  1. from Git Repository perspective, right click on the concerned Git
    project
  2. select Fetch from Upstream - it fetches remote updates (refs and objects) but no updates are made locally. for more info refer What is the difference between 'git pull' and 'git fetch'?
  3. select Rebase... - this open a popup, click on Preserve merges during rebase see why
    What exactly does git's "rebase --preserve-merges" do (and why?)
  4. click on Rebase button
  5. if there is/are a conflict(s), go to step 6 else step 11
  6. a Rebase Result popup would appear, just click on OK
  7. file comparator would open up, you need to modify left side file.
  8. once you are done with merging changes correctly, goto Git Staging view
  9. stage the changes. i.e. add to index
  10. on the same view, click on Rebase-> Continue. repeat 7 to 10 until all conflicts are resolved.
  11. from History view, select your commit row and select Push Commit
  12. select Rebase Commits of local....... checkbox and click next. refer why - Git: rebase onto development branch from upstream
  13. click on Finish

Note: if you have multiple local repository commits, you need to squash them in one commit to avoid multiple merges.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

In XSLT the same <xsl:variable> can be declared only once and can be given a value only at its declaration. If more than one variables are declared at the same time, they are in fact different variables and have different scope.

Therefore, the way to achieve the wanted conditional setting of the variable and producing its value is the following:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="class">
    <xsl:variable name="subexists">
            <xsl:choose>
                <xsl:when test="joined-subclass">true</xsl:when>
                <xsl:otherwise>false</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        subexists:  <xsl:text/>    
        <xsl:value-of select="$subexists" />
    </xsl:template>
</xsl:stylesheet>

When the above transformation is applied on the following XML document:

<class>
 <joined-subclass/>
</class>

the wanted result is produced:

    subexists:  true

Get exception description and stack trace which caused an exception, all as a string

For Python 3.5+:

So, you can get the stacktrace from your exception as from any other exception. Use traceback.TracebackException for it (just replace ex with your exception):

print("".join(traceback.TracebackException.from_exception(ex).format())

An extended example and other features to do this:

import traceback

try:
    1/0
except Exception as ex:
    print("".join(traceback.TracebackException.from_exception(ex).format()) == traceback.format_exc() == "".join(traceback.format_exception(type(ex), ex, ex.__traceback__))) # This is True !!
    print("".join(traceback.TracebackException.from_exception(ex).format()))

The output will be something like this:

True
Traceback (most recent call last):
  File "untidsfsdfsdftled.py", line 29, in <module>
    1/0
ZeroDivisionError: division by zero

Where is the web server root directory in WAMP?

this is the path to the web root directory c:\wamp\www

you can create different projects by adding different folders to this directory and call them like:

localhost/project1 from browser

this will run the index.html or index.php, lying inside project1

Watching variables in SSIS during debug

I believe you can only add variables to the Watch window while the debugger is stopped on a breakpoint. If you set a breakpoint on a step, you should be able to enter variables into the Watch window when the breakpoint is hit. You can select the first empty row in the Watch window and enter the variable name (you may or may not get some Intellisense there, I can't remember how well that works.)

Is it possible to reference one CSS rule within another?

Just add the classes to your html

<div class="someDiv radius opacity"></div>

Bash scripting missing ']'

I got this error while trying to use the && operator inside single brackets like [ ... && ... ]. I had to switch to [[ ... && ... ]].

Move branch pointer to different commit without checkout

If you want to move a non-checked out branch to another commit, the easiest way is running the git branch command with -f option, which determines where the branch HEAD should be pointing to:

git branch -f

Be careful as this won't work if the branch you are trying to move is your current branch. To move a branch pointer, run the following command: git update-ref -m "reset: Reset to " refs/heads/

The git update-ref command updates the object name stored in a ref safely.

Hope, my answer helped you.The source of information is this snippet.

How can I reverse a list in Python?

>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]

Or

>>> L[::-1]
[40, 20, 10, 0]

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

If you have the correct encoding in the string, you need not do more to get the bytes for another encoding.

public static void main(String[] args) throws Exception {
    printBytes("â");
    System.out.println(
            new String(new byte[] { (byte) 0xE2 }, "ISO-8859-1"));
    System.out.println(
            new String(new byte[] { (byte) 0xC3, (byte) 0xA2 }, "UTF-8"));
}

private static void printBytes(String str) {
    System.out.println("Bytes in " + str + " with ISO-8859-1");
    for (byte b : str.getBytes(StandardCharsets.ISO_8859_1)) {
        System.out.printf("%3X", b);
    }
    System.out.println();
    System.out.println("Bytes in " + str + " with UTF-8");
    for (byte b : str.getBytes(StandardCharsets.UTF_8)) {
        System.out.printf("%3X", b);
    }
    System.out.println();
}

Output:

Bytes in â with ISO-8859-1
 E2
Bytes in â with UTF-8
 C3 A2
â
â

How to error handle 1004 Error with WorksheetFunction.VLookup?

From my limited experience, this happens for two main reasons:

  1. The lookup_value (arg1) is not present in the table_array (arg2)

The simple solution here is to use an error handler ending with Resume Next

  1. The formats of arg1 and arg2 are not interpreted correctly

If your lookup_value is a variable you can enclose it with TRIM()

cellNum = wsFunc.VLookup(TRIM(currName), rngLook, 13, False)

What is the best practice for creating a favicon on a web site?

I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'

Find and replace string values in list

Beside list comprehension, you can try map

>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

Run java jar file on a server as background process

Systemd which now runs in the majority of distros

Step 1:

Find your user defined services mine was at /usr/lib/systemd/system/

Step 2:

Create a text file with your favorite text editor name it whatever_you_want.service

Step 3:

Put following Template to the file whatever_you_want.service

[Unit]
Description=webserver Daemon

[Service]
ExecStart=/usr/bin/java -jar /web/server.jar
User=user

[Install]
WantedBy=multi-user.target

Step 4:

Run your service
as super user

$ systemctl start whatever_you_want.service # starts the service
$ systemctl enable whatever_you_want.service # auto starts the service
$ systemctl disable whatever_you_want.service # stops autostart
$ systemctl stop whatever_you_want.service # stops the service
$ systemctl restart whatever_you_want.service # restarts the service

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I'm not sure if this will help anyone, but in my case further up my chain I was using distinctUntilChanged and an exception inside a function there was manifesting with this error message.

How to declare variable and use it in the same Oracle SQL script?

Sometimes you need to use a macro variable without asking the user to enter a value. Most often this has to be done with optional script parameters. The following code is fully functional

column 1 noprint new_value 1
select '' "1" from dual where 2!=2;
select nvl('&&1', 'VAH') "1" from dual;
column 1 clear
define 1

Similar code was somehow found in the rdbms/sql directory.

Abstract variables in Java?

Define a constructor in the abstract class which sets the field so that the concrete implementations are per the specification required to call/override the constructor.

E.g.

public abstract class AbstractTable {
    protected String name;

    public AbstractTable(String name) {
        this.name = name;
    }
}

When you extend AbstractTable, the class won't compile until you add a constructor which calls super("somename").

public class ConcreteTable extends AbstractTable {
    private static final String NAME = "concreteTable";

    public ConcreteTable() {
        super(NAME);
    }
}

This way the implementors are required to set name. This way you can also do (null)checks in the constructor of the abstract class to make it more robust. E.g:

public AbstractTable(String name) {
    if (name == null) throw new NullPointerException("Name may not be null");
    this.name = name;
}

clearing select using jquery

Here is a small jQuery plugin that (among other things) can empty an dropdown list.

Just write:

$('your-select-element').selectUtils('setEmpty');

How to rename array keys in PHP?

This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.

Also the foreach examples will throw a warning when using strict PHP error handling.

Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.

function multi_rename_key(&$array, $old_keys, $new_keys)
{
    if(!is_array($array)){
        ($array=="") ? $array=array() : false;
        return $array;
    }
    foreach($array as &$arr){
        if (is_array($old_keys))
        {
            foreach($new_keys as $k => $new_key)
            {
                (isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
                $arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
                unset($arr[$old_keys[$k]]);
            }
        }else{
            $arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
            unset($arr[$old_keys]);
        }
    }
    return $array;
}

Usage is simple. You can either change a single key like in your example:

multi_rename_key($tags, "url", "value");

or a more complex multikey

multi_rename_key($tags, array("url","name"), array("value","title"));

It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.

Use this all the time, hope it helps!

How can I save multiple documents concurrently in Mongoose/Node.js?

Add a file called mongoHelper.js

var MongoClient = require('mongodb').MongoClient;

MongoClient.saveAny = function(data, collection, callback)
{
    if(data instanceof Array)
    {
        saveRecords(data,collection, callback);
    }
    else
    {
        saveRecord(data,collection, callback);
    }
}

function saveRecord(data, collection, callback)
{
    collection.save
    (
        data,
        {w:1},
        function(err, result)
        {
            if(err)
                throw new Error(err);
            callback(result);
        }
    );
}
function saveRecords(data, collection, callback)
{
    save
    (
        data, 
        collection,
        callback
    );
}
function save(data, collection, callback)
{
    collection.save
    (
        data.pop(),
        {w:1},
        function(err, result)
        {
            if(err)
            {               
                throw new Error(err);
            }
            if(data.length > 0)
                save(data, collection, callback);
            else
                callback(result);
        }
    );
}

module.exports = MongoClient;

Then in your code change you requires to

var MongoClient = require("./mongoHelper.js");

Then when it is time to save call (after you have connected and retrieved the collection)

MongoClient.saveAny(data, collection, function(){db.close();});

You can change the error handling to suit your needs, pass back the error in the callback etc.

Javascript: How to remove the last character from a div or a string?

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

Calendar Recurring/Repeating Events - Best Storage Method

Sounds very much like MySQL events that are stored in system tables. You can look at the structure and figure out which columns are not needed:

   EVENT_CATALOG: NULL
    EVENT_SCHEMA: myschema
      EVENT_NAME: e_store_ts
         DEFINER: jon@ghidora
      EVENT_BODY: SQL
EVENT_DEFINITION: INSERT INTO myschema.mytable VALUES (UNIX_TIMESTAMP())
      EVENT_TYPE: RECURRING
      EXECUTE_AT: NULL
  INTERVAL_VALUE: 5
  INTERVAL_FIELD: SECOND
        SQL_MODE: NULL
          STARTS: 0000-00-00 00:00:00
            ENDS: 0000-00-00 00:00:00
          STATUS: ENABLED
   ON_COMPLETION: NOT PRESERVE
         CREATED: 2006-02-09 22:36:06
    LAST_ALTERED: 2006-02-09 22:36:06
   LAST_EXECUTED: NULL
   EVENT_COMMENT:

Determining complexity for recursive functions (Big O notation)

The key here is to visualise the call tree. Once done that, the complexity is:

nodes of the call tree * complexity of other code in the function

the latter term can be computed the same way we do for a normal iterative function.

Instead, the total nodes of a complete tree are computed as

                  C^L - 1
                  -------  , when C>1
               /   C - 1
              /
 # of nodes =
              \    
               \ 
                  L        , when C=1

Where C is number of children of each node and L is the number of levels of the tree (root included).

It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".

So, in the examples above:

  1. the call tree here is C = 1, L = n+1. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n+1) * O(1) = O(n)
n     level 1
n-1   level 2
n-2   level 3
n-3   level 4
... ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n/5) * O(1) = O(n)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5
  1. call tree here is C = 1, L = log(n). Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = log5(n) * O(1) = O(log(n))
n
n/5
n/5^2
n/5^3
... ~ log5(n) levels -> L = log5(n)
  1. call tree here is C = 2, L = n. Complexity of the rest of function is O(1). This time we use the full formula for the number of nodes in the call tree because C > 1. Therefore total complexity is (C^L-1)/(C-1) * O(1) = (2^n - 1) * O(1) = O(2^n).
               n                   level 1
      n-1             n-1          level 2
  n-2     n-2     n-2     n-2      ...
n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3    ...     
              ...                ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(n). Therefore total complexity is L * O(1) = (n/5) * O(n) = O(n^2)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5

Check if a folder exist in a directory and create them using C#

    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

Str_replace for multiple items

I guess you are looking after this:

// example
private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';

...

public function templateFor(string $type, string $language): string
{
   return \str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
}

Submitting a form by pressing enter without a submit button

I added it to a function on document ready. If there is no submit button on the form (all of my Jquery Dialog Forms don't have submit buttons), append it.

$(document).ready(function (){
    addHiddenSubmitButtonsSoICanHitEnter();
});
function addHiddenSubmitButtonsSoICanHitEnter(){
    var hiddenSubmit = "<input type='submit' style='position: absolute; left: -9999px; width: 1px; height: 1px;' tabindex='-1'/>";
    $("form").each(function(i,el){
        if($(this).find(":submit").length==0)
            $(this).append(hiddenSubmit);
    });
}

Jquery each - Stop loop and return object

Rather than setting a flag, it could be more elegant to use JavaScript's Array.prototype.find to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the .find call's return value:

function findXX(word) {
    return someArray.find((item, i) => {
        $('body').append('-> '+i+'<br />');
        return item === word;
    }); 
}

_x000D_
_x000D_
const someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';

var test = findXX('o322');
console.log('found word:', test);

function findXX(word) {
  return someArray.find((item, i) => {
    $('body').append('-> ' + i + '<br />');
    return item === word;
  });
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Prevent flex items from overflowing a container

I know this is really late, but for me, I found that applying flex-basis: 0; to the element prevented it from overflowing.

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

In my case, it happened when one table is InnoB and other is MyISAM. Changing engine of one table, through MySQL Workbench, solves for me.

Group by with union mysql select query

This may be what your after:

SELECT Count(Owner_ID), Name
FROM (
    SELECT M.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Motorbike As M
    WHERE T.Type = 'Motorbike'
    AND O.Owner_ID = M.Owner_ID
    AND T.Type_ID = M.Motorbike_ID

    UNION ALL

    SELECT C.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Car As C
    WHERE T.Type = 'Car'
    AND O.Owner_ID = C.Owner_ID
    AND T.Type_ID = C.Car_ID
)
GROUP BY Owner_ID

Re-doing a reverted merge in Git

To revert a revert in GIT:

git revert <commit-hash-of-previous-revert>

How to create a custom exception type in Java?

You should be able to create a custom exception class that extends the Exception class, for example:

class WordContainsException extends Exception
{
      // Parameterless Constructor
      public WordContainsException() {}

      // Constructor that accepts a message
      public WordContainsException(String message)
      {
         super(message);
      }
 }

Usage:

try
{
     if(word.contains(" "))
     {
          throw new WordContainsException();
     }
}
catch(WordContainsException ex)
{
      // Process message however you would like
}

Convert date to day name e.g. Mon, Tue, Wed

Very Simply Short week day name with Month and year

echo date('D, d-M-y');

output

Tue, 16-Feb-21

as per my requirements

return $item->start_time->format("D, d-M");

output

Tue, 16-Feb

How to export and import environment variables in windows?

To export user variables, open a command prompt and use regedit with /e

Example :

regedit /e "%userprofile%\Desktop\my_user_env_variables.reg" "HKEY_CURRENT_USER\Environment"

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018:

If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  

Show/hide image with JavaScript

You can do this with jquery just visit http://jquery.com/ to get the link then do something like this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').show('slow');
      });
   });
</script>

or if you would like the link to turn the image on and off do this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none;" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').toggle();
      });
   });
</script>

How to pass values across the pages in ASP.net without using Session

You can pass values from one page to another by followings..

Response.Redirect
Cookies
Application Variables
HttpContext

Response.Redirect

SET :

Response.Redirect("Defaultaspx?Name=Pandian");

GET :

string Name = Request.QueryString["Name"];

Cookies

SET :

HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian"; 

GET :

string name = Request.Cookies["Name"].Value;

Application Variables

SET :

Application["Name"] = "pandian";

GET :

string Name = Application["Name"].ToString();

Refer the full content here : Pass values from one to another

Increase max execution time for php

Add these lines of code in your htaccess file. I hope it will solve your problem.

<IfModule mod_php5.c>
php_value max_execution_time 259200
</IfModule>

How to fix syntax error, unexpected T_IF error in php?

PHP parser errors take some getting used to; if it complains about an unexpected 'something' at line X, look at line X-1 first. In this case it will not tell you that you forgot a semi-colon at the end of the previous line , instead it will complain about the if that comes next.

You'll get used to it :)

Javascript Date - set just the date, ignoring time?

If you don't mind creating an extra date object, you could try:

var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());

I do something very similar to get a date of the current month without the time.

Close virtual keyboard on button press

You should implement OnEditorActionListener for your EditView

public void performClickOnDone(EditView editView, final View button){
    textView.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(EditView v, int actionId, KeyEvent event) {
            hideKeyboard();
            button.requestFocus();
            button.performClick();
            return true;
        }
    });

And you hide keyboard by:

public void hideKeybord(View view) {
    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),
                                  InputMethodManager.RESULT_UNCHANGED_SHOWN);
}

You should also fire keyboard hiding in your button using onClickListener

Now clicking 'Done' on virtual keyboard and button will do the same - hide keyboard and perform click action.

CSS selector for a checked radio button's label

UPDATE:

This only worked for me because our existing generated html was wacky, generating labels along with radios and giving them both checked attribute.

Never mind, and big ups for Brilliand for bringing it up!

If your label is a sibling of a checkbox (which is usually the case), you can use the ~ sibling selector, and a label[for=your_checkbox_id] to address it... or give the label an id if you have multiple labels (like in this example where I use labels for buttons)


Came here looking for the same - but ended up finding my answer in the docs.

a label element with checked attribute can be selected like so:

label[checked] {
  ...
}

I know it's an old question, but maybe it helps someone out there :)

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Try

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header.

Adding header to all request with Retrofit 2

Kotlin version would be

fun getHeaderInterceptor():Interceptor{
    return object : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request =
            chain.request().newBuilder()
                    .header(Headers.KEY_AUTHORIZATION, "Bearer.....")
                    .build()
            return chain.proceed(request)
        }
    }
}


private fun createOkHttpClient(): OkHttpClient {
    return OkHttpClient.Builder()
            .apply {
                if(BuildConfig.DEBUG){
                    this.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
                }
            }
            .addInterceptor(getHeaderInterceptor())
            .build()
}

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

What's the difference between JavaScript and JScript?

JScript is the Microsoft implementation of Javascript

Python basics printing 1 to 100

because if you change your code with

def gukan(count):
    while count!=100:
      print(count)
      count=count+3;
gukan(0)

count reaches 99 and then, at the next iteration 102.

So

count != 100

never evaluates true and the loop continues forever

If you want to count up to 100 you may use

def gukan(count):
    while count <= 100:
      print(count)
      count=count+3;
gukan(0)

or (if you want 100 always printed)

def gukan(count):
    while count <= 100:
      print(count)
      count=count+3;
      if count > 100:
          count = 100
gukan(0)

How do I concatenate two lists in Python?

import itertools

A = list(zip([1,3,5,7,9],[2,4,6,8,10]))
B = [1,3,5,7,9]+[2,4,6,8,10]
C = list(set([1,3,5,7,9] + [2,4,6,8,10]))

D = [1,3,5,7,9]
D.append([2,4,6,8,10])

E = [1,3,5,7,9]
E.extend([2,4,6,8,10])

F = []
for a in itertools.chain([1,3,5,7,9], [2,4,6,8,10]):
    F.append(a)


print ("A: " + str(A))
print ("B: " + str(B))
print ("C: " + str(C))
print ("D: " + str(D))
print ("E: " + str(E))
print ("F: " + str(F))

Output:

A: [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
B: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
C: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
D: [1, 3, 5, 7, 9, [2, 4, 6, 8, 10]]
E: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
F: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

Seconds CountDown Timer

int segundo = 0;
DateTime dt = new DateTime();

private void timer1_Tick(object sender, EventArgs e){
    segundo++;
    label1.Text = dt.AddSeconds(segundo).ToString("HH:mm:ss");
}

Permutation of array

If you're using C++, you can use std::next_permutation from the <algorithm> header file:

int a[] = {3,4,6,2,1};
int size = sizeof(a)/sizeof(a[0]);
std::sort(a, a+size);
do {
  // print a's elements
} while(std::next_permutation(a, a+size));

warning: assignment makes integer from pointer without a cast

When you write the statement

*src = "anotherstring";

the compiler sees the constant string "abcdefghijklmnop" like an array. Imagine you had written the following code instead:

char otherstring[14] = "anotherstring";
...
*src = otherstring;

Now, it's a bit clearer what is going on. The left-hand side, *src, refers to a char (since src is of type pointer-to-char) whereas the right-hand side, otherstring, refers to a pointer.

This isn't strictly forbidden because you may want to store the address that a pointer points to. However, an explicit cast is normally used in that case (which isn't too common of a case). The compiler is throwing up a red flag because your code is likely not doing what you think it is.

It appears to me that you are trying to assign a string. Strings in C aren't data types like they are in C++ and are instead implemented with char arrays. You can't directly assign values to a string like you are trying to do. Instead, you need to use functions like strncpy and friends from <string.h> and use char arrays instead of char pointers. If you merely want the pointer to point to a different static string, then drop the *.

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

MySQL: selecting rows where a column is null

Info from http://w3schools.com/sql/sql_null_values.asp:

1) NULL values represent missing unknown data.

2) By default, a table column can hold NULL values.

3) NULL values are treated differently from other values

4) It is not possible to compare NULL and 0; they are not equivalent.

5) It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

6) We will have to use the IS NULL and IS NOT NULL operators instead

So in case of your problem:

SELECT pid FROM planets WHERE userid IS NULL

JQuery, select first row of table

Can't you use the first selector ?

something like: tr:first

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

WORDPRESS is having this error mostly:
SOLUTION:
Locate your PHP installed directory on Remote live hosting SERVER or "Local Server"
In case of Windows os
for example if you using xampp or wamp webserver. it will be in xammp directory 'c:\xammp\php'
Note: For Unix/Linux OS, locate your PHP directory in Webserver

Find & Edit PHP.INI file
Find 'allow_url_include'
replace it with value 'on'
allow_url_include=On
Save you php.ini & RESTART you web-server.

Tomcat 8 Maven Plugin for Java 8

Almost 2 years later....
This github project readme has a some clarity of configuration of the maven plugin and it seems, according to this apache github project, the plugin itself will materialise soon enough.

Where does the .gitignore file belong?

Root directory is fine for placing the .gitignore file.

Don't forget to use git rm --cached FILENAME to add files to .gitignore if you have created the gitignore file after you committed the repo with a file you want ignored. See github docs. I found this out when I created a .env file, then committed it, then tried it to ignore it by creating a .gitignore file.

How do I change db schema to dbo

Way to do it for an individual thing:

alter schema dbo transfer jonathan.MovieData

Iterating over ResultSet and adding its value in an ArrayList

Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet to List, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator:

jOOQ 3.8 or less

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(r -> Arrays.stream(r.intoArray()))
   .collect(Collectors.toList());

jOOQ 3.9

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(Record::intoStream)
   .collect(Collectors.toList());

(Disclaimer, I work for the company behind jOOQ)

What is the curl error 52 "empty reply from server"?

I've had this problem before. Figured out I had another application using the same port (3000).

Easy way to find this out:

In the terminal, type netstat -a -p TCP -n | grep 3000 (substitute the port you're using for the '3000'). If there is more than one listening, something else is already occupying that port. You should stop that process or change the port for your new process.

Substitute multiple whitespace with single whitespace in Python

A regular expression can be used to offer more control over the whitespace characters that are combined.

To match unicode whitespace:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"\s+")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()

To match ASCII whitespace only:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)

Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.

Reference:

About \s:

For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

About re.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

strip() will remote any leading and trailing whitespaces.

SQL recursive query on self referencing table (Oracle)

Do you want to do this?

SELECT id, parent_id, name, 
 (select Name from tbl where id = t.parent_id) parent_name
FROM tbl t start with id = 1 CONNECT BY PRIOR id = parent_id

Edit Another option based on OMG's one (but I think that will perform equally):

select 
           t1.id, 
           t1.parent_id, 
           t1.name,
           t2.name AS parent_name,
           t2.id AS parent_id
from 
    (select id, parent_id, name
    from tbl
    start with id = 1 
    connect by prior id = parent_id) t1
    left join
    tbl t2 on t2.id = t1.parent_id

Using {% url ??? %} in django templates

I run into same problem.

What I found from documentation, we should use namedspace.

in your case {% url login:login_view %}

How to update UI from another thread running in another class

I am going to throw you a curve ball here. If I have said it once I have said it a hundred times. Marshaling operations like Invoke or BeginInvoke are not always the best methods for updating the UI with worker thread progress.

In this case it usually works better to have the worker thread publish its progress information to a shared data structure that the UI thread then polls at regular intervals. This has several advantages.

  • It breaks the tight coupling between the UI and worker thread that Invoke imposes.
  • The UI thread gets to dictate when the UI controls get updated...the way it should be anyway when you really think about it.
  • There is no risk of overrunning the UI message queue as would be the case if BeginInvoke were used from the worker thread.
  • The worker thread does not have to wait for a response from the UI thread as would be the case with Invoke.
  • You get more throughput on both the UI and worker threads.
  • Invoke and BeginInvoke are expensive operations.

So in your calcClass create a data structure that will hold the progress information.

public class calcClass
{
  private double percentComplete = 0;

  public double PercentComplete
  {
    get 
    { 
      // Do a thread-safe read here.
      return Interlocked.CompareExchange(ref percentComplete, 0, 0);
    }
  }

  public testMethod(object input)
  {
    int count = 1000;
    for (int i = 0; i < count; i++)
    {
      Thread.Sleep(10);
      double newvalue = ((double)i + 1) / (double)count;
      Interlocked.Exchange(ref percentComplete, newvalue);
    }
  }
}

Then in your MainWindow class use a DispatcherTimer to periodically poll the progress information. Configure the DispatcherTimer to raise the Tick event on whatever interval is most appropriate for your situation.

public partial class MainWindow : Window
{
  public void YourDispatcherTimer_Tick(object sender, EventArgs args)
  {
    YourProgressBar.Value = calculation.PercentComplete;
  }
}

SQL Server - inner join when updating

UPDATE R 
SET R.status = '0' 
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P 
       ON R.pid = P.id 
WHERE R.id = '17190' 
  AND P.shopkeeper = '89137';

How can I develop for iPhone using a Windows development machine?

Yes and you don't need to learn Objective-C and buying Apple software and hardware.

Adobe have created compilator from ActionScript 3 to program for iOS. And later Apple approved this method of application creation.

This is best way to create Apple applications under Windows or Linux/BSD (and another one for MacOS-X)

How to send UTF-8 email?

I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:

function utf8_to_latin2($str)
{
    return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
    {
        mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
        "From: $form\r\n".
        "Reply-To: $reply\r\n".
        "X-Mailer: PHP/" . phpversion());
    }

I have made another mailer function, because apple device could not read well the previous version.

function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
    $s= "=?utf-8?b?".base64_encode($s)."?=";
    $headers = "MIME-Version: 1.0\r\n";
    $headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
    $headers.= "Content-Type: text/plain;charset=utf-8\r\n";
    $headers.= "Reply-To: $reply\r\n";  
    $headers.= "X-Mailer: PHP/" . phpversion();
    mail($to, $s, $body, $headers);
}

print spaces with String.format()

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

Insert new column into table in sqlite?

You can add new column with the query

ALTER TABLE TableName ADD COLUMN COLNew CHAR(25)

But it will be added at the end, not in between the existing columns.

How to select data of a table from another database in SQL Server?

In SQL Server 2012 and above, you don't need to create a link. You can execute directly

SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET

I don't know whether previous versions of SQL Server work as well

Why can't I define a default constructor for a struct in .NET?

Just special-case it. If you see a numerator of 0 and a denominator of 0, pretend like it has the values you really want.

jQuery - setting the selected value of a select control via its text description

If you are trying to bind select with ID then the following code worked for me.

<select name="0product_id[]" class="groupSelect" id="groupsel_0" onchange="productbuilder.update(this.value,0);">
    <option value="0" class="notag" id="id0_0">--Select--</option>
    <option class="notag" value="338" id="id0_338"  >Dual Promoter Puromycin Expression Plasmid - pSF-CMV-PGK-Puro  > £114.00</option>
    <option class="notag" value="282" id="id0_282"  >EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00</option>
    <option class="notag" value="265" id="id0_265"  >FMDV IRES Puromycin Expression Plasmid - pSF-CMV-FMDV-Puro  > £114.00</option>
    <option class="notag" value="101" id="id0_101"  >Puromycin Selection Plasmid - pSF-CMV-Ub-Puro AscI  > £114.00</option>
    <option class="notag" value="105" id="id0_105"  >Puromycin Selection SV40 Ori Plasmid - pSF-CMV-Ub-Puro-SV40 Ori SbfI  > £114.00</option></select>

AND THIS IS TEH JS CODE

$( document ).ready(function() {
      var text = "EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00";
      alert(text);
$("#groupsel_0 option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text;
}).prop('selected', true);
});

Why is Java's SimpleDateFormat not thread-safe?

ThreadLocal + SimpleDateFormat = SimpleDateFormatThreadSafe

package com.foocoders.text;

import java.text.AttributedCharacterIterator;
import java.text.DateFormatSymbols;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class SimpleDateFormatThreadSafe extends SimpleDateFormat {

    private static final long serialVersionUID = 5448371898056188202L;
    ThreadLocal<SimpleDateFormat> localSimpleDateFormat;

    public SimpleDateFormatThreadSafe() {
        super();
        localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat();
            }
        };
    }

    public SimpleDateFormatThreadSafe(final String pattern) {
        super(pattern);
        localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat(pattern);
            }
        };
    }

    public SimpleDateFormatThreadSafe(final String pattern, final DateFormatSymbols formatSymbols) {
        super(pattern, formatSymbols);
        localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat(pattern, formatSymbols);
            }
        };
    }

    public SimpleDateFormatThreadSafe(final String pattern, final Locale locale) {
        super(pattern, locale);
        localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
            protected SimpleDateFormat initialValue() {
                return new SimpleDateFormat(pattern, locale);
            }
        };
    }

    public Object parseObject(String source) throws ParseException {
        return localSimpleDateFormat.get().parseObject(source);
    }

    public String toString() {
        return localSimpleDateFormat.get().toString();
    }

    public Date parse(String source) throws ParseException {
        return localSimpleDateFormat.get().parse(source);
    }

    public Object parseObject(String source, ParsePosition pos) {
        return localSimpleDateFormat.get().parseObject(source, pos);
    }

    public void setCalendar(Calendar newCalendar) {
        localSimpleDateFormat.get().setCalendar(newCalendar);
    }

    public Calendar getCalendar() {
        return localSimpleDateFormat.get().getCalendar();
    }

    public void setNumberFormat(NumberFormat newNumberFormat) {
        localSimpleDateFormat.get().setNumberFormat(newNumberFormat);
    }

    public NumberFormat getNumberFormat() {
        return localSimpleDateFormat.get().getNumberFormat();
    }

    public void setTimeZone(TimeZone zone) {
        localSimpleDateFormat.get().setTimeZone(zone);
    }

    public TimeZone getTimeZone() {
        return localSimpleDateFormat.get().getTimeZone();
    }

    public void setLenient(boolean lenient) {
        localSimpleDateFormat.get().setLenient(lenient);
    }

    public boolean isLenient() {
        return localSimpleDateFormat.get().isLenient();
    }

    public void set2DigitYearStart(Date startDate) {
        localSimpleDateFormat.get().set2DigitYearStart(startDate);
    }

    public Date get2DigitYearStart() {
        return localSimpleDateFormat.get().get2DigitYearStart();
    }

    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
        return localSimpleDateFormat.get().format(date, toAppendTo, pos);
    }

    public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
        return localSimpleDateFormat.get().formatToCharacterIterator(obj);
    }

    public Date parse(String text, ParsePosition pos) {
        return localSimpleDateFormat.get().parse(text, pos);
    }

    public String toPattern() {
        return localSimpleDateFormat.get().toPattern();
    }

    public String toLocalizedPattern() {
        return localSimpleDateFormat.get().toLocalizedPattern();
    }

    public void applyPattern(String pattern) {
        localSimpleDateFormat.get().applyPattern(pattern);
    }

    public void applyLocalizedPattern(String pattern) {
        localSimpleDateFormat.get().applyLocalizedPattern(pattern);
    }

    public DateFormatSymbols getDateFormatSymbols() {
        return localSimpleDateFormat.get().getDateFormatSymbols();
    }

    public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols) {
        localSimpleDateFormat.get().setDateFormatSymbols(newFormatSymbols);
    }

    public Object clone() {
        return localSimpleDateFormat.get().clone();
    }

    public int hashCode() {
        return localSimpleDateFormat.get().hashCode();
    }

    public boolean equals(Object obj) {
        return localSimpleDateFormat.get().equals(obj);
    }

}

https://gist.github.com/pablomoretti/9748230

Trigger change() event when setting <select>'s value with val() function

I separate it, and then use an identity comparison to dictate what is does next.

$("#selectField").change(function(){
  if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
  if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});

PHP/MySQL: How to create a comment section in your website

This is my way i do comments (I think its secure):

<h1>Comment's:</h1>
<?php 
$i  = addslashes($_POST['a']);
$ip = addslashes($_POST['b']);
$a  = addslashes($_POST['c']);
$b  = addslashes($_POST['d']);
if(isset($i) & isset($ip) & isset($a) & isset($b))
{
    $r = mysql_query("SELECT COUNT(*) FROM $db.ban WHERE ip=$ip"); //Check if banned
    $r = mysql_fetch_array($r);
    if(!$r[0]) //Phew, not banned
    {
        if(mysql_query("INSERT INTO $db.com VALUES ($a, $b, $ip, $i)"))
        {
            ?>
            <script type="text/javascript">
                window.location="/index.php?id=".<?php echo $i; ?>;
            </script>
            <?php
        }
        else echo "Error, in mysql query";  
    }
    else echo "Error, You are banned.";
}
$x = mysql_query("SELECT * FROM $db.com WHERE i=$i");
while($r = mysql_fetch_object($x) echo '<div class="c">'.$r->a.'<p>'.$row->b.'</p> </div>';

?>  
<h1>Leave a comment, pl0x:</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="hidden" name="a" value="<?php $echo $_GET['id']; ?>" />
    <input type="hidden" name="b" value="<?php $echo $_SERVER['REMOTE_ADDR']; ?>" />
    <input type="text" name="c" value="Name"/></br>
    <textarea name="d">
    </textarea>
    <input type="submit" />
</form>

This does it all in one page (This is only the comments section, some configuration is needed)

Git log out user from command line

If you are facing any issues during push ( in windows OS), just remove the cached git account by following the given steps below: 1. Search for Control panel and open the same. 2. Search for Credential Manager and open this. 3. Click on Windows Credentials under Manage your credentials page. 4. Under Generic Credentials click on GitHub. 5. Click on Remove and then confirm by clicking Yes button. 6. Now start pushing the code and you will get GitHub popup to login again and now you are done. Everything will work properly after successful login.

Can you pass parameters to an AngularJS controller on creation?

Here is a solution (based on Marcin Wyszynski's suggestion) which works where you want to pass a value into your controller but you aren't explicitly declaring the controller in your html (which ng-init seems to require) - if, for example, you are rendering your templates with ng-view and declaring each controller for the corresponding route via routeProvider.

JS

messageboard.directive('currentuser', ['CurrentUser', function(CurrentUser) {
  return function(scope, element, attrs) {
    CurrentUser.name = attrs.name;
  };
}]);

html

<div ng-app="app">
  <div class="view-container">
    <div ng-view currentuser name="testusername" class="view-frame animate-view"></div>
  </div>
</div>

In this solution, CurrentUser is a service which can be injected into any controller, with the .name property then available.

Two notes:

  • a problem I've encountered is that .name gets set after the controller loads, so as a workaround I have a short timeout before rendering username on the controller's scope. Is there a neat way of waiting until .name has been set on the service?

  • this feels like a very easy way to get a current user into your Angular App with all the authentication kept outside Angular. You could have a before_filter to prevent non-logged in users getting to the html where your Angular app is bootstrapped in, and within that html you could just interpolate the logged in user's name and even their ID if you wanted to interact with the user's details via http requests from your Angular app. You could allow non-logged in users to use the Angular App with a default 'guest user'. Any advice on why this approach would be bad would be welcome - it feels too easy to be sensible!)

How to set lifetime of session

As long as the User does not delete their cookies or close their browser, the session should stay in existence.

Construct pandas DataFrame from list of tuples of (row,col,values)

This is what I expected to see when I came to this question:

#!/usr/bin/env python

import pandas as pd


df = pd.DataFrame([(1, 2, 3, 4),
                   (5, 6, 7, 8),
                   (9, 0, 1, 2),
                   (3, 4, 5, 6)],
                  columns=list('abcd'),
                  index=['India', 'France', 'England', 'Germany'])
print(df)

gives

         a  b  c  d
India    1  2  3  4
France   5  6  7  8
England  9  0  1  2
Germany  3  4  5  6

visual c++: #include files from other projects in the same solution

Expanding on @Benav's answer, my preferred approach is to:

  1. Add the solution directory to your include paths:
    • right click on your project in the Solution Explorer
    • select Properties
    • select All Configurations and All Platforms from the drop-downs
    • select C/C++ > General
    • add $(SolutionDir) to the Additional Include Directories
  2. Add references to each project you want to use:
    • right click on your project's References in the Solution Explorer
    • select Add Reference...
    • select the project(s) you want to refer to

Now you can include headers from your referenced projects like so:

#include "OtherProject/Header.h"

Notes:

  • This assumes that your solution file is stored one folder up from each of your projects, which is the default organization when creating projects with Visual Studio.
  • You could now include any file from a path relative to the solution folder, which may not be desirable but for the simplicity of the approach I'm ok with this.
  • Step 2 isn't necessary for #includes, but it sets the correct build dependencies, which you probably want.

Git reset --hard and push to remote repository

To complement Jakub's answer, if you have access to the remote git server in ssh, you can go into the git remote directory and set:

user@remote$ git config receive.denyNonFastforwards false

Then go back to your local repo, try again to do your commit with --force:

user@local$ git push origin +master:master --force

And finally revert the server's setting in the original protected state:

user@remote$ git config receive.denyNonFastforwards true

Jquery checking success of ajax post

The documentation is here: http://docs.jquery.com/Ajax/jQuery.ajax

But, to summarize, the ajax call takes a bunch of options. the ones you are looking for are error and success.

You would call it like this:

$.ajax({
  url: 'mypage.html',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

I have shown the success and error function taking no arguments, but they can receive arguments.

The error function can take three arguments: XMLHttpRequest, textStatus, and errorThrown.

The success function can take two arguments: data and textStatus. The page you requested will be in the data argument.

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

How to check whether an object is a date?

For all types I cooked up an Object prototype function. It may be of use to you

Object.prototype.typof = function(chkType){
      var inp        = String(this.constructor),
          customObj  = (inp.split(/\({1}/))[0].replace(/^\n/,'').substr(9),
          regularObj = Object.prototype.toString.apply(this),
          thisType   = regularObj.toLowerCase()
                        .match(new RegExp(customObj.toLowerCase()))
                       ? regularObj : '[object '+customObj+']';
     return chkType
            ? thisType.toLowerCase().match(chkType.toLowerCase()) 
               ? true : false
            : thisType;
}

Now you can check any type like this:

var myDate     = new Date().toString(),
    myRealDate = new Date();
if (myRealDate.typof('Date')) { /* do things */ }
alert( myDate.typof() ); //=> String

[Edit march 2013] based on progressing insight this is a better method:

Object.prototype.is = function() {
        var test = arguments.length ? [].slice.call(arguments) : null
           ,self = this.constructor;
        return test ? !!(test.filter(function(a){return a === self}).length)
               : (this.constructor.name ||
                  (String(self).match ( /^function\s*([^\s(]+)/im)
                    || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
}
// usage
var Some = function(){ /* ... */}
   ,Other = function(){ /* ... */}
   ,some = new Some;
2..is(String,Function,RegExp);        //=> false
2..is(String,Function,Number,RegExp); //=> true
'hello'.is(String);                   //=> true
'hello'.is();                         //-> String
/[a-z]/i.is();                        //-> RegExp
some.is();                            //=> 'ANONYMOUS_CONSTRUCTOR'
some.is(Other);                       //=> false
some.is(Some);                        //=> true
// note: you can't use this for NaN (NaN === Number)
(+'ab2').is(Number);                 //=> true

Detect application heap size in Android

This returns max heap size in bytes:

Runtime.getRuntime().maxMemory()

I was using ActivityManager.getMemoryClass() but on CyanogenMod 7 (I didn't test it elsewhere) it returns wrong value if the user sets heap size manually.

sendmail: how to configure sendmail on ubuntu?

Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth  #maybe not, because I cannot apply cmd "cd auth" if I do so.

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl

#run 
sudo sendmailconfig

Android change SDK version in Eclipse? Unable to resolve target android-x

I faced the same issue and got it working.

I think it is because when you import a project, build target is not set in the project properties which then default to the value used in manifest file. Most likely, you already have installed a later android API with your SDK.

The solution is to enable build target toward your installed API level (but keep the minimum api support as specified in the manifest file). TO do this, in project properties, go to android, and from "Project Build Target", pick a target name.

How to use terminal commands with Github?

To add all file at a time, use git add -A

To check git whole status, use git log

How do I start/stop IIS Express Server?

to stop IIS manually:

  1. go to start menu
  2. type in IIS

you get a search result for the manager (Internet Information Services (IIS) manager, on the right side of it there are restart/stop/start buttons.

If you don't want IIS to start on startup because its really annoying..:

  1. go to start menu.
  2. click control panel.
  3. click programs.
  4. turn windows features on or off
  5. wait until the list is loaded
  6. search for Internet Information Services (IIS).
  7. uncheck the box.
  8. Wait until it's done with the changes.
  9. restart computer, but then again the info box will tell you to do that anyways (you can leave this for later if you want to).

oh and IIS and xampp basically do the same thing just in a bit different way. ANd if you have Xampp for your projects then its not really all that nessecary to leave it on if you don't ever use it anyways.

PHP String to Float

If you need to handle values that cannot be converted separately, you can use this method:

try {
    $valueToUse = trim($stringThatMightBeNumeric) + 0;
} catch (\Throwable $th) {
    // bail here if you need to
}

How to make a phone call using intent in Android?

Every thing is fine.

i just placed call permissions tag before application tag in manifest file

and now every thing is working fine.

Div with margin-left and width:100% overflowing on the right side

Add some css either in the head or in a external document. asp:TextBox are rendered as input :

input {
     width:100%;
}

Your html should look like : http://jsfiddle.net/c5WXA/

Note this will affect all your textbox : if you don't want this, give the containing div a class and specify the css.

.divClass input {
     width:100%;
}

Change primary key column in SQL Server

Necromancing.
It looks you have just as good a schema to work with as me... Here is how to do it correctly:

In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

HTTP redirect: 301 (permanent) vs. 302 (temporary)

The main issue with 301 is browser will cache the redirection even if you disabled the redirection from the server level.

Its always better to use 302 if you are enabling the redirection for a short maintenance window.

The import org.junit cannot be resolved

When you add TestNG to your Maven dependencies , Change scope from test to compile.Hope this would solve your issue..

Convert date to another timezone in JavaScript

Okay, found it!

I'm using timezone-js. this is the code:

var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
dt.setTimezone("Asia/Jakarta");

console.debug(dt); //return formatted date-time in asia/jakarta

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

Php multiple delimiters in explode

You can take the first string, replace all the @ with vs using str_replace, then explode on vs or vice versa.

Auto generate function documentation in Visual Studio

In visual basic, if you create your function/sub first, then on the line above it, you type ' three times, it will auto-generate the relevant xml for documentation. This also shows up when you mouseover in intellisense, and when you are making use of the function.

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

New .NET 5 Solution:

In .NET 5, a new class has been introduced called JsonContent, which derives from HttpContent. See in Microsoft docs

This class has a static method called Create(), which takes an object as a parameter.

Usage:

var myObject = new
{
    foo = "Hello",
    bar = "World",
};

JsonContent content = JsonContent.Create(myObject);

HttpResponseMessage response = await _httpClient.PostAsync("https://...", content);

raw vs. html_safe vs. h to unescape html

The difference is between Rails’ html_safe() and raw(). There is an excellent post by Yehuda Katz on this, and it really boils down to this:

def raw(stringish)

  stringish.to_s.html_safe

end

Yes, raw() is a wrapper around html_safe() that forces the input to String and then calls html_safe() on it. It’s also the case that raw() is a helper in a module whereas html_safe() is a method on the String class which makes a new ActiveSupport::SafeBuffer instance — that has a @dirty flag in it.

Refer to "Rails’ html_safe vs. raw".

Passing Arrays to Function in C++

The question has already been answered, but I thought I'd add an answer with more precise terminology and references to the C++ standard.

Two things are going on here, array parameters being adjusted to pointer parameters, and array arguments being converted to pointer arguments. These are two quite different mechanisms, the first is an adjustment to the actual type of the parameter, whereas the other is a standard conversion which introduces a temporary pointer to the first element.

Adjustments to your function declaration:

dcl.fct#5:

After determining the type of each parameter, any parameter of type “array of T” (...) is adjusted to be “pointer to T”.

So int arg[] is adjusted to be int* arg.

Conversion of your function argument:

conv.array#1

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion is applied. The result is a pointer to the first element of the array.

So in printarray(firstarray, 3);, the lvalue firstarray of type "array of 3 int" is converted to a prvalue (temporary) of type "pointer to int", pointing to the first element.

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regular expression should look like:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/

Here is an explanation:

/^
  (?=.*\d)          // should contain at least one digit
  (?=.*[a-z])       // should contain at least one lower case
  (?=.*[A-Z])       // should contain at least one upper case
  [a-zA-Z0-9]{8,}   // should contain at least 8 from the mentioned characters
$/

tmux set -g mouse-mode on doesn't work

Try this. It works on my computer.

set -g mouse on

Why doesn't [01-12] range work as expected?

This also works:

^([1-9]|[0-1][0-2])$

[1-9] matches single digits between 1 and 9

[0-1][0-2] matches double digits between 10 and 12

There are some good examples here

How to use readline() method in Java?

This will explain it, I think...

import java.io.*;

class reading
{
    public static void  main(String args[]) throws IOException
    {
        float number;
        System.out.println("Enter a number");
        try
        {
            InputStreamReader in = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(in);
            String a = br.readLine();
            number = Float.valueOf(a);
            int x = (int)number;

            System.out.println("Your input=" + number);
            System.out.println("Your input in integer terms is = " + x);
        }
        catch(Exception e){
        }
    }
}

Convert Xml to DataTable

DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);

How to use underscore.js as a template engine?

In it's simplest form you would use it like:

var html = _.template('<li><%= name %></li>', { name: 'John Smith' });
//html is now '<li>John Smith</li>'   

If you're going to be using a template a few times you'll want to compile it so it's faster:

var template = _.template('<li><%= name %></li>');

var html = [];
for (var key in names) {
    html += template({ name: names[i] });
}

console.log(html.join('')); //Outputs a string of <li> items

I personally prefer the Mustache style syntax. You can adjust the template token markers to use double curly braces:

_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;

var template = _.template('<li>{{ name }}</li>');

How to run multiple .BAT files within a .BAT file

With correct quoting (this can be tricky sometimes):

start "" /D "C:\Program Files\ProgramToLaunch" "cmd.exe" "/c call ""C:\Program Files\ProgramToLaunch\programname.bat"""

1st arg - Title (empty in this case)
2nd arg - /D specifies starting directory, can be ommited if want the current working dir (such as "%~dp0")
3rd arg - command to launch, "cmd.exe"
4th arg - arguments to command, with doubled up quotes for the arguments inside it (this is how you escape quotes within quotes in batch)

jQuery UI: Datepicker set year range dropdown to 100 years

Try the following:-

ChangeYear:- When set to true, indicates that the cells of the previous or next month indicated in the calendar of the current month can be selected. This option is used with options.showOtherMonths set to true.

YearRange:- Specifies the range of years in the year dropdown. (Default value: “-10:+10")

Example:-

$(document).ready(function() {
    $("#date").datepicker({
        changeYear:true,
        yearRange: "2005:2015"
    });
});

See:- set year range in jquery datepicker

How to synchronize a static variable among threads running different instances of a class in Java?

If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:

public class Test {

    private final static AtomicInteger count = new AtomicInteger(0); 

    public void foo() {  
        count.incrementAndGet();
    }  
}

Classes vs. Functions

i know it is a controversial topic, and likely i get burned now. but here are my thoughts.

For myself i figured that it is best to avoid classes as long as possible. If i need a complex datatype I use simple struct (C/C++), dict (python), JSON (js), or similar, i.e. no constructor, no class methods, no operator overloading, no inheritance, etc. When using class, you can get carried away by OOP itself (What Design pattern, what should be private, bla bla), and loose focus on the essential stuff you wanted to code in the first place.

If your project grows big and messy, then OOP starts to make sense because some sort of helicopter-view system architecture is needed. "function vs class" also depends on the task ahead of you.

function

  • purpose: process data, manipulate data, create result sets.
  • when to use: always code a function if you want to do this: “y=f(x)”

struct/dict/json/etc (instead of class)

  • purpose: store attr./param., maintain attr./param., reuse attr./param., use attr./param. later.
  • when to use: if you deal with a set of attributes/params (preferably not mutable)
  • different languages same thing: struct (C/C++), JSON (js), dict (python), etc.
  • always prefer simple struct/dict/json/etc over complicated classes (keep it simple!)

class (if it is a new data type)

  • a simple perspective: is a struct (C), dict (python), json (js), etc. with methods attached.
  • The method should only make sense in combination with the data/param stored in the class.
  • my advice: never code complex stuff inside class methods (call an external function instead)
  • warning: do not misuse classes as fake namespace for functions! (this happens very often!)
  • other use cases: if you want to do a lot of operator overloading then use classes (e.g. your own matrix/vector multiplication class)
  • ask yourself: is it really a new “data type”? (Yes => class | No => can you avoid using a class)

array/vector/list (to store a lot of data)

  • purpose: store a lot of homogeneous data of the same data type, e.g. time series
  • advice#1: just use what your programming language already have. do not reinvent it
  • advice#2: if you really want your “class mysupercooldatacontainer”, then overload an existing array/vector/list/etc class (e.g. “class mycontainer : public std::vector…”)

enum (enum class)

  • i just mention it
  • advice#1: use enum plus switch-case instead of overcomplicated OOP design patterns
  • advice#2: use finite state machines

How to access local files of the filesystem in the Android emulator?

In Android Studio 3.5.3, the Device File Explorer can be found in View -> Tool Windows.

It can also be opened using the vertical tabs on the right-hand side of the main window.

How to launch a Google Chrome Tab with specific URL using C#

As a simplification to chrfin's response, since Chrome should be on the run path if installed, you could just call:

Process.Start("chrome.exe", "http://www.YourUrl.com");

This seem to work as expected for me, opening a new tab if Chrome is already open.

How to Refresh a Component in Angular

constructor(private router:Router, private route:ActivatedRoute ) { 
}

onReload(){
 this.router.navigate(['/servers'],{relativeTo:this.route})
}

Bootstrap 3 Flush footer to bottom. not fixed

Use any class and make it's height fixed. It solved my issue.

<div class="container"></div>
<footer></footer>

CSS:

.container{
    min-height: 60vh;
}

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

Pandas split column of lists into multiple columns

This solution preserves the index of the df2 DataFrame, unlike any solution that uses tolist():

df3 = df2.teams.apply(pd.Series)
df3.columns = ['team1', 'team2']

Here's the result:

  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

Best way to "push" into C# array

Your question is a little off the mark. In particular, you say "that the element needs to be added into the first empty slot in an array, lie (sic) a Java push function would do."

  1. Java's Array does not have a push operation - JavaScript does. Java and JavaScript are two very different languages
  2. JavaScript's push function does not behave as you describe. When you "push" a value into a JavaScript array, the array is extended by one element, and that new element is assigned the pushed value, see: Mozilla's Array.prototype.push function docs

The verb "Push" is not something that is used with an Array in any language that I know of except JavaScript. I suspect that it's only in JavaScript because it could be there (since JavaScript is a completely dynamic language). I'm pretty sure it wasn't designed in intentionally.

A JavaScript-style Push operation in C# could be written in this somewhat inefficient manner:

int [] myArray = new int [] {1, 2, 3, 4};
var tempList = myArray.ToList();
tempList.Add(5);
myArray = tempList.ToArray();   //equiv: myArray.Push(5);

"Push" is used in some types of containers, particularly Stacks, Queues and Deques (which get two pushes - one from the front, one from the back). I urge you not to include Push as a verb in your explanation of arrays. It adds nothing to a CS student's vocabulary.

In C#, as in most traditional procedural languages, an array is a collection of elements of a single type, contained in a fixed length contiguous block of memory. When you allocate an array, the space for every array element is allocated (and, in C# those elements are initialized to the default value of the type, null for reference types).

In C#, arrays of reference types are filled with object references; arrays of value types are filled with instances of that value type. As a result, an array of 4 strings uses the same memory as an array of 4 instance of your application class (since they are both reference types). But, an array of 4 DateTime instances is significantly longer that of an array of 4 short integers.

In C#, an instance of an array is an instance of System.Array, a reference type. Arrays have a few properties and methods (like the Length property). Otherwise, there isn't much you can do with an array: you can read (or write) from (or to) individual elements using an array index. Arrays of type T also implement IEnumerable<T>, so you can iterate through the elements of an array.

Arrays are mutable (the values in an array can be written to), but they have a fixed length - they can't be extended or shortened. They are ordered, and they can't be re-arranged (except by swizzling the values manually).

C# arrays are covariant. If you were to ask the C# language designers, this would be the feature they regret the most. It's one of the few ways you can break C# type safety. Consider this code (assuming that Cat and Dog classes inherit from Animal):

Cat[] myCats = new Cat[]{myCat, yourCat, theirCat};
Animal[] animals = (Animal[]) myCats;     //legal but dangerous
animals[1] = new Dog();                   //heading off the cliff
myCats[1].Speak();                        //Woof!

That "feature" is the result of the lack of generic types and explicit covariance/contravariance in the initial version of the .NET Framework and the urge to copy a Java "feature".

Arrays do show up in many core .NET APIs (for example, System.Reflection). They are there, again, because the initial release did not support generic collections.

In general, an experienced C# programmer will not use many arrays in his applications, preferring to use more capable collections such as List<T>, Dictionary<TKey, TValue>, HashSet<T> and friends. In particular, that programmer will tend to pass collections around using IEnumerable<T> an interface that all collections implement. The big advantage of using IEnumerable<T> as parameters and return types (where possible and logical) is that collections accessed via IEnumerable<T> references are immutable. It's kinda-sorta like using const correctly in C++.

One thing you might consider adding in to your lectures on arrays - after everyone has mastered the basics - is the new Span<T> type. Spans may make C# arrays useful.

Finally, LINQ (Language Integrated Query) introduced a lot of functionality to collections (by adding Extension Methods to IEnumerable<T>). Make sure your student do not have a using System.Linq; statement up at the top of their code - mixing LINQ in to a beginning student's class on arrays would bewilder him or her.

BTW: what kind of class is it you teach? At what level?

Octave/Matlab: Adding new elements to a vector

As mentioned before, the use of x(end+1) = newElem has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.

However, what should not be forgotten is that x = [x newElem] will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]


All in all, if you want a solution that allows you to concatenate your existing vector x with newElem that may or may not be a scalar, this should do the trick:

 x(end+(1:numel(newElem)))=newElem

How to draw rounded rectangle in Android UI?

You could just define a new xml background in the drawables folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />
</shape>  

After this just include it in your TextView or EditText by defining it in the background.

<TextView
 android:id="@+id/textView"
 android:layout_width="0dp"
 android:layout_height="80dp"
 android:background="YOUR_FILE_HERE"
 Android:layout_weight="1"
 android:gravity="center"
 android:text="TEXT_HERE"
 android:textSize="40sp" />

Is it possible to change the radio button icon in an android radio button group

In case you want to do it programmatically,

checkBoxOrRadioButton.setButtonDrawable(null);
checkBoxOrRadioButton.setBackgroundResource(R.drawable.resource_name);

how to get login option for phpmyadmin in xampp

Step 1:

Locate phpMyAdmin installation path.

Step 2:

Open phpMyAdmin/config.inc.php in your favourite text editor. Copy config.sample.inc.php to config.inc.php if it's missing.

Step 3:

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

Why does datetime.datetime.utcnow() not contain timezone information?

To add timezone information in Python 3.2+

import datetime

>>> d = datetime.datetime.now(tz=datetime.timezone.utc)
>>> print(d.tzinfo)
'UTC+00:00'

How to append a date in batch files

As has been noted, parsing the date and time is only useful if you know the format being used by the current user (eg. MM/dd/yy or dd-MM-yyyy just to name 2). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.

You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.

there are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.

Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.

reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f
reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f
@REM the following may be needed to be sure cache is clear before using the new setting
reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f

Multi-line bash commands in makefile

You can use backslash for line continuation. However note that the shell receives the whole command concatenated into a single line, so you also need to terminate some of the lines with a semicolon:

foo:
    for i in `find`;     \
    do                   \
        all="$$all $$i"; \
    done;                \
    gcc $$all

But if you just want to take the whole list returned by the find invocation and pass it to gcc, you actually don't necessarily need a multiline command:

foo:
    gcc `find`

Or, using a more shell-conventional $(command) approach (notice the $ escaping though):

foo:
    gcc $$(find)

Correct way to read a text file into a buffer in C?

If you're on a linux system, once you have the file descriptor you can get a lot of information about the file using fstat()

http://linux.die.net/man/2/stat

so you might have

#include  <unistd.h> 
void main()
{
    struct stat stat;
    int fd;
    //get file descriptor
    fstat(fd, &stat);
    //the size of the file is now in stat.st_size
}

This avoids seeking to the beginning and end of the file.

More than 1 row in <Input type="textarea" />

The "input" tag doesn't support rows and cols attributes. This is why the best alternative is to use a textarea with rows and cols attributes. You can still add a "name" attribute and also there is a useful "wrap" attribute which can serve pretty well in various situations.

How to put php inside JavaScript?

All the explanations above doesn't work if you work with .js files. If you want to parse PHP into .js files, you have to make changes on your server by modfiying the .htaccess in which the .js files reside using the following commands:

<FilesMatch "\.(js)$">
    AddHandler application/x-httpd-php .js
</FilesMatch>

Then, a file test.js files containing the following code will execute .JS on client side with the parsed PHP on server-side:

<html>
<head>
<script>
function myFunction(){
   alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()"><?php echo "My button";?></button>
</body>
</html>

Launch a shell command with in a python script, wait for the termination and return to the script

subprocess: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

http://docs.python.org/library/subprocess.html

Usage:

import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode

How to forward declare a template class in namespace std?

I solved that problem.

I was implementing an OSI Layer (slider window, Level 2) for a network simulation in C++ (Eclipse Juno). I had frames (template <class T>) and its states (state pattern, forward declaration).

The solution is as follows:

In the *.cpp file, you must include the Header file that you forward, i.e.

ifndef STATE_H_
#define STATE_H_
#include <stdlib.h>
#include "Frame.h"

template <class T>
class LinkFrame;

using namespace std;

template <class T>
class State {

  protected:
    LinkFrame<int> *myFrame;

}

Its cpp:

#include "State.h"
#include "Frame.h"
#include  "LinkFrame.h"

template <class T>
bool State<T>::replace(Frame<T> *f){

And... another class.

How to compare if two structs, slices or maps are equal?

Since July 2017 you can use cmp.Equal with cmpopts.IgnoreFields option.

func TestPerson(t *testing.T) {
    type person struct {
        ID   int
        Name string
    }

    p1 := person{ID: 1, Name: "john doe"}
    p2 := person{ID: 2, Name: "john doe"}
    println(cmp.Equal(p1, p2))
    println(cmp.Equal(p1, p2, cmpopts.IgnoreFields(person{}, "ID")))

    // Prints:
    // false
    // true
}

File upload along with other object in Jersey restful web service

Your ApplicationConfig should register the MultiPartFeature.class from the glassfish.jersey.media.. so as to enable file upload

@javax.ws.rs.ApplicationPath(ResourcePath.API_ROOT)
public class ApplicationConfig extends ResourceConfig {  
public ApplicationConfig() {
        //register the necessary headers files needed from client
        register(CORSConfigurationFilter.class);
        //The jackson feature and provider is used for object serialization
        //between client and server objects in to a json
        register(JacksonFeature.class);
        register(JacksonProvider.class);
        //Glassfish multipart file uploader feature
        register(MultiPartFeature.class);
        //inject and registered all resources class using the package
        //not to be tempered with
        packages("com.flexisaf.safhrms.client.resources");
        register(RESTRequestFilter.class);
    }

Editable 'Select' element

Similar to answer above but without the absolute positioning:

<select style="width: 200px; float: left;" onchange="this.nextElementSibling.value=this.value">
    <option></option>
    <option>1</option>
    <option>2</option>
    <option>3</option> 
</select>
<input style="width: 185px; margin-left: -199px; margin-top: 1px; border: none; float: left;"/>

So create a input box and put it over the top of the combobox

Pass multiple values with onClick in HTML link

 $Name= "'".$row['Name']."'";
  $Val1= "'".$row['Val1']."'";
  $Year= "'".$row['Year']."'";
  $Month="'".$row['Month']."'";

 echo '<button type="button"   onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');"  >submit</button>'; 

Corrupt jar file

This regularly occurs when you change the extension on the JAR for ZIP, extract the zip content and make some modifications on files such as changing the MANIFEST.MF file which is a very common case, many times Eclipse doesn't generate the MANIFEST file as we want, or maybe we would like to modify the CLASS-PATH or the MAIN-CLASS values of it.

The problem occurs when you zip back the folder.

A valid Runnable/Executable JAR has the next structure:

myJAR (Main-Directory)
    |-META-INF (Mandatory)
             |-MANIFEST.MF (Mandatory Main-class: com.MainClass)
    |-com 
         |-MainClass.class (must to implement the main method, mandatory)
    |-properties files (optional)
    |-etc (optional)

If your JAR complies with these rules it will work doesn't matter if you build it manually by using a ZIP tool and then you changed the extension back to .jar

Once you're done try execute it on the command line using:

java -jar myJAR.jar 

When you use a zip tool to unpack, change files and zip again, normally the JAR structure changes to this structure which is incorrect, since another directory level is added on the top of the file system making it a corrupted file as is shown below:

**myJAR (Main-Directory)
    |-myJAR (creates another directory making the file corrupted)**
          |-META-INF (Mandatory)
                   |-MANIFEST.MF (Mandatory Main-class: com.MainClass)
          |-com 
              |-MainClass.class (must to implement the main method, mandatory)
          |-properties files (optional)
          |-etc (optional)

:)

JavaScript variable number of arguments to function

In (most) recent browsers, you can accept variable number of arguments with this syntax:

function my_log(...args) {
     // args is an Array
     console.log(args);
     // You can pass this array as parameters to another function
     console.log(...args);
}

Here's a small example:

function foo(x, ...args) {
  console.log(x, args, ...args, arguments);
}

foo('a', 'b', 'c', z='d')

=>

a
Array(3) [ "b", "c", "d" ]
b c d
Arguments
?    0: "a"
    ?1: "b"
    ?2: "c"
    ?3: "d"
    ?length: 4

Documentation and more examples here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

How do I write out a text file in C# with a code page other than UTF-8?

Simple!

System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));

newline in <td title="">

Using &#xA; Works in Chrome to create separate lines in a tooltip.

ORA-28040: No matching authentication protocol exception

My Initial error is : ORA-28040: No matching authentication protocol exception

My DB version is 12.2 (Solaris) and client version is 11.2 ( windows). I have added below in both server and client sqlnet.ora

SQLNET.ALLOWED_LOGON_VERSION_CLIENT = 8 SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8

while connecting, I have got invalid username and password hence I have recreated the password ( same password ) in database which is resolved my issue.

How to delete SQLite database from Android programmatically

context.deleteDatabase("database_name.db");

This might help someone. You have to mention the extension otherwise, it will not work.

Sorting by date & time in descending order?

This is one of the simplest ways to sort record by Date:

SELECT  `Article_Id` ,  `Title` ,  `Source_Link` ,  `Content` ,  `Source` , `Reg_Date`, UNIX_TIMESTAMP(  `Reg_Date` ) AS DATE
FROM article
ORDER BY DATE DESC 

Combining two expressions (Expression<Func<T, bool>>)

I suggest one more improvement to PredicateBuilder and ExpressionVisitor solutions. I called it UnifyParametersByName and you can find it in MIT library of mine: LinqExprHelper. It allows for combining arbitary lambda expressions. Usually the questions are asked about predicate expression, but this idea extends to projection expressions as well.

The following code employs a method ExprAdres which creates a complicated parametrized expression, using inline lambda. This complicated expression is coded only once, and then reused, thanks to the LinqExprHelper mini-library.

public IQueryable<UbezpExt> UbezpFull
{
    get
    {
        System.Linq.Expressions.Expression<
            Func<UBEZPIECZONY, UBEZP_ADRES, UBEZP_ADRES, UbezpExt>> expr =
            (u, parAdrM, parAdrZ) => new UbezpExt
            {
                Ub = u,
                AdrM = parAdrM,
                AdrZ = parAdrZ,
            };

        // From here an expression builder ExprAdres is called.
        var expr2 = expr
            .ReplacePar("parAdrM", ExprAdres("M").Body)
            .ReplacePar("parAdrZ", ExprAdres("Z").Body);
        return UBEZPIECZONY.Select((Expression<Func<UBEZPIECZONY, UbezpExt>>)expr2);
    }
}

And this is the subexpression building code:

public static Expression<Func<UBEZPIECZONY, UBEZP_ADRES>> ExprAdres(string sTyp)
{
    return u => u.UBEZP_ADRES.Where(a => a.TYP_ADRESU == sTyp)
        .OrderByDescending(a => a.DATAOD).FirstOrDefault();
}

What I tried to achieve was to perform parametrized queries without need to copy-paste and with ability to use inline lambdas, which are so pretty. Without all these helper-expression stuff, I would be forced to create whole query in one go.

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

How can I add a line to a file in a shell script?

sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just

echo "c1, c2, ... " >> file
cat testfile.csv >> file

?

How to edit an Android app?

First you have to download file x-plore and installed it.. After that open it and find the thoes you want to edit.. After that just rename the file Xyz.apk to xyz.zip After that open that file and you can see some folders.. then just go and edit the app..

HTML5 Canvas 100% Width Height of Viewport?

I'll answer the more general question of how to have a canvas dynamically adapt in size upon window resize. The accepted answer appropriately handles the case where width and height are both supposed to be 100%, which is what was asked for, but which also will change the aspect ratio of the canvas. Many users will want the canvas to resize on window resize, but while keeping the aspect ratio untouched. It's not the exact question, but it "fits in", just putting the question into a slightly more general context.

The window will have some aspect ratio (width / height), and so will the canvas object. How you want these two aspect ratios to relate to each other is one thing you'll have to be clear about, there is no "one size fits all" answer to that question - I'll go through some common cases of what you might want.

Most important thing you have to be clear about: the html canvas object has a width attribute and a height attribute; and then, the css of the same object also has a width and a height attribute. Those two widths and heights are different, both are useful for different things.

Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.

I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)

1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is

$(ctx.canvas).css("width", "100%");

where ctx is your canvas context. fiddle: resizeByWidth

2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do

$(ctx.canvas).css("height", window.innerHeight);

fiddle: messWithAspectratio

3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.

fiddle: redraw

4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.

fiddle: fixed

All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw

Read .csv file in C

Thought I'd share this code. It's fairly simple, but effective. It parses comma-separated files with parenthesis. You can easily modify it to suit your needs.

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


int main(int argc, char *argv[])
{
  //argv[1] path to csv file
  //argv[2] number of lines to skip
  //argv[3] length of longest value (in characters)

  FILE *pfinput;
  unsigned int nSkipLines, currentLine, lenLongestValue;
  char *pTempValHolder;
  int c;
  unsigned int vcpm; //value character marker
  int QuotationOnOff; //0 - off, 1 - on

  nSkipLines = atoi(argv[2]);
  lenLongestValue = atoi(argv[3]);

  pTempValHolder = (char*)malloc(lenLongestValue);  

  if( pfinput = fopen(argv[1],"r") ) {

    rewind(pfinput);

    currentLine = 1;
    vcpm = 0;
    QuotationOnOff = 0;

    //currentLine > nSkipLines condition skips ignores first argv[2] lines
    while( (c = fgetc(pfinput)) != EOF)
    {
       switch(c)
       {
          case ',':
            if(!QuotationOnOff && currentLine > nSkipLines) 
            {
              pTempValHolder[vcpm] = '\0';
              printf("%s,",pTempValHolder);
              vcpm = 0;
            }
            break;
          case '\n':
            if(currentLine > nSkipLines)
            {
              pTempValHolder[vcpm] = '\0';
              printf("%s\n",pTempValHolder);
              vcpm = 0;
            }
            currentLine++;
            break;
          case '\"':
            if(currentLine > nSkipLines)
            {
              if(!QuotationOnOff) {
                QuotationOnOff = 1;
                pTempValHolder[vcpm] = c;
                vcpm++;
              } else {
                QuotationOnOff = 0;
                pTempValHolder[vcpm] = c;
                vcpm++;
              }
            }
            break;
          default:
            if(currentLine > nSkipLines)
            {
              pTempValHolder[vcpm] = c;
              vcpm++;
            }
            break;
       }
    }

    fclose(pfinput); 
    free(pTempValHolder);

  }

  return 0;
}

Difference between MongoDB and Mongoose

From the first answer,

"Using Mongoose, a user can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB."

You can now also define schema with mongoDB native driver using

##For new collection

`db.createCollection("recipes",
    validator: { $jsonSchema: {
         <<Validation Rules>>
        }
    }
)`

##For existing collection

`db.runCommand( {
        collMod: "recipes",
        validator: { $jsonSchema: {
             <<Validation Rules>>
            }
        }
    } )`
    

##full example

`db.createCollection("recipes", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "servings", "ingredients"],
      additionalProperties: false,
      properties: {
        _id: {},
        name: {
          bsonType: "string",
          description: "'name' is required and is a string"
        },
        servings: {
          bsonType: ["int", "double"],
          minimum: 0,
          description:
            "'servings' is required and must be an integer with a minimum of zero."
        },
        cooking_method: {
          enum: [
            "broil",
            "grill",
            "roast",
            "bake",
            "saute",
            "pan-fry",
            "deep-fry",
            "poach",
            "simmer",
            "boil",
            "steam",
            "braise",
            "stew"
          ],
          description:
            "'cooking_method' is optional but, if used, must be one of the listed options."
        },
        ingredients: {
          bsonType: ["array"],
          minItems: 1,
          maxItems: 50,
          items: {
            bsonType: ["object"],
            required: ["quantity", "measure", "ingredient"],
            additionalProperties: false,
            description: "'ingredients' must contain the stated fields.",
            properties: {
              quantity: {
                bsonType: ["int", "double", "decimal"],
                description:
                  "'quantity' is required and is of double or decimal type"
              },
              measure: {
                enum: ["tsp", "Tbsp", "cup", "ounce", "pound", "each"],
                description:
                  "'measure' is required and can only be one of the given enum values"
              },
              ingredient: {
                bsonType: "string",
                description: "'ingredient' is required and is a string"
              },
              format: {
                bsonType: "string",
                description:
                  "'format' is an optional field of type string, e.g. chopped or diced"
              }
            }
          }
        }
      }
    }
  }
});`

Insert collection Example

`db.recipes.insertOne({
  name: "Chocolate Sponge Cake Filling",
  servings: 4,
  ingredients: [
    {
      quantity: 7,
      measure: "ounce",
      ingredient: "bittersweet chocolate",
      format: "chopped"
    },
    { quantity: 2, measure: "cup", ingredient: "heavy cream" }
  ]
});`

Is there "\n" equivalent in VBscript?

I had to use vbLf only in an ASP script where the original data was POSTed from a PHP script on a cPanel box over to ASP on a win server

(VBScript)

EmailText = Replace(EmailText, vbLf, "<br>")

How to select lines between two marker patterns which may occur multiple times with awk/sed

sed '/^abc$/,/^mno$/!d;//d' file

golfs two characters better than ppotong's {//!b};d

The empty forward slashes // mean: "reuse the last regular expression used". and the command does the same as the more understandable:

sed '/^abc$/,/^mno$/!d;/^abc$/d;/^mno$/d' file

This seems to be POSIX:

If an RE is empty (that is, no pattern is specified) sed shall behave as if the last RE used in the last command applied (either as an address or as part of a substitute command) was specified.

Reorder HTML table rows using drag-and-drop

thanks to Jim Petkus that did gave me a wonderful answer . but i was trying to solve my own script not to changing it to another plugin . My main focus was not using an independent plugin and do what i wanted just by using the jquery core !

and guess what i did find the problem .

var title = $("em").attr("title");
$("div").text(title);

this is what i add to my script and the blew codes to my html part :

<td> <em title=\"$weight\">$weight</em></td>

and found each row $weight value

thanks again to Jim Petkus