Programs & Examples On #Webrole

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

You can use Oracle.ManagedDataAccess.dll instead (download from Oracle), include that dll in you project bin dir, add reference to that dll in the project. In code, "using Oracle.MangedDataAccess.Client". Deploy project to server as usual. No need install Oracle Client on server. No need to add assembly info in web.config.

Get index of array element faster than O(n)

Is there a good reason not to use a hash? Lookups are O(1) vs. O(n) for the array.

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

The problem is mostly due to a MySQL service that is not running, so make sure it is. If it isn't, run this CMD with administrator privilege in order to start it:

sc start [Your MySQL Service name]

How to check that a string is parseable to a double?

All answers are OK, depending on how academic you want to be. If you wish to follow the Java specifications accurately, use the following:

private static final Pattern DOUBLE_PATTERN = Pattern.compile(
    "[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
    "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
    "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
    "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");

public static boolean isFloat(String s)
{
    return DOUBLE_PATTERN.matcher(s).matches();
}

This code is based on the JavaDocs at Double.

Check if date is a valid one

Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.

Changing font size and direction of axes text in ggplot2

Using "fill" attribute helps in cases like this. You can remove the text from axis using element_blank()and show multi color bar chart with a legend. I am plotting a part removal frequency in a repair shop as below

ggplot(data=df_subset,aes(x=Part,y=Removal_Frequency,fill=Part))+geom_bar(stat="identity")+theme(axis.text.x  = element_blank())

I went for this solution in my case as I had many bars in bar chart and I was not able to find a suitable font size which is both readable and also small enough not to overlap each other.

.htaccess file to allow access to images folder to view pictures?

Having the .htaccess file on the root folder, add this line. Make sure to delete all other useless rules you tried before:

Options -Indexes

Or try:

Options All -Indexes

TSQL - Cast string to integer or return default value

As has been mentioned, you may run into several issues if you use ISNUMERIC:

-- Incorrectly gives 0:
SELECT CASE WHEN ISNUMERIC('-') = 1 THEN CAST('-' AS INT) END   

-- Error (conversion failure):
SELECT CASE WHEN ISNUMERIC('$') = 1 THEN CAST('$' AS INT) END
SELECT CASE WHEN ISNUMERIC('4.4') = 1 THEN CAST('4.4' AS INT) END
SELECT CASE WHEN ISNUMERIC('1,300') = 1 THEN CAST('1,300' AS INT) END

-- Error (overflow):
SELECT CASE WHEN ISNUMERIC('9999999999') = 1 THEN CAST('9999999999' AS INT) END

If you want a reliable conversion, you'll need to code one yourself.

Update: My new recommendation would be to use an intermediary test conversion to FLOAT to validate the number. This approach is based on adrianm's comment. The logic can be defined as an inline table-valued function:

CREATE FUNCTION TryConvertInt (@text NVARCHAR(MAX)) 
RETURNS TABLE
AS
RETURN
(
    SELECT
        CASE WHEN ISNUMERIC(@text + '.e0') = 1 THEN 
             CASE WHEN CONVERT(FLOAT, @text) BETWEEN -2147483648 AND 2147483647 
                  THEN CONVERT(INT, @text) 
             END 
         END AS [Result]
)

Some tests:

SELECT [Conversion].[Result]
FROM ( VALUES
     ( '1234'                     )   -- 1234
   , ( '1,234'                    )   -- NULL
   , ( '1234.0'                   )   -- NULL
   , ( '-1234'                    )   -- -1234
   , ( '$1234'                    )   -- NULL
   , ( '1234e10'                  )   -- NULL
   , ( '1234 5678'                )   -- NULL
   , ( '123-456'                  )   -- NULL
   , ( '1234.5'                   )   -- NULL
   , ( '123456789000000'          )   -- NULL
   , ( 'N/A'                      )   -- NULL
   , ( '-'                        )   -- NULL
   , ( '$'                        )   -- NULL
   , ( '4.4'                      )   -- NULL
   , ( '1,300'                    )   -- NULL
   , ( '9999999999'               )   -- NULL
   , ( '00000000000000001234'     )   -- 1234
   , ( '212110090000000235698741' )   -- NULL
) AS [Source] ([Text])
OUTER APPLY TryConvertInt ([Source].[Text]) AS [Conversion]

Results are similar to Joseph Sturtevant's answer, with the following main differences:

  • My logic does not tolerate occurrences of . or , in order to mimic the behaviour of native INT conversions. '1,234' and '1234.0' return NULL.
  • Since it does not use local variables, my function can be defined as an inline table-valued function, allowing for better query optimization.
  • Joseph's answer can lead to incorrect results due to silent truncations of the argument; '00000000000000001234' evaluates to 12. Increasing the parameter length would result in errors on numbers that overflow BIGINT, such as BBANs (basic bank account numbers) like '212110090000000235698741'.

Withdrawn: The approach below is no longer recommended, as is left just for reference.

The snippet below works on non-negative integers. It checks that your string does not contain any non-digit characters, is not empty, and does not overflow (by exceeding the maximum value for the int type). However, it also gives NULL for valid integers whose length exceeds 10 characters due to leading zeros.

SELECT 
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 
                OR LEN(@text) = 10 AND @text <= '2147483647' 
              THEN CAST (@text AS INT)
         END
    END 

If you want to support any number of leading zeros, use the below. The nested CASE statements, albeit unwieldy, are required to promote short-circuit evaluation and reduce the likelihood of errors (arising, for example, from passing a negative length to LEFT).

SELECT 
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
              WHEN LEN(@text) >= 10 THEN
              CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
                    AND RIGHT(@text, 10) <= '2147483647'
                   THEN CAST (@text AS INT)
              END
         END
    END

If you want to support positive and negative integers with any number of leading zeros:

SELECT 
         -- Positive integers (or 0):
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
              WHEN LEN(@text) >= 10 THEN
              CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
                    AND RIGHT(@text, 10) <= '2147483647'
                   THEN CAST (@text AS INT)
              END
         END
         -- Negative integers:
         WHEN LEFT(@text, 1) = '-' THEN
         CASE WHEN RIGHT(@text, LEN(@text) - 1) NOT LIKE '%[^0-9]%' THEN
              CASE WHEN LEN(@text) BETWEEN 2 AND 10 THEN CAST (@text AS INT)
                   WHEN LEN(@text) >= 11 THEN
                   CASE WHEN SUBSTRING(@text, 2, LEN(@text) - 11) NOT LIKE '%[^0]%'
                         AND RIGHT(@text, 10) <= '2147483648'
                        THEN CAST (@text AS INT)
                   END
              END
         END
    END

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

how to wait for first command to finish?

Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait, and wait short time in every loop. This will result in something like

max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
   if [ -f /tmp/st_new.tmp ]; then
      break # call results.sh outside loop
   else
      (( retry = retry + 1 ))
      sleep 1
   fi
done
if [ -f /tmp/st_new.tmp ]; then
   source ../../results.sh 
   rm -f /tmp/st_new.tmp
else
   echo Something wrong with st_new.sh
fi

What is the use of printStackTrace() method in Java?

printStackTrace() helps the programmer to understand where the actual problem occurred. printStacktrace() is a method of the class Throwable of java.lang package. It prints several lines in the output console. The first line consists of several strings. It contains the name of the Throwable sub-class & the package information. From second line onwards, it describes the error position/line number beginning with at.

The last line always describes the destination affected by the error/exception. The second last line informs us about the next line in the stack where the control goes after getting transfer from the line number described in the last line. The errors/exceptions represents the output in the form a stack, which were fed into the stack by fillInStackTrace() method of Throwable class, which itself fills in the program control transfer details into the execution stack. The lines starting with at, are nothing but the values of the execution stack. In this way the programmer can understand where in code the actual problem is.

Along with the printStackTrace() method, it's a good idea to use e.getmessage().

How to create a GUID in Excel?

This is not a problem with the function at all.

It took me a bit of digging, but the problem is in copying and pasting. Try copying this: RANDBETWEEN(0,6553??5) string, posted in your original question, and paste it into a Hex Editor, then you'll see that there are actually two null characters in the 65535:

00000000  52 41 4E 44 42 45 54 57 45 45 4E 28 30 2C 36 35  RANDBETWEEN(0,65
00000010  35 33 00 00 35 29                                53?..?5)

String to list in Python

>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']

split:

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].

phpmyadmin.pma_table_uiprefs doesn't exist

Steps:

  • Just download create_table.sql from GitHub and save that file in your system.
  • Then go to your phpMyAdmin.
  • And click on Import from upper tab.
  • At last select create_table.sql and upload that.

After all it works for me and hopefully work for you.

Logical XOR operator in C++?

The XOR operator cannot be short circuited; i.e. you cannot predict the result of an XOR expression just by evaluating its left hand operand. Thus, there's no reason to provide a ^^ version.

How to get the jQuery $.ajax error response text?

If you're not having a network error, and wanting to surface an error from the backend, for exmple insufficient privileges, server your response with a 200 and an error message. Then in your success handler check data.status == 'error'

Can you style an html radio button to look like a checkbox?

This is my solution using only CSS (Jsfiddle: http://jsfiddle.net/xykPT/).

enter image description here

_x000D_
_x000D_
div.options > label > input {_x000D_
 visibility: hidden;_x000D_
}_x000D_
_x000D_
div.options > label {_x000D_
 display: block;_x000D_
 margin: 0 0 0 -10px;_x000D_
 padding: 0 0 20px 0;  _x000D_
 height: 20px;_x000D_
 width: 150px;_x000D_
}_x000D_
_x000D_
div.options > label > img {_x000D_
 display: inline-block;_x000D_
 padding: 0px;_x000D_
 height:30px;_x000D_
 width:30px;_x000D_
 background: none;_x000D_
}_x000D_
_x000D_
div.options > label > input:checked +img {  _x000D_
 background: url(http://cdn1.iconfinder.com/data/icons/onebit/PNG/onebit_34.png);_x000D_
 background-repeat: no-repeat;_x000D_
 background-position:center center;_x000D_
 background-size:30px 30px;_x000D_
}
_x000D_
<div class="options">_x000D_
 <label title="item1">_x000D_
  <input type="radio" name="foo" value="0" /> _x000D_
  Item 1_x000D_
  <img />_x000D_
 </label>_x000D_
 <label title="item2">_x000D_
  <input type="radio" name="foo" value="1" />_x000D_
  Item 2_x000D_
  <img />_x000D_
 </label>   _x000D_
 <label title="item3">_x000D_
  <input type="radio" name="foo" value="2" />_x000D_
  Item 3_x000D_
  <img />_x000D_
 </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I center floated elements?

Set your container's width in px and add:

margin: 0 auto;

Reference.

Creating a border like this using :before And :after Pseudo-Elements In CSS?

See the following snippet, is this what you want?

_x000D_
_x000D_
body {
    background: silver;
    padding: 0 10px;
}

#content:after {
    height: 10px;
    display: block;
    width: 100px;
    background: #808080;
    border-right: 1px white;
    content: '';
}

#footer:before {
    display: block;
    content: '';
    background: silver;
    height: 10px;
    margin-top: -20px;
    margin-left: 101px;
}

#content {
    background: white;
}


#footer {
    padding-top: 10px;
    background: #404040;
}

p {
    padding: 100px;
    text-align: center;
}

#footer p {
    color: white;
}
_x000D_
<body>
    <div id="content"><p>#content</p></div>
    <div id="footer"><p>#footer</p></div>
</body>
_x000D_
_x000D_
_x000D_

JSFiddle

How can I find out the current route in Rails?

I find that the the approved answer, request.env['PATH_INFO'], works for getting the base URL, but this does not always contain the full path if you have nested routes. You can use request.env['HTTP_REFERER'] to get the full path and then see if it matches a given route:

request.env['HTTP_REFERER'].match?(my_cool_path)

GitLab git user password

I had the right public/private key, but seemed like it didn't work anyway (got same errors, prompting for the git-user password). After a computer-restart it worked though!

CSS two divs next to each other

The method suggested by @roe and @MohitNanda work, but if the right div is set as float:right;, then it must come first in the HTML source. This breaks the left-to-right read order, which could be confusing if the page is displayed with styles turned off. If that's the case, it might be better to use a wrapper div and absolute positioning:

<div id="wrap" style="position:relative;">
    <div id="left" style="margin-right:201px;border:1px solid red;">left</div>
    <div id="right" style="position:absolute;width:200px;right:0;top:0;border:1px solid blue;">right</div>
</div>

Demonstrated:

left right

Edit: Hmm, interesting. The preview window shows the correctly formatted divs, but the rendered post item does not. Sorry then, you'll have to try it for yourself.

use a javascript array to fill up a drop down select box

This is a part from a REST-Service I´ve written recently.

var select = $("#productSelect")
for (var prop in data) {
    var option = document.createElement('option');
    option.innerHTML = data[prop].ProduktName
    option.value = data[prop].ProduktName;
    select.append(option)
}

The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

I've encountered the same issue while following the React Native tutorial (developing on Linux and targeting Android).

This issue helped me resolve the problem in following steps. Run following commands in the below sequence:

  1. (in project directory) mkdir android/app/src/main/assets
  2. react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
  3. react-native run-android

You can automate the above steps by placing them in scripts part of package.json like this:

"android-linux": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android"

Then you can just execute npm run android-linux from your command line every time.

What's the strangest corner case you've seen in C# or .NET?

This one had me truly puzzled (I apologise for the length but it's WinForm). I posted it in the newsgroups a while back.

I've come across an interesting bug. I have workarounds but i'd like to know the root of the problem. I've stripped it down into a short file and hope someone might have an idea about what's going on.

It's a simple program that loads a control onto a form and binds "Foo" against a combobox ("SelectedItem") for it's "Bar" property and a datetimepicker ("Value") for it's "DateTime" property. The DateTimePicker.Visible value is set to false. Once it's loaded up, select the combobox and then attempt to deselect it by selecting the checkbox. This is rendered impossible by the combobox retaining the focus, you cannot even close the form, such is it's grasp on the focus.

I have found three ways of fixing this problem.

a) Remove the binding to Bar (a bit obvious)

b) Remove the binding to DateTime

c) Make the DateTimePicker visible !?!

I'm currently running Win2k. And .NET 2.00, I think 1.1 has the same problem. Code is below.

using System;
using System.Collections;
using System.Windows.Forms;

namespace WindowsApplication6
{
    public class Bar
    {
        public Bar()
        {
        }
    }

    public class Foo
    {
        private Bar m_Bar = new Bar();
        private DateTime m_DateTime = DateTime.Now;

        public Foo()
        {
        }

        public Bar Bar
        {
            get
            {
                return m_Bar;
            }
            set
            {
                m_Bar = value;
            }
        }

        public DateTime DateTime
        {
            get
            {
                return m_DateTime;
            }
            set
            {
                m_DateTime = value;
            }
        }
    }

    public class TestBugControl : UserControl
    {
        public TestBugControl()
        {
            InitializeComponent();
        }

        public void InitializeData(IList types)
        {
            this.cBoxType.DataSource = types;
        }

        public void BindFoo(Foo foo)
        {
            this.cBoxType.DataBindings.Add("SelectedItem", foo, "Bar");
            this.dtStart.DataBindings.Add("Value", foo, "DateTime");
        }

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            this.cBoxType = new System.Windows.Forms.ComboBox();
            this.dtStart = new System.Windows.Forms.DateTimePicker();
            this.SuspendLayout();
            //
            // checkBox1
            //
            this.checkBox1.AutoSize = true;
            this.checkBox1.Location = new System.Drawing.Point(14, 5);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(97, 20);
            this.checkBox1.TabIndex = 0;
            this.checkBox1.Text = "checkBox1";
            this.checkBox1.UseVisualStyleBackColor = true;
            //
            // cBoxType
            //
            this.cBoxType.FormattingEnabled = true;
            this.cBoxType.Location = new System.Drawing.Point(117, 3);
            this.cBoxType.Name = "cBoxType";
            this.cBoxType.Size = new System.Drawing.Size(165, 24);
            this.cBoxType.TabIndex = 1;
            //
            // dtStart
            //
            this.dtStart.Location = new System.Drawing.Point(117, 40);
            this.dtStart.Name = "dtStart";
            this.dtStart.Size = new System.Drawing.Size(165, 23);
            this.dtStart.TabIndex = 2;
            this.dtStart.Visible = false;
            //
            // TestBugControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.dtStart);
            this.Controls.Add(this.cBoxType);
            this.Controls.Add(this.checkBox1);
            this.Font = new System.Drawing.Font("Verdana", 9.75F,
            System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,
            ((byte)(0)));
            this.Margin = new System.Windows.Forms.Padding(4);
            this.Name = "TestBugControl";
            this.Size = new System.Drawing.Size(285, 66);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.CheckBox checkBox1;
        private System.Windows.Forms.ComboBox cBoxType;
        private System.Windows.Forms.DateTimePicker dtStart;
    }

    public class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += new EventHandler(Form1_Load);
        }

        void Form1_Load(object sender, EventArgs e)
        {
            InitializeControl();
        }

        public void InitializeControl()
        {
            TestBugControl control = new TestBugControl();
            IList list = new ArrayList();
            for (int i = 0; i < 10; i++)
            {
                list.Add(new Bar());
            }
            control.InitializeData(list);
            control.BindFoo(new Foo());
            this.Controls.Add(control);
        }

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Text = "Form1";
        }

        #endregion
    }

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

How best to read a File into List<string>

string inLine = reader.ReadToEnd();
myList = inLine.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();

I also use the Environment.NewLine.toCharArray as well, but found that didn't work on a couple files that did end in \r\n. Try either one and I hope it works well for you.

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, but you'll need to run it at the database level.

Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.

Screen shot of Advanced Scripting Options

What causes HttpHostConnectException?

You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document

Replace \n with <br />

I know this is an old thread but I tried the suggested answers and unfortunately simply replacing line breaks with <br /> didn't do what I needed it to. It simply rendered them literally as text.

One solution would have been to disable autoescape like this: {% autoescape false %}{{ mystring }}{% endautoescape %} and this works fine but this is no good if you have user-provided content. So this was also not a solution for me.

So this is what I used:

In Python:

newvar = mystring.split('\n')

And then, passing newvar into my Jinja template:

{% for line in newvar %}
    <br />{{ line }}
{% endfor %}

How to change a field name in JSON using Jackson

Be aware that there is org.codehaus.jackson.annotate.JsonProperty in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.

Export data from Chrome developer tool

I don't see an export or save as option.

I filtered out all the unwanted requests using -.css -.js -.woff then right clicked on one of the requests then Copy > Copy all as HAR

Then pasted the content into a text editor and saved it.

git ahead/behind info between master and branch?

First of all to see how many revisions you are behind locally, you should do a git fetch to make sure you have the latest info from your remote.

The default output of git status tells you how many revisions you are ahead or behind, but usually I find this too verbose:

$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 1 different commit each, respectively.
#
nothing to commit (working directory clean)

I prefer git status -sb:

$ git status -sb
## master...origin/master [ahead 2, behind 1]

In fact I alias this to simply git s, and this is the main command I use for checking status.

To see the diff in the "ahead revisions" of master, I can exclude the "behind revisions" from origin/master:

git diff master..origin/master^

To see the diff in the "behind revisions" of origin/master, I can exclude the "ahead revisions" from master:

git diff origin/master..master^^

If there are 5 revisions ahead or behind it might be easier to write like this:

git diff master..origin/master~5
git diff origin/master..master~5

UPDATE

To see the ahead/behind revisions, the branch must be configured to track another branch. For me this is the default behavior when I clone a remote repository, and after I push a branch with git push -u remotename branchname. My version is 1.8.4.3, but it's been working like this as long as I remember.

As of version 1.8, you can set the tracking branch like this:

git branch --track test-branch

As of version 1.7, the syntax was different:

git branch --set-upstream test-branch

How to skip to next iteration in jQuery.each() util?

The loop only breaks if you return literally false. Ex:

// this is how jquery calls your function
// notice hard comparison (===) against false
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
   break;
}

This means you can return anything else, including undefined, which is what you return if you return nothing, so you can simply use an empty return statement:

$.each(collection, function (index, item) {
   if (!someTestCondition)
      return; // go to next iteration

   // otherwise do something
});

It's possible this might vary by version; this is applicable for jquery 1.12.4. But really, when you exit out the bottom of the function, you are also returning nothing, and that's why the loop continues, so I would expect that there is no possibility whatsoever that returning nothing could not continue the loop. Unless they want to force everyone to start returning something to keep the loop going, returning nothing has to be a way to keep it going.

Set timeout for ajax (jQuery)

Please read the $.ajax documentation, this is a covered topic.

$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});

You can get see what type of error was thrown by accessing the textStatus parameter of the error: function(jqXHR, textStatus, errorThrown) option. The options are "timeout", "error", "abort", and "parsererror".

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

How to truncate float values?

If you fancy some mathemagic, this works for +ve numbers:

>>> v = 1.923328437452
>>> v - v % 1e-3
1.923

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

How do you comment an MS-access Query?

I know this question is very old, but I would like to add a few points, strangely omitted:

  1. you can right-click the query in the container, and click properties, and fill that with your description. The text you input that way is also accessible in design view, in the Descrption property
  2. Each field can be documented as well. Just make sure the properties window is open, then click the query field you want to document, and fill the Description (just above the too little known Format property)

It's a bit sad that no product (I know of) documents these query fields descriptions and expressions.

How to refresh the data in a jqGrid?

This worked for me.

jQuery('#grid').jqGrid('clearGridData');
jQuery('#grid').jqGrid('setGridParam', {data: dataToLoad});
jQuery('#grid').trigger('reloadGrid');

PowerShell: Run command from script's directory

Do you mean you want the script's own path so you can reference a file next to the script? Try this:

$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
Write-host "My directory is $dir"

You can get a lot of info from $MyInvocation and its properties.

If you want to reference a file in the current working directory, you can use Resolve-Path or Get-ChildItem:

$filepath = Resolve-Path "somefile.txt"

EDIT (based on comment from OP):

# temporarily change to the correct folder
Push-Location $folder

# do stuff, call ant, etc

# now back to previous directory
Pop-Location

There's probably other ways of achieving something similar using Invoke-Command as well.

Float a DIV on top of another DIV

What about:

.close-image{
    display:block;
    cursor:pointer;
    z-index:3;
    position:absolute;
    top:0;
    right:0;
}

Is that the desired result?

MVC Calling a view from a different controller

It is explained pretty well here: Display a view from another controller in ASP.NET MVC

To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

How to deselect all selected rows in a DataGridView control?

i have ran into the same problem and found a solution (not totally by myself, but there is the internet for)

Color blue  = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;

foreach (DataGridViewRow r in datagridIncome.Rows)
{
    if (r.Cells[5].Value.ToString().Contains("1")) { 
        r.DefaultCellStyle.BackColor = blue;
        r.DefaultCellStyle.SelectionBackColor = blue;
        r.DefaultCellStyle.SelectionForeColor = letters;
    }
    else { 
        r.DefaultCellStyle.BackColor = red;
        r.DefaultCellStyle.SelectionBackColor = red;
        r.DefaultCellStyle.SelectionForeColor = letters;
    }
}

This is a small trick, the only way you can see a row is selected, is by the very first column (not column[0], but the one therefore). When you click another row, you will not see the blue selection anymore, only the arrow indicates which row have selected. As you understand, I use rowSelection in my gridview.

Procedure or function !!! has too many arguments specified

You invoke the function with 2 parameters (@GenId and @Description):

EXEC etl.etl_M_Update_Promo @GenID, @Description

However you have declared the function to take 1 argument:

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0

SQL Server is telling you that [etl_M_Update_Promo] only takes 1 parameter (@GenId)

You can alter the procedure to take two parameters by specifying @Description.

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0,
    @Description NVARCHAR(50)
AS 

.... Rest of your code.

Difference between Select Unique and Select Distinct

Unique is a keyword used in the Create Table() directive to denote that a field will contain unique data, usually used for natural keys, foreign keys etc.

For example:

Create Table Employee(   
    Emp_PKey Int Identity(1, 1) Constraint PK_Employee_Emp_PKey Primary Key,  
    Emp_SSN Numeric Not Null Unique,  
    Emp_FName varchar(16),   
    Emp_LName varchar(16) 
)

i.e. Someone's Social Security Number would likely be a unique field in your table, but not necessarily the primary key.

Distinct is used in the Select statement to notify the query that you only want the unique items returned when a field holds data that may not be unique.

Select Distinct Emp_LName
From Employee

You may have many employees with the same last name, but you only want each different last name.

Obviously if the field you are querying holds unique data, then the Distinct keyword becomes superfluous.

How to change UIPickerView height

After a long day of scratching my head, I've found something that works for me. The codes below will recreate the UIDatePicker everytime the user change the phone orientation. This will remove whatever glitches that the UIDatePicker have after an orientation change.

Since we are recreating the UIDatePicker, we need an instance variable that will keep the selected date value. The codes below are tested on iOS 4.0.

    @interface AdvanceDateViewController : UIViewController<UIPickerViewDelegate> {
        UIDatePicker *datePicker;
        NSDate *date;
    }


    @property (nonatomic, retain) UIDatePicker *datePicker;
    @property (nonatomic, retain) NSDate *date;

    -(void)resizeViewWithOrientation:(UIInterfaceOrientation) orientation;

    @end

    @implementation AdvanceDateViewController
    @synthesize datePicker, date;

    - (void)viewDidLoad {
      [super viewDidLoad];
          [self resizeViewWithOrientation:self.interfaceOrientation];
    }


    -(void)viewWillAppear:(BOOL)animated{
         [super viewWillAppear:animated];
         [self resizeViewWithOrientation:self.interfaceOrientation];
     }

     - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
         return YES;
     }

     -(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
      [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
      [self resizeViewWithOrientation:toInterfaceOrientation];
      }

     -(void)resizeViewWithOrientation:(UIInterfaceOrientation) orientation{
          [self.datePicker removeFromSuperview];
          [self.datePicker removeTarget:self action:@selector(refreshPickupDate) forControlEvents:UIControlEventValueChanged];
          self.datePicker = nil;

          //(Re)initialize the datepicker, thanks to Apple's buggy UIDatePicker implementation
          UIDatePicker *dummyDatePicker = [[UIDatePicker alloc] init];
          self.datePicker = dummyDatePicker;
          [dummyDatePicker release];

          [self.datePicker setDate:self.date animated:YES];
          [self.datePicker addTarget:self action:@selector(refreshPickupDate) forControlEvents:UIControlEventValueChanged];

          if(UIInterfaceOrientationIsLandscape(orientation)){
                 self.datePicker.frame = CGRectMake(0, 118, 480, 162);    
           } else {
                 self.datePicker.frame = CGRectMake(0, 200, 320, 216);
           }

           [self.view addSubview:self.datePicker];
           [self.view setNeedsDisplay];
      }

      @end

jQuery change input text value

no, you need to do something like:

$('input.sitebg').val('000000');

but you should really be using unique IDs if you can.

You can also get more specific, such as:

$('input[type=text].sitebg').val('000000');

EDIT:

do this to find your input based on the name attribute:

$('input[name=sitebg]').val('000000');

Transpose a matrix in Python

If we wanted to return the same matrix we would write:

return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]

What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:

[[1,2,3],
[4,5,6],
[7,8,9]]

Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:

[[1,4,7],
[2,5,8],
[3,6,9]]

Therefore just switch the order in which we iterate:

return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]

How to remove a Gitlab project?

  1. Open project
  2. Setting (In the left sidebar)
  3. General
  4. Advanced Setting (Click on Expand)
  5. Remove Project (Bottom of the Page)
  6. Confirm (By typing project name and press Confirm button)

Is there a way to force npm to generate package-lock.json?

If your npm version is lower than version 5 then install the higher version for getting the automatic generation of package-lock.json.

Example: Upgrade your current npm to version 6.14.0

npm i -g [email protected]

You could view the latest npm version list by

npm view npm versions

Remote JMX connection

Had it been on Linux the problem would be that localhost is the loopback interface, you need to application to bind to your network interface.

You can use the netstat to confirm that it is not bound to the expected network interface.

You can make this work by invoking the program with the system parameter java.rmi.server.hostname="YOUR_IP", either as an environment variable or using

java -Djava.rmi.server.hostname=YOUR_IP YOUR_APP

Loop code for each file in a directory

Check out the DirectoryIterator class.

From one of the comments on that page:

// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

The recursive version is RecursiveDirectoryIterator.

Hide separator line on one UITableViewCell

For those looking specifically for hiding separator line of an Eureka row, this is the only solution that worked for me:

     row.cellUpdate { (cell, row) in
            cell.separatorInset =  UIEdgeInsets(top: 0, left: 0, bottom: 0, right: CGFloat.greatestFiniteMagnitude)
        }

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You can just use the Select() extension method:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

Or in LINQ syntax:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };

var strings = from i in integers
              select i.ToString();

How to calculate distance from Wifi router using Signal Strength?

K = 32.44
FSPL = Ptx - CLtx + AGtx + AGrx - CLrx - Prx - FM
d = 10 ^ (( FSPL - K - 20 log10( f )) / 20 )

Here:

  • K - constant (32.44, when f in MHz and d in km, change to -27.55 when f in MHz and d in m)
  • FSPL - Free Space Path Loss
  • Ptx - transmitter power, dBm ( up to 20 dBm (100mW) )
  • CLtx, CLrx - cable loss at transmitter and receiver, dB ( 0, if no cables )
  • AGtx, AGrx - antenna gain at transmitter and receiver, dBi
  • Prx - receiver sensitivity, dBm ( down to -100 dBm (0.1pW) )
  • FM - fade margin, dB ( more than 14 dB (normal) or more than 22 dB (good))
  • f - signal frequency, MHz
  • d - distance, m or km (depends on value of K)

Note: there is an error in formulas from TP-Link support site (mising ^).

Substitute Prx with received signal strength to get a distance from WiFi AP.

Example: Ptx = 16 dBm, AGtx = 2 dBi, AGrx = 0, Prx = -51 dBm (received signal strength), CLtx = 0, CLrx = 0, f = 2442 MHz (7'th 802.11bgn channel), FM = 22. Result: FSPL = 47 dB, d = 2.1865 m

Note: FM (fade margin) seems to be irrelevant here, but I'm leaving it because of the original formula.

You should take into acount walls, table http://www.liveport.com/wifi-signal-attenuation may help.

Example: (previous data) + one wooden wall ( 5 dB, from the table ). Result: FSPL = FSPL - 5 dB = 44 dB, d = 1.548 m

Also please note, that antena gain dosn't add power - it describes the shape of radiation pattern (donut in case of omnidirectional antena, zeppelin in case of directional antenna, etc).

None of this takes into account signal reflections (don't have an idea how to do this). Probably noise is also missing. So this math may be good only for rough distance estimation.

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

Easy:

SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

Pesonally tested on 10g ;-)

From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php

Find kth smallest element in a binary search tree in Optimum way

public int ReturnKthSmallestElement1(int k)
    {
        Node node = Root;

        int count = k;

        int sizeOfLeftSubtree = 0;

        while(node != null)
        {

            sizeOfLeftSubtree = node.SizeOfLeftSubtree();

            if (sizeOfLeftSubtree + 1 == count)
                return node.Value;
            else if (sizeOfLeftSubtree < count)
            {
                node = node.Right;
                count -= sizeOfLeftSubtree+1;
            }
            else
            {
                node = node.Left;
            }
        }

        return -1;
    }

this is my implementation in C# based on the algorithm above just thought I'd post it so people can understand better it works for me

thank you IVlad

Format SQL in SQL Server Management Studio

Late answer, but hopefully worthwhile: The Poor Man's T-SQL Formatter is an open-source (free) T-SQL formatter with complete T-SQL batch/script support (any DDL, any DML), SSMS Plugin, command-line bulk formatter, and other options.

It's available for immediate/online use at http://poorsql.com, and just today graduated to "version 1.0" (it was in beta version for a few months), having just acquired support for MERGE statements, OUTPUT clauses, and other finicky stuff.

The SSMS Add-in allows you to set your own hotkey (default is Ctrl-K, Ctrl-F, to match Visual Studio), and formats the entire script or just the code you have selected/highlighted, if any. Output formatting is customizable.

In SSMS 2008 it combines nicely with the built-in intelli-sense, effectively providing more-or-less the same base functionality as Red Gate's SQL Prompt (SQL Prompt does, of course, have extra stuff, like snippets, quick object scripting, etc).

Feedback/feature requests are more than welcome, please give it a whirl if you get the chance!

Disclosure: This is probably obvious already but I wrote this library/tool/site, so this answer is also shameless self-promotion :)

How should I validate an e-mail address?

Simplest way of Email Validation.

EditText TF;
public Button checkButton;

public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
          "[a-zA-Z0-9+._%-+]{1,256}" +
          "@" +
          "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" +
          "(" +
          "." +
          "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" +
          ")+"
      );
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

   TF=(EditText) findViewById(R.id.TF);
   checkButton=(Button) findViewById(R.id.checkButton);

    checkButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
           String email=TF.getText().toString();
           if(checkEmail(email))
              Toast.makeText(getApplicationContext(),"Valid Email Addresss", Toast.LENGTH_SHORT).show();
           else
              Toast.makeText(getApplicationContext(),"Invalid Email Addresss", Toast.LENGTH_SHORT).show();
    }
    });
}
private boolean checkEmail(String email) {
    return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}}

localhost refused to connect Error in visual studio

Same problem here but I think mine was due to installing the latest version of Visual Studio and having both 2015 and 2019 versions running the solution. I deleted the whole .vs folder and restarted Visual Studio and it worked.

I think the issue is that there are multiple configurations for each version of Visual Studio in the .vs folder and it seems to screw it up.

Razor View Without Layout

I think it's better work with individual "views", Im trying to move from PHP to MVC4, its really hard but im on the right way...

Answering your question, if you'll work individual pages, just edit the _ViewStart.cshtml

@{
  Layout = null;
}

Another tip if you're getting some issues with CSS path...

Put "../" before of the url

This are the 2 problems that i get today, and I resolve in that way!

Regards;

How to retrieve unique count of a field using Kibana + Elastic Search

Create "topN" query on "clientip" and then histogram with count on "clientip" and set "topN" query as source. Then you will see count of different ips per time.

Ubuntu apt-get unable to fetch packages

I tried this really interesting solution today, which worked for me on an Ubuntu server. Some DNS or another issue in the apt was making it adamant to not installing some packages from a custom PPA. What I did was install the apt-fast package and use it to install my packages instead of apt.

apt-fast is an alternative to apt which works on top of apt but uses aria2c to download packages. It is used to increase the download speed. In my case, it also solved whatever network problem was making apt to fail.

Using it is exactly the same as apt:

sudo apt-fast install package-name

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Check to see if the Remote Procedure Call (RPC) service is running. If it is, then it's a firewall issue between your workstation and the server. You can test it by temporary disabling the firewall and retrying the command.

Edit after comment:

Ok, it's a firewall issue. You'll have to either limit the ports WMI/RPC work on, or open a lot of ports in the McAfee firewall.

Here are a few sites that explain this:

  1. Microsoft KB for limiting ports
  2. McAfee site talking about the same thing

How do I negate a condition in PowerShell?

if you don't like the double brackets or you don't want to write a function, you can just use a variable.

$path = Test-Path C:\Code
if (!$path) {
    write "it doesn't exist!"
}

composer laravel create project

Dont write with stability stable in the command ,
in your composer.json file, put
"minimum-stability": "stable" before the closing curly bracket.

How to get value of checked item from CheckedListBox?

try:

  foreach (var item in chlCompanies.CheckedItems){
     item.Value //ID
     item.Text //CompanyName
  }

angular ng-repeat in reverse

That's because you are using JSON Object. When you face such problems then change your JSON Object to JSON Array Object.

For Example,

{"India":"IN","America":"US","United Kingdon":"UK"} json object
[{"country":"India","countryId":"IN"},{"country":"America","countryId":"US"},{"country":"United Kingdon","countryId":"UK"}] 

How to make return key on iPhone make keyboard disappear?

Swift 2 :

this is what is did to do every thing !

close keyboard with Done button or Touch outSide ,Next for go to next input.

First Change TextFiled Return Key To Next in StoryBoard.

override func viewDidLoad() {
  txtBillIdentifier.delegate = self
  txtBillIdentifier.tag = 1
  txtPayIdentifier.delegate  = self
  txtPayIdentifier.tag  = 2

  let tap = UITapGestureRecognizer(target: self, action: "onTouchGesture")
  self.view.addGestureRecognizer(tap)

}

func textFieldShouldReturn(textField: UITextField) -> Bool {
   if(textField.returnKeyType == UIReturnKeyType.Default) {
       if let next = textField.superview?.viewWithTag(textField.tag+1) as? UITextField {
           next.becomeFirstResponder()
           return false
       }
   }
   textField.resignFirstResponder()
   return false
}

func onTouchGesture(){
    self.view.endEditing(true)
}

Using two CSS classes on one element

I know this post is getting outdated, but here's what they asked. In your style sheet:

.social {
    width: 330px;
    height: 75px;
    float: right;
    text-align: left;
    padding: 10px 0;
    border-bottom: dotted 1px #6d6d6d;
}
[class~="first"] {
    padding-top:0;
}
[class~="last"] {
    border:0;
}

But it may be a bad way to use selectors. Also, if you need multiple "first" extension, you'll have to be sure to set different name, or to refine your selector.

[class="social first"] {...}

I hope this will help someone, it can be pretty handy in some situation.

For exemple, if you have a tiny piece of css that has to be linked to many different components, and you don't want to write a hundred time the same code.

div.myClass1 {font-weight:bold;}
div.myClass2 {font-style:italic;}
...
div.myClassN {text-shadow:silver 1px 1px 1px;}

div.myClass1.red {color:red;}
div.myClass2.red {color:red;}
...
div.myClassN.red {color:red;}

Becomes:

div.myClass1 {font-weight:bold;}
div.myClass2 {font-style:italic;}
...
div.myClassN {text-shadow:silver 1px 1px 1px;}

[class~=red] {color:red;}

How to dismiss a Twitter Bootstrap popover by clicking outside?

This has been asked before here. The same answer I gave then still applies:

I had a similar need, and found this great little extension of the Twitter Bootstrap Popover by Lee Carmichael, called BootstrapX - clickover. He also has some usage examples here. Basically it will change the popover into an interactive component which will close when you click elsewhere on the page, or on a close button within the popover. This will also allow multiple popovers open at once and a bunch of other nice features.

How ViewBag in ASP.NET MVC works

ViewBag is a dynamic type that allow you to dynamically set or get values and allow you to add any number of additional fields without a strongly-typed class They allow you to pass data from controller to view. In controller......

public ActionResult Index()
{
    ViewBag.victor = "My name is Victor";
    return View();
}

In view

@foreach(string a in ViewBag.victor)
{
     .........
}

What I have learnt is that both should have the save dynamic name property ie ViewBag.victor

Access parent DataContext from DataTemplate

I was searching how to do something similar in WPF and I got this solution:

<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <RadioButton 
            Content="{Binding}" 
            Command="{Binding Path=DataContext.CustomCommand, 
                        RelativeSource={RelativeSource Mode=FindAncestor,      
                        AncestorType={x:Type ItemsControl}} }"
            CommandParameter="{Binding}" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

I hope this works for somebody else. I have a data context which is set automatically to the ItemsControls, and this data context has two properties: MyItems -which is a collection-, and one command 'CustomCommand'. Because of the ItemTemplate is using a DataTemplate, the DataContext of upper levels is not directly accessible. Then the workaround to get the DC of the parent is use a relative path and filter by ItemsControl type.

XOR operation with two strings in java

This solution is compatible with Android (I've tested and used it myself). Thanks to @user467257 whose solution I adapted this from.

import android.util.Base64;

public class StringXORer {

public String encode(String s, String key) {
    return new String(Base64.encode(xorWithKey(s.getBytes(), key.getBytes()), Base64.DEFAULT));
}

public String decode(String s, String key) {
    return new String(xorWithKey(base64Decode(s), key.getBytes()));
}

private byte[] xorWithKey(byte[] a, byte[] key) {
    byte[] out = new byte[a.length];
    for (int i = 0; i < a.length; i++) {
        out[i] = (byte) (a[i] ^ key[i%key.length]);
    }
    return out;
}

private byte[] base64Decode(String s) {
    return Base64.decode(s,Base64.DEFAULT);
}

private String base64Encode(byte[] bytes) {
    return new String(Base64.encode(bytes,Base64.DEFAULT));

}
}

HTML Display Current date

I prefer to use

<input type='date' id='hasta' value='<?php echo date('Y-m-d');?>'>

that works well

Installing Java 7 on Ubuntu

PPA method no longer works.

While Oracle Java 6 and 7 are not supported for quite a while, they were still available for download on Oracle's website until recently.

However, the binaries were removed about 10 days ago (?), so the Oracle Java (JDK) 6 and 7 installers available in the WebUpd8 Oracle Java PPA no longer work.

Oracle Java 6 and 7 are now only available for those with an Oracle Support account (which is not free), so I can't support this for the PPA packages.

Source : http://www.webupd8.org/2017/06/why-oracle-java-7-and-6-installers-no.html Dated : June 2017

Oracle's download page says

Updates for Java SE 7 released after April 2015, and updates for Java SE 6 released after April 2013 are only available to Oracle Customers through My Oracle Support (requires support login).

Java SE Advanced offers users commercial features, access to critical bug fixes, security fixes, and general maintenance".

I had to download it from Oracle archives - http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

You need an account for this though.

How do you run `apt-get` in a dockerfile behind a proxy?

before any apt-get command in your Dockerfile you should put this line

COPY apt.conf /etc/apt/apt.conf

Dont'f forget to create apt.conf in the same folder that you have the Dockerfile, the content of the apt.conf file should be like this:

Acquire::socks::proxy "socks://YOUR-PROXY-IP:PORT/";
Acquire::http::proxy "http://YOUR-PROXY-IP:PORT/";
Acquire::https::proxy "http://YOUR-PROXY-IP:PORT/";

if you use username and password to connect to your proxy then the apt.conf should be like as below:

Acquire::socks::proxy "socks://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";
Acquire::http::proxy "http://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";
Acquire::https::proxy "http://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";

for example :

Acquire::https::proxy "http://foo:[email protected]:8080/";

Where the foo is the username and bar is the password.

CSS - Make divs align horizontally

This seems close to what you want:

_x000D_
_x000D_
#foo {_x000D_
  background: red;_x000D_
  max-height: 100px;_x000D_
  overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.bar {_x000D_
  background: blue;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  float: left;_x000D_
  margin: 1em;_x000D_
}
_x000D_
<div id="foo">_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
  <div class="bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I had the same problem:

curl -v -H "Content-Type: application/json" -X PUT -d '{"name":"json","surname":"gson","married":true,"age":32,"salary":123,"hasCar":true,"childs":["serkan","volkan","aybars"]}' XXXXXX/ponyo/UserModel/json

* About to connect() to localhost port 8081 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* connected
* Connected to localhost (127.0.0.1) port 8081 (#0)
> PUT /ponyo/UserModel/json HTTP/1.1
> User-Agent: curl/7.28.1
> Host: localhost:8081
> Accept: */*
> Content-Type: application/json
> Content-Length: 121
> 
* upload completely sent off: 121 out of 121 bytes
< HTTP/1.1 415 Unsupported Media Type
< Content-Type: text/html; charset=iso-8859-1
< Date: Wed, 09 Apr 2014 13:55:43 GMT
< Content-Length: 0
< 
* Connection #0 to host localhost left intact
* Closing connection #0

I resolved it by adding the dependency to pom.xml as follows. Please try it.

    <dependency>
        <groupId>com.owlike</groupId>
        <artifactId>genson</artifactId>
        <version>0.98</version>
    </dependency>

Find all controls in WPF Window by type

And this is how it works upwards

    private T FindParent<T>(DependencyObject item, Type StopAt) where T : class
    {
        if (item is T)
        {
            return item as T;
        }
        else
        {
            DependencyObject _parent = VisualTreeHelper.GetParent(item);
            if (_parent == null)
            {
                return default(T);
            }
            else
            {
                Type _type = _parent.GetType();
                if (StopAt != null)
                {
                    if ((_type.IsSubclassOf(StopAt) == true) || (_type == StopAt))
                    {
                        return null;
                    }
                }

                if ((_type.IsSubclassOf(typeof(T)) == true) || (_type == typeof(T)))
                {
                    return _parent as T;
                }
                else
                {
                    return FindParent<T>(_parent, StopAt);
                }
            }
        }
    }

Using Cookie in Asp.Net Mvc 4

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

You probably want

userCookie.Expires = DateTime.Now.AddDays(365); 

Multiple left-hand assignment with JavaScript

var var1 = 1, var2 = 1, var3 = 1;

In this case var keyword is applicable to all the three variables.

var var1 = 1,
    var2 = 1,
    var3 = 1;

which is not equivalent to this:

var var1 = var2 = var3 = 1;

In this case behind the screens var keyword is only applicable to var1 due to variable hoisting and rest of the expression is evaluated normally so the variables var2, var3 are becoming globals

Javascript treats this code in this order:

/*
var 1 is local to the particular scope because of var keyword
var2 and var3 will become globals because they've used without var keyword
*/

var var1;   //only variable declarations will be hoisted.

var1= var2= var3 = 1; 

Run PowerShell scripts on remote PC

After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:

PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2

Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

EDIT: dialog support was added to JavaFX, see https://stackoverflow.com/a/28887273/1054140


There were no common dialog support in a year 2011. You had to write it yourself by creating new Stage():

Stage dialogStage = new Stage();
dialogStage.initModality(Modality.WINDOW_MODAL);

VBox vbox = new VBox(new Text("Hi"), new Button("Ok."));
vbox.setAlignment(Pos.CENTER);
vbox.setPadding(new Insets(15));

dialogStage.setScene(new Scene(vbox));
dialogStage.show();

ASP.NET MVC Razor pass model to layout

old question but just to mention the solution for MVC5 developers, you can use the Model property same as in view.

The Model property in both view and layout is assosiated with the same ViewDataDictionary object, so you don't have to do any extra work to pass your model to the layout page, and you don't have to declare @model MyModelName in the layout.

But notice that when you use @Model.XXX in the layout the intelliSense context menu will not appear because the Model here is a dynamic object just like ViewBag.

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

Even though the <head> and <body> tags aren't required, the elements are still there - it's just that the browser can work out where the tags would have been from the rest of the document.

The other elements you're using still have to be inside the <body>

Difference between web reference and service reference?

A Web Reference allows you to communicate with any service based on any technology that implements the WS-I Basic Profile 1.1, and exposes the relevant metadata as WSDL. Internally, it uses the ASMX communication stack on the client's side.

A Service Reference allows you to communicate with any service based on any technology that implements any of the many protocols supported by WCF (including but not limited to WS-I Basic Profile). Internally, it uses the WCF communication stack on the client side.

Note that both these definitions are quite wide, and both include services not written in .NET.

It is perfectly possible (though not recommended) to add a Web Reference that points to a WCF service, as long as the WCF endpoint uses basicHttpBinding or some compatible custom variant.

It is also possible to add a Service Reference that points to an ASMX service. When writing new code, you should always use a Service Reference simply because it is more flexible and future-proof.

TypeError: $(...).autocomplete is not a function

you missed jquery ui library. Use CDN of Jquery UI or if you want it locally then download the file from Jquery Ui

<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="YourJquery source path"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

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

var myLength = $("#myTextbox").val().length;

Correct location of openssl.cnf file

RHEL: /etc/pki/tls/openssl.cnf

Is Secure.ANDROID_ID unique for each device?

There are multiple solution exist but none of them perfect. let's go one by one.

1. Unique Telephony Number (IMEI, MEID, ESN, IMSI)

  • This solution needs to request for android.permission.READ_PHONE_STATE to your user which can be hard to justify following the type of application you have made.

  • Furthermore, this solution is limited to smartphones because tablets don’t have telephony services. One advantage is that the value survives to factory resets on devices.

2. MAC Address

  • You can also try to get a MAC Address from a device having a Wi-Fi or Bluetooth hardware. But, this solution is not recommended because not all of the device have Wi-Fi connection. Even if the user have a Wi-Fi connection, it must be turned on to retrieve the data. Otherwise, the call doesn’t report the MAC Address.

3. Serial Number

  • Devices without telephony services like tablets must report a unique device ID that is available via android.os.Build.SERIAL since Android 2.3 Gingerbread. Some phones having telephony services can also define a serial number. Like not all Android devices have a Serial Number, this solution is not reliable.

4. Secure Android ID

  • On a device first boot, a randomly value is generated and stored. This value is available via Settings.Secure.ANDROID_ID . It’s a 64-bit number that should remain constant for the lifetime of a device. ANDROID_ID seems a good choice for a unique device identifier because it’s available for smartphones and tablets.

    String androidId = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
    
  • However, the value may change if a factory reset is performed on the device. There is also a known bug with a popular handset from a manufacturer where every instance have the same ANDROID_ID. Clearly, the solution is not 100% reliable.

5. Use UUID

  • As the requirement for most of applications is to identify a particular installation and not a physical device, a good solution to get unique id for an user if to use UUID class. The following solution has been presented by Reto Meier from Google in a Google I/O presentation :

    private static String uniqueID = null;
    private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
    public synchronized static String id(Context context) {
       if (uniqueID == null) {
           SharedPreferences sharedPrefs = context.getSharedPreferences(
                   PREF_UNIQUE_ID, Context.MODE_PRIVATE);
           uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
           if (uniqueID == null) {
               uniqueID = UUID.randomUUID().toString();
               Editor editor = sharedPrefs.edit();
               editor.putString(PREF_UNIQUE_ID, uniqueID);
               editor.commit();
           }
       }    return uniqueID;
    }
    

Identify a particular device on Android is not an easy thing. There are many good reasons to avoid that. Best solution is probably to identify a particular installation by using UUID solution. credit : blog

Inconsistent Accessibility: Parameter type is less accessible than method

Try making your constructor private like this:

private Foo newClass = new Foo();

How do you replace double quotes with a blank space in Java?

You don't need regex for this. Just a character-by-character replace is sufficient. You can use String#replace() for this.

String replaced = original.replace("\"", " ");

Note that you can also use an empty string "" instead to replace with. Else the spaces would double up.

String replaced = original.replace("\"", "");

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

Strings as Primary Keys in SQL Database

It doesn't matter what you use as a primary key so long as it is UNIQUE. If you care about speed or good database design use the int unless you plan on replicating data, then use a GUID.

If this is an access database or some tiny app then who really cares. I think the reason why most of us developers slap the old int or guid at the front is because projects have a way of growing on us, and you want to leave yourself the option to grow.

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

How to get value from form field in django framework?

I use django 1.7+ and python 2.7+, the solution above dose not work. And the input value in the form can be got use POST as below (use the same form above):

if form.is_valid():
  data = request.POST.get('my_form_field_name')
  print data

Hope this helps.

View RDD contents in Python Spark?

Try this:

data = f.flatMap(lambda x: x.split(' '))
map = data.map(lambda x: (x, 1))
mapreduce = map.reduceByKey(lambda x,y: x+y)
result = mapreduce.collect()

Please note that when you run collect(), the RDD - which is a distributed data set is aggregated at the driver node and is essentially converted to a list. So obviously, it won't be a good idea to collect() a 2T data set. If all you need is a couple of samples from your RDD, use take(10).

Biggest differences of Thrift vs Protocol Buffers?

Protocol Buffers seems to have a more compact representation, but that's only an impression I get from reading the Thrift whitepaper. In their own words:

We decided against some extreme storage optimizations (i.e. packing small integers into ASCII or using a 7-bit continuation format) for the sake of simplicity and clarity in the code. These alterations can easily be made if and when we encounter a performance-critical use case that demands them.

Also, it may just be my impression, but Protocol Buffers seems to have some thicker abstractions around struct versioning. Thrift does have some versioning support, but it takes a bit of effort to make it happen.

Get year, month or day from numpy datetime64

As datetime is not stable in numpy I would use pandas for this:

In [52]: import pandas as pd

In [53]: dates = pd.DatetimeIndex(['2010-10-17', '2011-05-13', "2012-01-15"])

In [54]: dates.year
Out[54]: array([2010, 2011, 2012], dtype=int32)

Pandas uses numpy datetime internally, but seems to avoid the shortages, that numpy has up to now.

String.format() to format double in java

public class MainClass {
   public static void main(String args[]) {
    System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);

    System.out.printf("Default floating-point format: %f\n", 1234567.123);
    System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
    System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
    System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);

    System.out.printf("Line-up positive and negative values:\n");
    System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
  }
}

And print out:

3 (3) +3 00003
Default floating-point format: 1234567,123000
Floating-point with commas: 1.234.567,123000
Negative floating-point default: -1.234.567,123000
Negative floating-point option: (1.234.567,123000)

Line-up positive and negative values:
1.234.567,12
-1.234.567,12

Checking if a variable is an integer

Use a regular expression on a string:

def is_numeric?(obj) 
   obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end

If you want to check if a variable is of certain type, you can simply use kind_of?:

1.kind_of? Integer #true
(1.5).kind_of? Float #true
is_numeric? "545"  #true
is_numeric? "2aa"  #false

Android emulator failed to allocate memory 8

This error fires if you set the AVD RAM to anything that is larger then the single largest block of continuous memory the emulator is able to allocate. Close anything RAM heavy, start your emulator, start everything else you need. In a previous answer I have limited this to x86 images with IntelHAXM, but this actually is the case for all types of emulator instances.

SQL Server 2005 How Create a Unique Constraint?

ALTER TABLE [TableName] ADD CONSTRAINT  [constraintName] UNIQUE ([columns])

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

see NSURLError.h Define

NSURLErrorUnknown =             -1,
NSURLErrorCancelled =           -999,
NSURLErrorBadURL =              -1000,
NSURLErrorTimedOut =            -1001,
NSURLErrorUnsupportedURL =          -1002,
NSURLErrorCannotFindHost =          -1003,
NSURLErrorCannotConnectToHost =         -1004,
NSURLErrorNetworkConnectionLost =       -1005,
NSURLErrorDNSLookupFailed =         -1006,
NSURLErrorHTTPTooManyRedirects =        -1007,
NSURLErrorResourceUnavailable =         -1008,
NSURLErrorNotConnectedToInternet =      -1009,
NSURLErrorRedirectToNonExistentLocation =   -1010,
NSURLErrorBadServerResponse =       -1011,
NSURLErrorUserCancelledAuthentication =     -1012,
NSURLErrorUserAuthenticationRequired =  -1013,
NSURLErrorZeroByteResource =        -1014,
NSURLErrorCannotDecodeRawData =             -1015,
NSURLErrorCannotDecodeContentData =         -1016,
NSURLErrorCannotParseResponse =             -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist =        -1100,
NSURLErrorFileIsDirectory =         -1101,
NSURLErrorNoPermissionsToReadFile =     -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103,

// SSL errors
NSURLErrorSecureConnectionFailed =      -1200,
NSURLErrorServerCertificateHasBadDate =     -1201,
NSURLErrorServerCertificateUntrusted =  -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid =    -1204,
NSURLErrorClientCertificateRejected =   -1205,
NSURLErrorClientCertificateRequired =   -1206,
NSURLErrorCannotLoadFromNetwork =       -2000,

// Download and file I/O errors
NSURLErrorCannotCreateFile =        -3000,
NSURLErrorCannotOpenFile =          -3001,
NSURLErrorCannotCloseFile =         -3002,
NSURLErrorCannotWriteToFile =       -3003,
NSURLErrorCannotRemoveFile =        -3004,
NSURLErrorCannotMoveFile =          -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,

NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021,

NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,

How to add external library in IntelliJ IDEA?

I've used this process to attach a 3rd party Jar to an Android project in IDEA.

  • Copy the Jar to your libs/ directory
  • Open Project Settings (Ctrl Alt Shift S)
  • Under the Project Settings panel on the left, choose Modules
  • On the larger right pane, choose the Dependencies tab
  • Press the Add... button on the far right of the screen (if you have a smaller screen like me, you may have to drag resize to the right in order to see it)
  • From the dropdown of Add options, choose "Library". A "Choose Libraries" dialog will appear.
  • Press "New Library..."
  • Choose a suitable title for the library
  • Press "Attach Classes..."
  • Choose the Jar from your libs/ directory, and press OK to dismiss

The library should now be recognised.

Align DIV's to bottom or baseline

The answer posted by Y. Shoham (using absolute positioning) seems to be the simplest solution in most cases where the container is a fixed height, but if the parent DIV has to contain multiple DIVs and auto adjust it's height based on dynamic content, then there can be a problem. I needed to have two blocks of dynamic content; one aligned to the top of the container and one to the bottom and although I could get the container to adjust to the size of the top DIV, if the DIV aligned to the bottom was taller, it would not resize the container but would extend outside. The method outlined above by romiem using table style positioning, although a bit more complicated, is more robust in this respect and allowed alignment to the bottom and correct auto height of the container.

CSS

#container {
        display: table;
        height: auto;
}

#top {
    display: table-cell;
    width:50%;
    height: 100%;
}

#bottom {
    display: table-cell;
    width:50%;
    vertical-align: bottom;
    height: 100%;
}

HTML

<div id=“container”>
    <div id=“top”>Dynamic content aligned to top of #container</div>
    <div id=“bottom”>Dynamic content aligned to botttom of #container</div>
</div>

Example

I realise this is not a new answer but I wanted to comment on this approach as it lead me to find my solution but as a newbie I was not allowed to comment, only post.

How to set up gradle and android studio to do release build?

To activate the installRelease task, you simply need a signingConfig. That is all.

From http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Android-tasks:

Finally, the plugin creates install/uninstall tasks for all build types (debug, release, test), as long as they can be installed (which requires signing).

Here is what you want:

Install tasks
-------------
installDebug - Installs the Debug build
installDebugTest - Installs the Test build for the Debug build
installRelease - Installs the Release build
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build
uninstallDebugTest - Uninstalls the Test build for the Debug build
uninstallRelease - Uninstalls the Release build   <--- release

Here is how to obtain the installRelease task:

Example build.gradle:

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
    }
}

apply plugin: 'com.android.application'

android {
  compileSdkVersion 22
  buildToolsVersion '22.0.1'

  defaultConfig {
    applicationId 'demo'
    minSdkVersion 15
    targetSdkVersion 22
    versionCode 1
    versionName '1.0'
  }

  signingConfigs {
      release {
          storeFile <file>
          storePassword <password>
          keyAlias <alias>
          keyPassword <password>
      }
  }

  buildTypes {
    release {
        signingConfig signingConfigs.release
    }
  }
}

How do I specify a password to 'psql' non-interactively?

  • in one line:

    export PGPASSWORD='password'; psql -h 'server name' -U 'user name' -d 'base name' -c 'command'
    

    with command a sql command such as "select * from schema.table"

  • or more readable:

    export PGPASSWORD='password'
    psql -h 'server name' -U 'user name' -d 'base name' \
         -c 'command' (eg. "select * from schema.table")
    

How to convert a date String to a Date or Calendar object?

In brief:

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
try {
  Date date = formatter.parse("01/29/02");
} catch (ParseException e) {
  e.printStackTrace();
}

See SimpleDateFormat javadoc for more.

And to turn it into a Calendar, do:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

How can I check Drupal log files?

To view entries in Drupal's own internal log system (the watchdog database table), go to http://example.com/admin/reports/dblog. These can include Drupal-specific errors as well as general PHP or MySQL errors that have been thrown.

Use the watchdog() function to add an entry to this log from your own custom module.

When Drupal bootstraps it uses the PHP function set_error_handler() to set its own error handler for PHP errors. Therefore, whenever a PHP error occurs within Drupal it will be logged through the watchdog() call at admin/reports/dblog. If you look for PHP fatal errors, for example, in /var/log/apache/error.log and don't see them, this is why. Other errors, e.g. Apache errors, should still be logged in /var/log, or wherever you have it configured to log to.

Byte Array to Image object

BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

Run a PHP file in a cron job using CPanel

It is actually very simple,

php -q /home/username/public_html/cron/cron.php

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

Clearing input in vuejs form

This solution is only for components

If we toggle(show/hide) components using booleans then data is also removed. No need to clean the form fields.

I usually make components and initialize them using booleans. e.g.

<template>
    <button @click="show_create_form = true">Add New Record</button
    <create-form v-if="show_create_form" />
</template>


<script>
...
data(){
   return{
       show_create_form:false //making it false by default
   }
},
methods:{
    submitForm(){
      //...
      this.axios.post('/submit-form-url',data,config)
           .then((response) => {
               this.show_create_form= false; //hide it again after success.
               //if you now click on add new record button then it will show you empty form
           }).catch((error) => {
              //
           })
    }
}
...
</script>

When use clicks on edit button then this boolean becomes true and after successful submit I change it to false again.

How to set time zone in codeigniter?

Add this line inside the main index.php of codeigniter folder

date_default_timezone_set('Asia/Kolkata');

Reading inputStream using BufferedReader.readLine() is too slow

I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader's fault. Try measuring this:

InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing

I think you'll find it's almost exactly the same time as when you're parsing the text.

Note that you should also give InputStreamReader an appropriate encoding - the platform default encoding is almost certainly not what you should be using.

How to convert an ArrayList containing Integers to primitive int array?

If you are using there's also another way to do this.

int[] arr = list.stream().mapToInt(i -> i).toArray();

What it does is:

  • getting a Stream<Integer> from the list
  • obtaining an IntStream by mapping each element to itself (identity function), unboxing the int value hold by each Integer object (done automatically since Java 5)
  • getting the array of int by calling toArray

You could also explicitly call intValue via a method reference, i.e:

int[] arr = list.stream().mapToInt(Integer::intValue).toArray();

It's also worth mentioning that you could get a NullPointerException if you have any null reference in the list. This could be easily avoided by adding a filtering condition to the stream pipeline like this:

                       //.filter(Objects::nonNull) also works
int[] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray();

Example:

List<Integer> list = Arrays.asList(1, 2, 3, 4);
int[] arr = list.stream().mapToInt(i -> i).toArray(); //[1, 2, 3, 4]

list.set(1, null); //[1, null, 3, 4]
arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); //[1, 3, 4]

Setting table column width

Alternative way with just one class while keeping your styles in a CSS file, which even works in IE7:

<table class="mytable">
    <tr>
        <th>From</th>
        <th>Subject</th>
        <th>Date</th>
    </tr>
</table>
<style>
    .mytable td, .mytable th { width:15%; }
    .mytable td + td, .mytable th + th { width:70%; }
    .mytable td + td + td, .mytable th + th + th { width:15%; }
</style>

More recently, you can also use the nth-child() selector from CSS3 (IE9+), where you'd just put the nr. of the respective column into the parenthesis instead of stringing them together with the adjacent selector. Like this, for example:

<style>
    .mytable tr > *:nth-child(1) { width:15%; }
    .mytable tr > *:nth-child(2) { width:70%; }
    .mytable tr > *:nth-child(3) { width:15%; }
</style>

Types in Objective-C on iOS

This is a good overview:

http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html

or run this code:

32 bit process:

  NSLog(@"Primitive sizes:");
  NSLog(@"The size of a char is: %d.", sizeof(char));
  NSLog(@"The size of short is: %d.", sizeof(short));
  NSLog(@"The size of int is: %d.", sizeof(int));
  NSLog(@"The size of long is: %d.", sizeof(long));
  NSLog(@"The size of long long is: %d.", sizeof(long long));
  NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
  NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
  NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
  NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
  NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
  NSLog(@"The size of a float is: %d.", sizeof(float));
  NSLog(@"The size of a double is %d.", sizeof(double));

  NSLog(@"Ranges:");
  NSLog(@"CHAR_MIN:   %c",   CHAR_MIN);
  NSLog(@"CHAR_MAX:   %c",   CHAR_MAX);
  NSLog(@"SHRT_MIN:   %hi",  SHRT_MIN);    // signed short int
  NSLog(@"SHRT_MAX:   %hi",  SHRT_MAX);
  NSLog(@"INT_MIN:    %i",   INT_MIN);
  NSLog(@"INT_MAX:    %i",   INT_MAX);
  NSLog(@"LONG_MIN:   %li",  LONG_MIN);    // signed long int
  NSLog(@"LONG_MAX:   %li",  LONG_MAX);
  NSLog(@"ULONG_MAX:  %lu",  ULONG_MAX);   // unsigned long int
  NSLog(@"LLONG_MIN:  %lli", LLONG_MIN);   // signed long long int
  NSLog(@"LLONG_MAX:  %lli", LLONG_MAX);
  NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX);  // unsigned long long int

When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:

Primitive sizes:
The size of a char is: 1.                
The size of short is: 2.                 
The size of int is: 4.                   
The size of long is: 4.                  
The size of long long is: 8.             
The size of a unsigned char is: 1.       
The size of unsigned short is: 2.        
The size of unsigned int is: 4.          
The size of unsigned long is: 4.         
The size of unsigned long long is: 8.    
The size of a float is: 4.               
The size of a double is 8.               
Ranges:                                  
CHAR_MIN:   -128                         
CHAR_MAX:   127                          
SHRT_MIN:   -32768                       
SHRT_MAX:   32767                        
INT_MIN:    -2147483648                  
INT_MAX:    2147483647                   
LONG_MIN:   -2147483648                  
LONG_MAX:   2147483647                   
ULONG_MAX:  4294967295                   
LLONG_MIN:  -9223372036854775808         
LLONG_MAX:  9223372036854775807          
ULLONG_MAX: 18446744073709551615 

64 bit process:

The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

git am error: "patch does not apply"

This kind of error can be caused by LF vs CRLF line ending mismatches, e.g. when you're looking at the patch file and you're absolutely sure it should be able to apply, but it just won't.

To test this out, if you have a patch that applies to just one file, you can try running 'unix2dos' or 'dos2unix' on just that file (try both, to see which one causes the file to change; you can get these utilities for Windows as well as Unix), then commit that change as a test commit, then try applying the patch again. If that works, that was the problem.

NB git am applies patches as LF by default (even if the patch file contains CRLF), so if you want to apply CRLF patches to CRLF files you must use git am --keep-cr, as per this answer.

Is it possible only to declare a variable without assigning any value in Python?

You look like you're trying to write C in Python. If you want to find something in a sequence, Python has builtin functions to do that, like

value = sequence.index(blarg)

git remove merge commit from history

Starting with the repo in the original state

Original repo history

To remove the merge commit and squash the branch into a single commit in the mainline

Squashed commits, no merge commit

Use these commands (replacing 5 and 1 with the SHAs of the corresponding commits):

git checkout 5
git reset --soft 1
git commit --amend -m '1 2 3 4 5'
git rebase HEAD master

To retain a merge commit but squash the branch commits into one:

Squashed commits, retained merge commit

Use these commands (replacing 5, 1 and C with the SHAs of the corresponding commits):

git checkout -b tempbranch 5
git reset --soft 1
git commit --amend -m '1 2 3 4 5'
git checkout C
git merge --no-ff tempbranch
git rebase HEAD master

To remove the merge commit and replace it with individual commits from the branch

Branch moved into mainline, no merge commit

Just do (replacing 5 with the SHA of the corresponding commit):

git rebase 5 master

And finally, to remove the branch entirely

Branch removed entirely

Use this command (replacing C and D with the SHAs of the corresponding commits):

git rebase --onto C D~ master

Editing an item in a list<T>

public changeAttr(int id)
{
    list.Find(p => p.IdItem == id).FieldToModify = newValueForTheFIeld;
}

With:

  • IdItem is the id of the element you want to modify

  • FieldToModify is the Field of the item that you want to update.

  • NewValueForTheField is exactly that, the new value.

(It works perfect for me, tested and implemented)

How can I check if PostgreSQL is installed or not via Linux script?

There is no single simple way to do it, because PostgreSQL might be installed and set up in many different ways:

  • Installed from source in a user home directory
  • Installed from source into /opt or /usr/local, manually started or started by an init script
  • Installed from distributor rpm / deb packages and started via init script
  • Installed from 3rd party rpm / deb packages and started via init script
  • Installed from packages but not set to start
  • Client installed, connecting to a server on a different computer
  • Installed and running but not on the default PATH or default port

You can't rely on psql being on the PATH. You can't rely on there being only one psql on the system (multiple versions might be installed in different ways). You can't do it based on port, as there's no guarantee it's on port 5432, or that there aren't multiple versions.

Prompt the user and ask them.

Update statement using with clause

The WITH syntax appears to be valid in an inline view, e.g.

UPDATE (WITH comp AS ...
        SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
   SET SomeColumn=ComputedValue;

But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.

You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:

MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;

But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING clause arbitrarily complex, incorporating multiple WITH clauses.

Check existence of directory and create if doesn't exist

In terms of general architecture I would recommend the following structure with regard to directory creation. This will cover most potential issues and any other issues with directory creation will be detected by the dir.create call.

mainDir <- "~"
subDir <- "outputDirectory"

if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
    cat("subDir exists in mainDir and is a directory")
} else if (file.exists(paste(mainDir, subDir, sep = "/", collapse = "/"))) {
    cat("subDir exists in mainDir but is a file")
    # you will probably want to handle this separately
} else {
    cat("subDir does not exist in mainDir - creating")
    dir.create(file.path(mainDir, subDir))
}

if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
    # By this point, the directory either existed or has been successfully created
    setwd(file.path(mainDir, subDir))
} else {
    cat("subDir does not exist")
    # Handle this error as appropriate
}

Also be aware that if ~/foo doesn't exist then a call to dir.create('~/foo/bar') will fail unless you specify recursive = TRUE.

What can cause a “Resource temporarily unavailable” on sock send() command

Let'e me give an example:

  1. client connect to server, and send 1MB data to server every 1 second.

  2. server side accept a connection, and then sleep 20 second, without recv msg from client.So the tcp send buffer in the client side will be full.

Code in client side:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...)                                                                          \
    if (r) {                                                                                     \
        printf(__VA_ARGS__);                                                                     \
        printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
        exit(1);                                                                                 \
    }

void setNonBlock(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    exit_if(flags < 0, "fcntl failed");
    int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    exit_if(r < 0, "fcntl failed");
}

void test_full_sock_buf_1(){
    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;


    int fd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(fd<0, "create socket error");

    int ret = connect(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(ret<0, "connect to server error");
    setNonBlock(fd);

    printf("connect to server success");

    const int LEN = 1024 * 1000;
    char msg[LEN];  // 1MB data
    memset(msg, 'a', LEN);

    for (int i = 0; i < 1000; ++i) {
        int len = send(fd, msg, LEN, 0);
        printf("send: %d, erron: %d, %s \n", len, errno, strerror(errno));
        sleep(1);
    }

}

int main(){
    test_full_sock_buf_1();

    return 0;
}

Code in server side:

    #include <arpa/inet.h>
    #include <sys/socket.h>
    #include <stdio.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <string.h>
    #define exit_if(r, ...)                                                                          \
        if (r) {                                                                                     \
            printf(__VA_ARGS__);                                                                     \
            printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
            exit(1);                                                                                 \
        }
void test_full_sock_buf_1(){

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(listenfd<0, "create socket error");

    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;

    int r = ::bind(listenfd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(r<0, "bind socket error");

    r = listen(listenfd, 100);
    exit_if(r<0, "listen socket error");

    struct sockaddr_in raddr;
    socklen_t rsz = sizeof(raddr);
    int cfd = accept(listenfd, (struct sockaddr *) &raddr, &rsz);
    exit_if(cfd<0, "accept socket error");

    sockaddr_in peer;
    socklen_t alen = sizeof(peer);
    getpeername(cfd, (sockaddr *) &peer, &alen);

    printf("accept a connection from %s:%d\n", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));

    printf("but now I will sleep 15 second, then exit");
    sleep(15);
}

Start server side, then start client side.

server side may output:

accept a connection from 127.0.0.1:35764
but now I will sleep 15 second, then exit
Process finished with exit code 0

enter image description here

client side may output:

connect to server successsend: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 552190, erron: 0, Success 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 104, Connection reset by peer 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 

enter image description here

You can see, as the server side doesn't recv the data from client, so when the client side tcp buffer get full, but you still send data, so you may get Resource temporarily unavailable error.

How do I get column datatype in Oracle with PL-SQL with low privileges?

The best solution that I've found for such case is

select column_name, data_type||
case
when data_precision is not null and nvl(data_scale,0)>0 then '('||data_precision||','||data_scale||')'
when data_precision is not null and nvl(data_scale,0)=0 then '('||data_precision||')'
when data_precision is null and data_scale is not null then '(*,'||data_scale||')'
when char_length>0 then '('||char_length|| case char_used 
                                                         when 'B' then ' Byte'
                                                         when 'C' then ' Char'
                                                         else null 
                                           end||')'
end||decode(nullable, 'N', ' NOT NULL')
from user_tab_columns
where table_name = 'TABLE_NAME'
and column_name = 'COLUMN_NAME';

@Aaron Stainback, thank you for correction!

Update data on a page without refreshing

In general, if you don't know how something works, look for an example which you can learn from.

For this problem, consider this DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it. Good luck.

You can find the corresponding tutorial HERE

Update

Right now the following event starts the ajax load function:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);) the content is updated.

You can also just load the data immediately:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.

OpenSSL Command to check if a server is presenting a certificate

I had a similar issue. The root cause was that the sending IP was not in the range of white-listed IPs on the receiving server. So, all requests for communication were killed by the receiving site.

How to escape special characters of a string with single backslashes

We could use built-in function repr() or string interpolation fr'{}' escape all backwardslashs \ in Python 3.7.*

repr('my_string') or fr'{my_string}'

Check the Link: https://docs.python.org/3/library/functions.html#repr

serialize/deserialize java 8 java.time with Jackson JSON mapper

Update: Leaving this answer for historical reasons, but I don't recommend it. Please see the accepted answer above.

Tell Jackson to map using your custom [de]serialization classes:

@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime ignoreUntil;

provide custom classes:

public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
    @Override
    public void serialize(LocalDateTime arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException {
        arg1.writeString(arg0.toString());
    }
}

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    @Override
    public LocalDateTime deserialize(JsonParser arg0, DeserializationContext arg1) throws IOException {
        return LocalDateTime.parse(arg0.getText());
    }
}

random fact: if i nest above classes and don't make them static, the error message is weird: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported

Empty ArrayList equals null

First of all, You can verify this on your own by writing a simple TestCase!

empty Arraylist (with nulls as its items)

Second, If ArrayList is EMPTY that means it is really empty, it cannot have NULL or NON-NULL things as element.

Third,

 List list  = new ArrayList();
    list.add(null);
    System.out.println(list == null)

would print false.

c++ array assignment of multiple values

There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.

Here is what you can do:

#include <algorithm>

int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);

However, in C++0x, you can do this:

std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};

Of course, if you choose to use std::vector instead of raw array.

How to include a child object's child object in Entity Framework 5

If you include the library System.Data.Entity you can use an overload of the Include() method which takes a lambda expression instead of a string. You can then Select() over children with Linq expressions rather than string paths.

return DatabaseContext.Applications
     .Include(a => a.Children.Select(c => c.ChildRelationshipType));

how to redirect to home page

window.location.href = "/";

This worked for me. If you have multiple folders/directories, you can use this:

window.location.href = "/folder_name/";

Disabling the long-running-script message in Internet Explorer

The unresponsive script dialog box shows when some javascript thread takes too long too complete. Editing the registry could work, but you would have to do it on all client machines. You could use a "recursive closure" as follows to alleviate the problem. It's just a coding structure in which allows you to take a long running for loop and change it into something that does some work, and keeps track where it left off, yielding to the browser, then continuing where it left off until we are done.

Figure 1, Add this Utility Class RepeatingOperation to your javascript file. You will not need to change this code:

RepeatingOperation = function(op, yieldEveryIteration) {

  //keeps count of how many times we have run heavytask() 
  //before we need to temporally check back with the browser.
  var count = 0;   

  this.step = function() {

    //Each time we run heavytask(), increment the count. When count
    //is bigger than the yieldEveryIteration limit, pass control back 
    //to browser and instruct the browser to immediately call op() so
    //we can pick up where we left off.  Repeat until we are done.
    if (++count >= yieldEveryIteration) {
      count = 0;

      //pass control back to the browser, and in 1 millisecond, 
      //have the browser call the op() function.  
      setTimeout(function() { op(); }, 1, [])

      //The following return statement halts this thread, it gives 
      //the browser a sigh of relief, your long-running javascript
      //loop has ended (even though technically we havn't yet).
      //The browser decides there is no need to alarm the user of
      //an unresponsive javascript process.
      return;
      }
    op();
  };
};

Figure 2, The following code represents your code that is causing the 'stop running this script' dialog because it takes so long to complete:

process10000HeavyTasks = function() {
  var len = 10000;  
  for (var i = len - 1; i >= 0; i--) {
    heavytask();   //heavytask() can be run about 20  times before
                   //an 'unresponsive script' dialog appears.
                   //If heavytask() is run more than 20 times in one
                   //javascript thread, the browser informs the user that
                   //an unresponsive script needs to be dealt with.  

                   //This is where we need to terminate this long running
                   //thread, instruct the browser not to panic on an unresponsive
                   //script, and tell it to call us right back to pick up
                   //where we left off.
  }
}

Figure 3. The following code is the fix for the problematic code in Figure 2. Notice the for loop is replaced with a recursive closure which passes control back to the browser every 10 iterations of heavytask()

process10000HeavyTasks = function() {

  var global_i = 10000; //initialize your 'for loop stepper' (i) here.

  var repeater = new this.RepeatingOperation(function() {

    heavytask();

    if (--global_i >= 0){     //Your for loop conditional goes here.
      repeater.step();        //while we still have items to process,
                              //run the next iteration of the loop.
    }
    else {
       alert("we are done");  //when this line runs, the for loop is complete.
    }
  }, 10);                   //10 means process 10 heavytask(), then
                            //yield back to the browser, and have the
                            //browser call us right back.

  repeater.step();          //this command kicks off the recursive closure.

};

Adapted from this source:

http://www.picnet.com.au/blogs/Guido/post/2010/03/04/How-to-prevent-Stop-running-this-script-message-in-browsers

PHP Warning: PHP Startup: Unable to load dynamic library

Note that you can also get this error if your PHP library doesn't have the "other" directory opening permission. In my particular case, I noticed this when using php -l to syntax check a script in my text editor. This meant that since my account was called "volomike", that account didn't have permission to run the libraries that the php command relied upon.

For instance, on Ubuntu 14.04, I had PHP5 installed automatically into the path /usr/lib/php5/20121212+lfs. However, because I was working in C++ in building some shared objects, I messed around with the directory permissions and screwed things up such that non-root accounts did not have the directory execute (directory open) permissions to view /usr/lib/php5/20121212+lfs. So, I typed the following command to rectify that problem:

sudo chmod o+x /usr/lib/php5/20121212+lfs.

Now when I do php -l example.php as a non-root user, it never gives me this "Unabled to load dynamic library" problem anymore.

AngularJs ReferenceError: angular is not defined

I ran into this because I made a copy-and-paste of ngBoilerplate into my project on a Mac without Finder showing hidden files. So .bower was not copied with the rest of ngBoilerplate. Thus bower moved resources to bower_components (defult) instead of vendor (as configured) and my app didn't get angular. Probably a corner case, but it might help someone here.

If else embedding inside html

In @Patrick McMahon's response, the second comment here ( $first_condition is false and $second_condition is true ) is not entirely accurate:

<?php if($first_condition): ?>
  /*$first_condition is true*/
  <div class="first-condition-true">First Condition is true</div>
<?php elseif($second_condition): ?>
  /*$first_condition is false and $second_condition is true*/
  <div class="second-condition-true">Second Condition is true</div>
<?php else: ?>
  /*$first_condition and $second_condition are false*/
  <div class="first-and-second-condition-false">Conditions are false</div>
<?php endif; ?>

Elseif fires whether $first_condition is true or false, as do additional elseif statements, if there are multiple.

I am no PHP expert, so I don't know whether that's the correct way to say IF this OR that ELSE that or if there is another/better way to code it in PHP, but this would be an important distinction to those looking for OR conditions versus ELSE conditions.

Source is w3schools.com and my own experience.

How to check that Request.QueryString has a specific value or not in ASP.NET?

You can just check for null:

if(Request.QueryString["aspxerrorpath"]!=null)
{
   //your code that depends on aspxerrorpath here
}

jQuery issue - #<an Object> has no method

This problem can also arise if you include jQuery more than once.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

Here a code that works with windows office 2010. This script will ask you for input filtered range of cells and then the paste range.

Please, both ranges should have the same number of cells.

Sub Copy_Filtered_Cells()

Dim from As Variant
Dim too As Variant
Dim thing As Variant
Dim cell As Range

'Selection.SpecialCells(xlCellTypeVisible).Select

    'Set from = Selection.SpecialCells(xlCellTypeVisible)
    Set temp = Application.InputBox("Copy Range :", Type:=8)
    Set from = temp.SpecialCells(xlCellTypeVisible)
    Set too = Application.InputBox("Select Paste range selected cells ( Visible cells only)", Type:=8)



    For Each cell In from
        cell.Copy
        For Each thing In too
            If thing.EntireRow.RowHeight > 0 Then
                thing.PasteSpecial
                Set too = thing.Offset(1).Resize(too.Rows.Count)
                Exit For
            End If
        Next
    Next


End Sub

Enjoy!

Passing an array to a query using a WHERE clause

Safe way without PDO:

$ids = array_filter(array_unique(array_map('intval', (array)$ids)));

if ($ids) {
    $query = 'SELECT * FROM `galleries` WHERE `id` IN ('.implode(',', $ids).');';
}
  • (array)$ids Cast $ids variable to array
  • array_map Transform all array values into integers
  • array_unique Remove repeated values
  • array_filter Remove zero values
  • implode Join all values to IN selection

How to print out the method name and line number and conditionally disable NSLog?

It's easy to change your existing NSLogs to display line number and class from which they are called. Add one line of code to your prefix file:

#define NSLog(__FORMAT__, ...) NSLog((@"%s [Line %d] " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

Return a value if no rows are found in Microsoft tSQL

You should avoid using expensive methods. You don't need any column for TBL2.

SELECT COUNT(*) FROM(
         SELECT TOP 1     1 AS CNT  FROM  TBL1 
         WHERE ColumnValue ='FooDoo') AS TBL2

Or this code:

IF EXISTS (SELECT TOP 1 1 FROM TABLE1 AS T1 
                          WHERE T1.ColumnValue='VooDoo') 
   SELECT 1 
ELSE 
   SELECT 0
 

Best Practices for mapping one object to another

This is a possible generic implementation using a bit of reflection (pseudo-code, don't have VS now):

public class DtoMapper<DtoType>
{
    Dictionary<string,PropertyInfo> properties;

    public DtoMapper()
    {
        // Cache property infos
        var t = typeof(DtoType);
        properties = t.GetProperties().ToDictionary(p => p.Name, p => p);
     }

    public DtoType Map(Dto dto)
    {
        var instance = Activator.CreateInstance(typeOf(DtoType));

        foreach(var p in properties)
        {
            p.SetProperty(
                instance, 
                Convert.Type(
                    p.PropertyType, 
                    dto.Items[Array.IndexOf(dto.ItemsNames, p.Name)]);

            return instance;
        }
    }

Usage:

var mapper = new DtoMapper<Model>();
var modelInstance = mapper.Map(dto);

This will be slow when you create the mapper instance but much faster later.

How to detect tableView cell touched or clicked in swift

This worked good for me:

_x000D_
_x000D_
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {_x000D_
        print("section: \(indexPath.section)")_x000D_
        print("row: \(indexPath.row)")_x000D_
    }
_x000D_
_x000D_
_x000D_

The output should be:

section: 0
row: 0

Split large string in n-size chunks in JavaScript

Include both left and right version with pre-allocation. This is as fast as RegExp impl for small chunks but it goes faster as the chunk size grows. And it is memory efficent.

function chunkLeft (str, size = 3) {
  if (typeof str === 'string') {
    const length = str.length
    const chunks = Array(Math.ceil(length / size))
    for (let i = 0, index = 0; index < length; i++) {
      chunks[i] = str.slice(index, index += size)
    }
    return chunks
  }
}

function chunkRight (str, size = 3) {
  if (typeof str === 'string') {
    const length = str.length
    const chunks = Array(Math.ceil(length / size))
    if (length) {
      chunks[0] = str.slice(0, length % size || size)
      for (let i = 1, index = chunks[0].length; index < length; i++) {
        chunks[i] = str.slice(index, index += size)
      }
    }
    return chunks
  }
}

console.log(chunkRight())  // undefined
console.log(chunkRight(''))  // []
console.log(chunkRight('1'))  // ["1"]
console.log(chunkRight('123'))  // ["123"]
console.log(chunkRight('1234'))  // ["1", "234"]
console.log(chunkRight('12345'))  // ["12", "345"]
console.log(chunkRight('123456'))  // ["123", "456"]
console.log(chunkRight('1234567'))  // ["1", "234", "567"]

How to programmatically tell if a Bluetooth device is connected?

BluetoothAdapter.getDefaultAdapter().isEnabled -> returns true when bluetooth is open

val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager

audioManager.isBluetoothScoOn -> returns true when device connected

How to find if a native DLL file is compiled as x64 or x86?

For an unmanaged DLL file, you need to first check if it is a 16-bit DLL file (hopefully not). Then check the IMAGE\_FILE_HEADER.Machine field.

Someone else took the time to work this out already, so I will just repeat here:

To distinguish between a 32-bit and 64-bit PE file, you should check IMAGE_FILE_HEADER.Machine field. Based on the Microsoft PE and COFF specification below, I have listed out all the possible values for this field: http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/pecoff_v8.doc

IMAGE_FILE_MACHINE_UNKNOWN 0x0 The contents of this field are assumed to be applicable to any machine type

IMAGE_FILE_MACHINE_AM33 0x1d3 Matsushita AM33

IMAGE_FILE_MACHINE_AMD64 0x8664 x64

IMAGE_FILE_MACHINE_ARM 0x1c0 ARM little endian

IMAGE_FILE_MACHINE_EBC 0xebc EFI byte code

IMAGE_FILE_MACHINE_I386 0x14c Intel 386 or later processors and compatible processors

IMAGE_FILE_MACHINE_IA64 0x200 Intel Itanium processor family

IMAGE_FILE_MACHINE_M32R 0x9041 Mitsubishi M32R little endian

IMAGE_FILE_MACHINE_MIPS16 0x266 MIPS16

IMAGE_FILE_MACHINE_MIPSFPU 0x366 MIPS with FPU

IMAGE_FILE_MACHINE_MIPSFPU16 0x466 MIPS16 with FPU

IMAGE_FILE_MACHINE_POWERPC 0x1f0 Power PC little endian

IMAGE_FILE_MACHINE_POWERPCFP 0x1f1 Power PC with floating point support

IMAGE_FILE_MACHINE_R4000 0x166 MIPS little endian

IMAGE_FILE_MACHINE_SH3 0x1a2 Hitachi SH3

IMAGE_FILE_MACHINE_SH3DSP 0x1a3 Hitachi SH3 DSP

IMAGE_FILE_MACHINE_SH4 0x1a6 Hitachi SH4

IMAGE_FILE_MACHINE_SH5 0x1a8 Hitachi SH5

IMAGE_FILE_MACHINE_THUMB 0x1c2 Thumb

IMAGE_FILE_MACHINE_WCEMIPSV2 0x169 MIPS little-endian WCE v2

Yes, you may check IMAGE_FILE_MACHINE_AMD64|IMAGE_FILE_MACHINE_IA64 for 64bit and IMAGE_FILE_MACHINE_I386 for 32bit.

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Add the "code" folder to the project properties within Visual Studio

Project->Properties->Configuration Properties->C/C++->Additional Include Directories

How to trigger ngClick programmatically

You can do like

$timeout(function() {
   angular.element('#btn2').triggerHandler('click');
});

What is setup.py?

setup.py is a python file, the presence of which is an indication that the module/package you are about to install has likely been packaged and distributed with Distutils, which is the standard for distributing Python Modules.

This allows you to easily install Python packages. Often it's enough to write:

$ pip install . 

pip will use setup.py to install your module. Avoid calling setup.py directly.

https://docs.python.org/3/installing/index.html#installing-index

How do I pass a variable by reference?

There are no variables in Python

The key to understanding parameter passing is to stop thinking about "variables". There are names and objects in Python and together they appear like variables, but it is useful to always distinguish the three.

  1. Python has names and objects.
  2. Assignment binds a name to an object.
  3. Passing an argument into a function also binds a name (the parameter name of the function) to an object.

That is all there is to it. Mutability is irrelevant to this question.

Example:

a = 1

This binds the name a to an object of type integer that holds the value 1.

b = x

This binds the name b to the same object that the name x is currently bound to. Afterward, the name b has nothing to do with the name x anymore.

See sections 3.1 and 4.2 in the Python 3 language reference.

How to read the example in the question

In the code shown in the question, the statement self.Change(self.variable) binds the name var (in the scope of function Change) to the object that holds the value 'Original' and the assignment var = 'Changed' (in the body of function Change) assigns that same name again: to some other object (that happens to hold a string as well but could have been something else entirely).

How to pass by reference

So if the thing you want to change is a mutable object, there is no problem, as everything is effectively passed by reference.

If it is an immutable object (e.g. a bool, number, string), the way to go is to wrap it in a mutable object.
The quick-and-dirty solution for this is a one-element list (instead of self.variable, pass [self.variable] and in the function modify var[0]).
The more pythonic approach would be to introduce a trivial, one-attribute class. The function receives an instance of the class and manipulates the attribute.

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

If you are using macOS, add both Android SDK emulator and tools directories to the path:

Step 1: In my case the order was important, first emulator and then tools.

export ANDROID_SDK=$HOME/Library/Android/sdk
export PATH=$ANDROID_SDK/emulator:$ANDROID_SDK/tools:$PATH

Step 2: Reload you .bash_profile Or .bashrc depending on OS

Step 3: Get list of emulators available: $emulator -list-avds

Step 4: Launch emulator from the command line and Replace avd with the name of your emulator $emulator @avd

Don't forget to add the @ symbol.

This was tested with macOS High Sierra 10.13.4 and Android Studio 3.1.2.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Exit codes in Python

From the documentation for sys.exit:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.

One example where exit codes are used are in shell scripts. In Bash you can check the special variable $? for the last exit status:

me@mini:~$ python -c ""; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(0)"; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(43)"; echo $?
43

Personally I try to use the exit codes I find in /usr/include/asm-generic/errno.h (on a Linux system), but I don't know if this is the right thing to do.

How to get a list of all files in Cloud Storage in a Firebase app?

I faced the same issue, mine is even more complicated.

Admin will upload audio and pdf files into storage:

  • audios/season1, season2.../class1, class 2/.mp3 files

  • books/.pdf files

Android app needs to get the list of sub folders and files.

The solution is catching the upload event on storage and create the same structure on firestore using cloud function.

Step 1: Create manually 'storage' collection and 'audios/books' doc on firestore

enter image description here

Step 2: Setup cloud function

Might take around 15 mins: https://www.youtube.com/watch?v=DYfP-UIKxH0&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=1

Step 3: Catch upload event using cloud function

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
const path = require('path');

export const onFileUpload = functions.storage.object().onFinalize(async (object) => {
        let filePath = object.name; // File path in the bucket.
        const contentType = object.contentType; // File content type.
        const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
        if (metageneration !== "1") return;

        // Get the file name.
        const fileName = path.basename(filePath);
        filePath = filePath.substring(0, filePath.length - 1);
        console.log('contentType ' + contentType);
        console.log('fileName ' + fileName);
        console.log('filePath ' + filePath);
        console.log('path.dirname(filePath) ' + path.dirname(filePath));
        filePath = path.dirname(filePath);
        const pathArray = filePath.split("/");
        let ref = '';
        for (const item of pathArray) {
            if (ref.length === 0) {
                ref = item;
            }
            else {
                ref = ref.concat('/sub/').concat(item);
            }
        }

        ref = 'storage/'.concat(ref).concat('/sub')
        admin.firestore().collection(ref).doc(fileName).create({})
                .then(result => {console.log('onFileUpload:updated')})
                .catch(error => {
                    console.log(error);
                });
    });

Step 4: Retrieve list of folders/files on Android app using firestore

private static final String STORAGE_DOC = "storage/";
    public static void getMediaCollection(String path, OnCompleteListener onCompleteListener) {
        String[] pathArray = path.split("/");
        String doc = null;
        for (String item : pathArray) {
            if (TextUtils.isEmpty(doc)) doc = STORAGE_DOC.concat(item);
            else doc = doc.concat("/sub/").concat(item);
        }
        doc = doc.concat("/sub");

        getFirestore().collection(doc).get().addOnCompleteListener(onCompleteListener);
    }

Step 5: Get download url

public static void downloadMediaFile(String path, OnCompleteListener<Uri> onCompleteListener) {
        getStorage().getReference().child(path).getDownloadUrl().addOnCompleteListener(onCompleteListener);
    }

Note

We have to put "sub" collection to each item since firestore doesn't support to retrieve the list of collection.

It took me 3 days to find out the solution, hopefully will take you 3 hours at most.

Cheers.

How do I tokenize a string sentence in NLTK?

As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

If your sentence is truly simple enough:

Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y

Retrieving an element from array list in Android?

In arraylist you have a positional order and not a nominal order, so you need to know in advance the element position you need to select or you must loop between elements until you find the element that you need to use. To do this you can use an iterator and an if, for example:

Iterator iter = list.iterator();
while (iter.hasNext())
{
    // if here          
    System.out.println("string " + iter.next());
}

How can I get a channel ID from YouTube?

At any channel page with "user" url for example http://www.youtube.com/user/klauskkpm, without API call, from YouTube UI, click a video of the channel (in its "VIDEOS" tab) and click the channel name on the video. Then you can get to the page with its "channel" url for example https://www.youtube.com/channel/UCfjTOrCPnAblTngWAzpnlMA.

javascript onclick increment number

Check this out.

_x000D_
_x000D_
var timeout_;

function mouseDown_i() {
  value = isNaN(parseInt(document.getElementById('xxxx').value)) ? 0 : parseInt(document.getElementById('xxxx').value);
  document.getElementById('xxxx').value = value + 1;  
  timeout_ = setTimeout(function() { mouseDown_i(); }, 150);
}

function mouseDown_d() {
  value = isNaN(parseInt(document.getElementById('xxxx').value)) ? 0 : parseInt(document.getElementById('xxxx').value);
  value - 1 <= 0 ? document.getElementById('xxxx').value = '' : document.getElementById('xxxx').value = value - 1;  
  timeout_ = setTimeout(function() { mouseDown_d(); }, 150);
}

function mouseUp() { clearTimeout(timeout_); }

function mouseLeave() { clearTimeout(timeout_); }
_x000D_
<p onmousedown="mouseDown_i()" onmouseup="mouseUp()" onmouseleave="mouseLeave()">Click to INCREMENT!</p>
<p onmousedown="mouseDown_d()" onmouseup="mouseUp()" onmouseleave="mouseLeave()">Click to DECREMENT!</p>
<input id="xxxx" type="text" value="0">
_x000D_
_x000D_
_x000D_

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

I had the same problem and I found this solution working with bindParam :

    bindParam(':param', $myvar = NULL, PDO::PARAM_INT);

How do I attach events to dynamic HTML elements with jQuery?

You can bind a single click event to a page for all elements, no matter if they are already on that page or if they will arrive at some future time, like that:

$(document).bind('click', function (e) {
   var target = $(e.target);
   if (target.is('.myclass')) {
      e.preventDefault(); // if you want to cancel the event flow
      // do something
   } else if (target.is('.myotherclass')) {
      e.preventDefault();
      // do something else
   }
});

Been using it for a while. Works like a charm.

In jQuery 1.7 and later, it is recommended to use .on() in place of bind or any other event delegation method, but .bind() still works.

Amazon S3 - HTTPS/SSL - Is it possible?

payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:

https://s3-<region>.amazonaws.com/your.domain.com/some/asset

Where <region> is the bucket location name. For example, if your bucket is in the us-west-2 (Oregon) region, you can do this:

https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset

Correct way of getting Client's IP Addresses from http.Request

This is how I come up with the IP

func ReadUserIP(r *http.Request) string {
    IPAddress := r.Header.Get("X-Real-Ip")
    if IPAddress == "" {
        IPAddress = r.Header.Get("X-Forwarded-For")
    }
    if IPAddress == "" {
        IPAddress = r.RemoteAddr
    }
    return IPAddress
}
  • X-Real-Ip - fetches first true IP (if the requests sits behind multiple NAT sources/load balancer)

  • X-Forwarded-For - if for some reason X-Real-Ip is blank and does not return response, get from X-Forwarded-For

  • Remote Address - last resort (usually won't be reliable as this might be the last ip or if it is a naked http request to server ie no load balancer)

call a function in success of datatable ajax call

The best way I have found is to use the initComplete method as it fires after the data has been retrieved and renders the table. NOTE this only fires once though.

$("#tableOfData").DataTable({
        "pageLength": 50,
        "ajax":{
            url: someurl,
            dataType : "json",
            type: "post",
            "data": {data to be sent}
        },
        "initComplete":function( settings, json){
            console.log(json);
            // call your function here
        }
    });

How do I concatenate two strings in C?

David Heffernan explained the issue in his answer, and I wrote the improved code. See below.

A generic function

We can write a useful variadic function to concatenate any number of strings:

#include <stdlib.h>       // calloc
#include <stdarg.h>       // va_*
#include <string.h>       // strlen, strcpy

char* concat(int count, ...)
{
    va_list ap;
    int i;

    // Find required length to store merged string
    int len = 1; // room for NULL
    va_start(ap, count);
    for(i=0 ; i<count ; i++)
        len += strlen(va_arg(ap, char*));
    va_end(ap);

    // Allocate memory to concat strings
    char *merged = calloc(sizeof(char),len);
    int null_pos = 0;

    // Actually concatenate strings
    va_start(ap, count);
    for(i=0 ; i<count ; i++)
    {
        char *s = va_arg(ap, char*);
        strcpy(merged+null_pos, s);
        null_pos += strlen(s);
    }
    va_end(ap);

    return merged;
}

Usage

#include <stdio.h>        // printf

void println(char *line)
{
    printf("%s\n", line);
}

int main(int argc, char* argv[])
{
    char *str;

    str = concat(0);             println(str); free(str);
    str = concat(1,"a");         println(str); free(str);
    str = concat(2,"a","b");     println(str); free(str);
    str = concat(3,"a","b","c"); println(str); free(str);

    return 0;
}

Output:

  // Empty line
a
ab
abc

Clean-up

Note that you should free up the allocated memory when it becomes unneeded to avoid memory leaks:

char *str = concat(2,"a","b");
println(str);
free(str);

ReactJs: What should the PropTypes be for this.props.children?

Try something like this utilizing oneOfType or PropTypes.node

import PropTypes from 'prop-types'

...

static propTypes = {
    children: PropTypes.oneOfType([
        PropTypes.arrayOf(PropTypes.node),
        PropTypes.node
    ]).isRequired
}

or

static propTypes = {
    children: PropTypes.node.isRequired,
}

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

I'm going to answer the literal question: no, there isn't a good reason you see VARCHAR(255) used so often (there are indeed reasons, as discussed in the other answers, just not good ones). You won't find many examples of projects that have failed catastrophically because the architect chose VARCHAR(300) instead of VARCHAR(255). This would be an issue of near-total insignificance even if you were talking about CHAR instead of VARCHAR.

jQuery AJAX Call to PHP Script with JSON Return

Your datatype is wrong, change datatype for dataType.

Wait one second in running program

Wait function using timers, no UI locks.

public void wait(int milliseconds)
{
    var timer1 = new System.Windows.Forms.Timer();
    if (milliseconds == 0 || milliseconds < 0) return;

    // Console.WriteLine("start wait timer");
    timer1.Interval = milliseconds;
    timer1.Enabled  = true;
    timer1.Start();

    timer1.Tick += (s, e) =>
    {
        timer1.Enabled = false;
        timer1.Stop();
        // Console.WriteLine("stop wait timer");
    };

    while (timer1.Enabled)
    {
        Application.DoEvents();
    }
}

Usage: just placing this inside your code that needs to wait:

wait(1000); //wait one second

jQuery prevent change for select

You can do this without jquery...

<select onchange="event.target.selectedIndex = 0">
...
</select>

or you can do a function to check your condition

<select onchange="check(event)">
...
</select>

<script>
function check(e){
    if (my_condition){
        event.target.selectedIndex = 0;
    }
}
</script>

Ctrl+click doesn't work in Eclipse Juno

Please check your .classpath file as well. Some times Eclipse do not redirect when using "ctrl+click" to Class or method if classpath is not proper. I had faced same issue in Eclipse Mars but it got resolved when I got proper .classpath file at my work location.

ASP.Net MVC - Read File from HttpPostedFileBase without save

This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here

You should convert the stream into byte array and then you can read file content

Please refer following link

http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]

Hope this helps

UPDATE :

The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array.

Taken from here

// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);

string result = System.Text.Encoding.UTF8.GetString(binData);

Angular: date filter adds timezone, how to output UTC?

The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.

Borrowing from this answer, you could do something like this without moment.js:

controller

var app1 = angular.module('app1',[]);

app1.controller('ctrl',['$scope',function($scope){

  var toUTCDate = function(date){
    var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    return _utc;
  };

  var millisToUTCDate = function(millis){
    return toUTCDate(new Date(millis));
  };

    $scope.toUTCDate = toUTCDate;
    $scope.millisToUTCDate = millisToUTCDate;

  }]);

template

<html ng-app="app1">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="ctrl">
      <div>
      utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
      </div>
      <div>
      local {{1400167800 | date:'dd-M-yyyy H:mm'}}
      </div>
    </div>
  </body>

</html>

here's plunker to play with it

See also this and this.

Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.

How to update single value inside specific array item in redux

I'm afraid that using map() method of an array may be expensive since entire array is to be iterated. Instead, I combine a new array that consists of three parts:

  • head - items before the modified item
  • the modified item
  • tail - items after the modified item

Here the example I've used in my code (NgRx, yet the machanism is the same for other Redux implementations):

// toggle done property: true to false, or false to true

function (state, action) {
    const todos = state.todos;
    const todoIdx = todos.findIndex(t => t.id === action.id);

    const todoObj = todos[todoIdx];
    const newTodoObj = { ...todoObj, done: !todoObj.done };

    const head = todos.slice(0, todoIdx - 1);
    const tail = todos.slice(todoIdx + 1);
    const newTodos = [...head, newTodoObj, ...tail];
}

Detect whether a Python string is a number or a letter

Check if string is positive digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False

Check for strings as positive/negative - integer/float

str.isdigit() returns False if the string is a negative number or a float number. For example:

# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False

If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

def is_number(n):
    try:
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

Sample Run:

>>> is_number('123')    # positive integer number
True

>>> is_number('123.4')  # positive float number
True
 
>>> is_number('-123')   # negative integer number
True

>>> is_number('-123.4') # negative `float` number
True

>>> is_number('abc')    # `False` for "some random" string
False

Discard "NaN" (not a number) strings while checking for number

The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

>>> is_number('NaN')
True

In order to check whether the number is "NaN", you may use math.isnan() as:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)
True

Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False

Hence, above function is_number can be updated to return False for "NaN" as:

def is_number(n):
    is_number = True
    try:
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan')   # not a number string "nan" with all lower cased
False

>>> is_number('123')   # positive integer
True

>>> is_number('-123')  # negative integer
True

>>> is_number('-1.12') # negative `float`
True

>>> is_number('abc')   # "some random" string
False

Allow Complex Number like "1+2j" to be treated as valid number

The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:

def is_number(n):
    is_number = True
    try:
        #      v type-casting the number here as `complex`, instead of `float`
        num = complex(n)
        is_number = num == num
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('1+2j')    # Valid 
True                     #      : complex number 

>>> is_number('1+ 2j')   # Invalid 
False                    #      : string with space in complex number represetantion
                         #        is treated as invalid complex number

>>> is_number('123')     # Valid
True                     #      : positive integer

>>> is_number('-123')    # Valid 
True                     #      : negative integer

>>> is_number('abc')     # Invalid 
False                    #      : some random string, not a valid number

>>> is_number('nan')     # Invalid
False                    #      : not a number "nan" string

PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

Crop image in android

Can you use default android Crop functionality?

Here is my code

private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties here
        cropIntent.putExtra("crop", true);
        // indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        // indicate output X and Y
        cropIntent.putExtra("outputX", 128);
        cropIntent.putExtra("outputY", 128);
        // retrieve data on return
        cropIntent.putExtra("return-data", true);
        // start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

declare:

final int PIC_CROP = 1;

at top.

In onActivity result method, writ following code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PIC_CROP) {
        if (data != null) {
            // get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap
            Bitmap selectedBitmap = extras.getParcelable("data");

            imgView.setImageBitmap(selectedBitmap);
        }
    }
}

It is pretty easy for me to implement and also shows darken areas.

How to vertically center content with variable height within a div?

This seems to be the best solution I’ve found to this problem, as long as your browser supports the ::before pseudo element: CSS-Tricks: Centering in the Unknown.

It doesn’t require any extra markup and seems to work extremely well. I couldn’t use the display: table method because table elements don’t obey the max-height property.

_x000D_
_x000D_
.block {_x000D_
  height: 300px;_x000D_
  text-align: center;_x000D_
  background: #c0c0c0;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.block::before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  height: 100%; _x000D_
  vertical-align: middle;_x000D_
  margin-right: -0.25em; /* Adjusts for spacing */_x000D_
_x000D_
  /* For visualization _x000D_
  background: #808080; width: 5px;_x000D_
  */_x000D_
}_x000D_
_x000D_
.centered {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  width: 300px;_x000D_
  padding: 10px 15px;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  background: #f5f5f5;_x000D_
}
_x000D_
<div class="block">_x000D_
    <div class="centered">_x000D_
        <h1>Some text</h1>_x000D_
        <p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
           shoulder, said&mdash;"Did ye see anything looking like men going_x000D_
           towards that ship a while ago?"</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Remove multiple whitespaces

You need:

$ro = preg_replace('/\s+/', ' ',$row['message']);

You are using \s\s+ which means whitespace(space, tab or newline) followed by one or more whitespace. Which effectively means replace two or more whitespace with a single space.

What you want is replace one or more whitespace with single whitespace, so you can use the pattern \s\s* or \s+ (recommended)

using href links inside <option> tag

<select name="forma" onchange="location = this.value;">
 <option value="Home.php">Home</option>
 <option value="Contact.php">Contact</option>
 <option value="Sitemap.php">Sitemap</option>
</select>

UPDATE (Nov 2015): In this day and age if you want to have a drop menu there are plenty of arguably better ways to implement one. This answer is a direct answer to a direct question, but I don't advocate this method for public facing web sites.

UPDATE (May 2020): Someone asked in the comments why I wouldn't advocate this solution. I guess it's a question of semantics. I'd rather my users navigate using <a> and kept <select> for making form selections because HTML elements have semantic meeting and they have a purpose, anchors take you places, <select> are for picking things from lists.

Consider, if you are viewing a page with a non-traditional browser (a non graphical browser or screen reader or the page is accessed programmatically, or JavaScript is disabled) what then is the "meaning" or the "intent" of this <select> you have used for navigation? It is saying "please pick a page name" and not a lot else, certainly nothing about navigating. The easy response to this is well i know that my users will be using IE or whatever so shrug but this kinda misses the point of semantic importance.

Whereas a funky drop-down UI element made of suitable layout elements (and some js) containing some regular anchors still retains it intent even if the layout element is lost, "these are a bunch of links, select one and we will navigate there".

Here is an article on the misuse and abuse of <select>.

Group by multiple field names in java 8

You have a few options here. The simplest is to chain your collectors:

Map<String, Map<Integer, List<Person>>> map = people
    .collect(Collectors.groupingBy(Person::getName,
        Collectors.groupingBy(Person::getAge));

Then to get a list of 18 year old people called Fred you would use:

map.get("Fred").get(18);

A second option is to define a class that represents the grouping. This can be inside Person. This code uses a record but it could just as easily be a class (with equals and hashCode defined) in versions of Java before JEP 359 was added:

class Person {
    record NameAge(String name, int age) { }

    public NameAge getNameAge() {
        return new NameAge(name, age);
    }
}

Then you can use:

Map<NameAge, List<Person>> map = people.collect(Collectors.groupingBy(Person::getNameAge));

and search with

map.get(new NameAge("Fred", 18));

Finally if you don't want to implement your own group record then many of the Java frameworks around have a pair class designed for this type of thing. For example: apache commons pair If you use one of these libraries then you can make the key to the map a pair of the name and age:

Map<Pair<String, Integer>, List<Person>> map =
    people.collect(Collectors.groupingBy(p -> Pair.of(p.getName(), p.getAge())));

and retrieve with:

map.get(Pair.of("Fred", 18));

Personally I don't really see much value in generic tuples now that records are available in the language as records display intent better and require very little code.

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

Regular expression - starting and ending with a character string

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

..The underlying connection was closed: An unexpected error occurred on a receive

Before Execute query I put the statement as below and it resolved my error. Just FYI in case it will help someone.

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ctx.ExecuteQuery();

How can I align YouTube embedded video in the center in bootstrap

make iframe with align="middle" and put it in paragraph with style="text-aling:center":

<p style="text-align:center;">
<iframe width="420" height="315" align="middle" src="https://www.youtube.com/embed/YOURVIDEO">
</iframe>
</p>

How to insert a row in an HTML table body in JavaScript

Basic approach:

This should add HTML-formatted content and show the newly added row.

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;

What's the difference between faking, mocking, and stubbing?

stub and fake are objects in that they can vary their response based on input parameters. the main difference between them is that a Fake is closer to a real-world implementation than a stub. Stubs contain basically hard-coded responses to an expected request. Let see an example:

public class MyUnitTest {

 @Test
 public void testConcatenate() {
  StubDependency stubDependency = new StubDependency();
  int result = stubDependency.toNumber("one", "two");
  assertEquals("onetwo", result);
 }
}

public class StubDependency() {
 public int toNumber(string param) {
  if (param == “one”) {
   return 1;
  }
  if (param == “two”) {
   return 2;
  }
 }
}

A mock is a step up from fakes and stubs. Mocks provide the same functionality as stubs but are more complex. They can have rules defined for them that dictate in what order methods on their API must be called. Most mocks can track how many times a method was called and can react based on that information. Mocks generally know the context of each call and can react differently in different situations. Because of this, mocks require some knowledge of the class they are mocking. a stub generally cannot track how many times a method was called or in what order a sequence of methods was called. A mock looks like:

public class MockADependency {

 private int ShouldCallTwice;
 private boolean ShouldCallAtEnd;
 private boolean ShouldCallFirst;

 public int StringToInteger(String s) {
  if (s == "abc") {
   return 1;
  }
  if (s == "xyz") {
   return 2;
  }
  return 0;
 }

 public void ShouldCallFirst() {
  if ((ShouldCallTwice > 0) || ShouldCallAtEnd)
   throw new AssertionException("ShouldCallFirst not first thod called");
  ShouldCallFirst = true;
 }

 public int ShouldCallTwice(string s) {
  if (!ShouldCallFirst)
   throw new AssertionException("ShouldCallTwice called before ShouldCallFirst");
  if (ShouldCallAtEnd)
   throw new AssertionException("ShouldCallTwice called after ShouldCallAtEnd");
  if (ShouldCallTwice >= 2)
   throw new AssertionException("ShouldCallTwice called more than twice");
  ShouldCallTwice++;
  return StringToInteger(s);
 }

 public void ShouldCallAtEnd() {
  if (!ShouldCallFirst)
   throw new AssertionException("ShouldCallAtEnd called before ShouldCallFirst");
  if (ShouldCallTwice != 2) throw new AssertionException("ShouldCallTwice not called twice");
  ShouldCallAtEnd = true;
 }

}

Inserting image into IPython notebook markdown

I am using ipython 2.0, so just two line.

from IPython.display import Image
Image(filename='output1.png')

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

This is the best way to get a simple date string :

 @DateTime.Parse(Html.DisplayFor(Model => Model.AuditDate).ToString()).ToShortDateString()