Programs & Examples On #Colorfilter

Coloring Buttons in Android with Material Design and AppCompat

Officially fixed in Support Library rev.22 (Fri March 13, 2015). See relevant google code issue:

https://issuetracker.google.com/issues/37008632

Usage example

theme.xml:

<item name="colorButtonNormal">@color/button_color</item>

v21/theme.xml

<item name="android:colorButtonNormal">@color/button_color</item>

How to set tint for an image view programmatically in android?

As the first answer didn't work for me:

//get ImageView
ImageView myImageView = (ImageView) findViewById(R.id.iv);

//colorid is the id of a color defined in values/colors.xml
myImageView.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(getApplicationContext(), R.color.colorid)));

This only seems to work in API 21+, but for me that wasn't an issue. You can use an ImageViewCompat to resolve that issue, tho.

I hope I helped anyone out :-)

Android button background color

Try this

<androidx.appcompat.widget.AppCompatButton
    android:layout_width="wrap_content"
    android:layout_height="34dp"
    android:text="Check Out"
    android:textAllCaps="true"
    android:background="#54c2bc"
    android:textColor="#FFFFFF"
    android:textSize="9sp"/>

Change drawable color programmatically

Syntax

"your image name".setColorFilter("your context".getResources().getColor("color name"));

Example

myImage.setColorFilter(mContext.getResources().getColor(R.color.deep_blue_new));

chai test array equality doesn't work as expected

You can use .deepEqual()

const { assert } = require('chai');

assert.deepEqual([0,0], [0,0]);

Converting String to "Character" array in Java

if you are working with JTextField then it can be helpfull..

public JTextField display;
String number=e.getActionCommand();

display.setText(display.getText()+number);

ch=number.toCharArray();
for( int i=0; i<ch.length; i++)
    System.out.println("in array a1= "+ch[i]);

How to know that a string starts/ends with a specific string in jQuery?

For startswith, you can use indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

and you can do the maths based on string length to determine 'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

How can I get the MAC and the IP address of a connected client in PHP?

You can use the following solution to solve your problem:

$mac='UNKNOWN';
foreach(explode("\n",str_replace(' ','',trim(`getmac`,"\n"))) as $i)
if(strpos($i,'Tcpip')>-1){$mac=substr($i,0,17);break;}
echo $mac;

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Use fetch instead of XHR,then the request will not be prelighted even it's cross-domained.

Execute stored procedure with an Output parameter?

First, declare the output variable:

DECLARE @MyOutputParameter INT;

Then, execute the stored procedure, and you can do it without parameter's names, like this:

EXEC my_stored_procedure 'param1Value', @MyOutputParameter OUTPUT

or with parameter's names:

EXEC my_stored_procedure @param1 = 'param1Value', @myoutput = @MyOutputParameter OUTPUT

And finally, you can see the output result by doing a SELECT:

SELECT @MyOutputParameter 

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

Why not try adding Scope? Scope is a very good feature of Eloquent.

class User extends Eloquent {

    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    public function scopeWomen($query)
    {
        return $query->whereGender('W');
    }

}

$users = User::popular()->women()->orderBy('created_at')->get();

Eloquent #scopes in Laravel Docs

Can I assume (bool)true == (int)1 for any C++ compiler?

Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...

Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as ints that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h> only require zero or non-zero, not necessarily zero or one.

If you cast that to bool, zero will convert to false, and non-zero to true (as you'd expect).

if, elif, else statement issues in Bash

Missing space between elif and [ rest your program is correct. you need to correct it an check it out. here is fixed program:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

useful link related to this bash if else statement

How to check whether an object is a date?

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

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

Now you can check any type like this:

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

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

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

Math.random() versus Random.nextInt(int)

another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the same seed. This is not possible with Math.random().

Filter multiple values on a string column in dplyr

This can be achieved using dplyr package, which is available in CRAN. The simple way to achieve this:

  1. Install dplyr package.
  2. Run the below code
library(dplyr) 

df<- select(filter(dat,name=='tom'| name=='Lynn'), c('days','name))

Explanation:

So, once we’ve downloaded dplyr, we create a new data frame by using two different functions from this package:

filter: the first argument is the data frame; the second argument is the condition by which we want it subsetted. The result is the entire data frame with only the rows we wanted. select: the first argument is the data frame; the second argument is the names of the columns we want selected from it. We don’t have to use the names() function, and we don’t even have to use quotation marks. We simply list the column names as objects.

How do I install SciPy on 64 bit Windows?

You can either download a scientific Python distribution. One of the ones mentioned here: https://scipy.org/install.html

Or pip install from a whl file here if the above is not an option for you.

http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

Populating a razor dropdownlist from a List<object> in MVC

I'm going to approach this as if you have a Users model:

Users.cs

public class Users
{
    [Key]
    public int UserId { get; set; }

    [Required]
    public string UserName { get; set; }

    public int RoleId { get; set; }

    [ForeignKey("RoleId")]
    public virtual DbUserRoles DbUserRoles { get; set; }
}

and a DbUserRoles model that represented a table by that name in the database:

DbUserRoles.cs

public partial class DbUserRoles
{
    [Key]
    public int UserRoleId { get; set; }

    [Required]
    [StringLength(30)]
    public string UserRole { get; set; }
}

Once you had that cleaned up, you should just be able to create and fill a collection of UserRoles, like this, in your Controller:

var userRoleList = GetUserRolesList();
ViewData["userRoles"] = userRolesList;

and have these supporting functions:

private static SelectListItem[] _UserRolesList;

/// <summary>
/// Returns a static category list that is cached
/// </summary>
/// <returns></returns>
public SelectListItem[] GetUserRolesList()
{
    if (_UserRolesList == null)
    {
        var userRoles = repository.GetAllUserRoles().Select(a => new SelectListItem()
         {
             Text = a.UserRole,
             Value = a.UserRoleId.ToString()
         }).ToList();
         userRoles.Insert(0, new SelectListItem() { Value = "0", Text = "-- Please select your user role --" });

        _UserRolesList = userRoles.ToArray();
    }

    // Have to create new instances via projection
    // to avoid ModelBinding updates to affect this
    // globally
    return _UserRolesList
        .Select(d => new SelectListItem()
    {
         Value = d.Value,
         Text = d.Text
    })
     .ToArray();
}

Repository.cs

My Repository function GetAllUserRoles() for the function, above:

public class Repository
{
    Model1 db = new Model1(); // Entity Framework context

    // User Roles
    public IList<DbUserRoles> GetAllUserRoles()
    {
        return db.DbUserRoles.OrderBy(e => e.UserRoleId).ToList();
    }
}

AddNewUser.cshtml

Then do this in your View:

<table>
    <tr>
        <td>
            @Html.EditorFor(model => model.UserName,
                  htmlAttributes: new { @class = "form-control" }
                  )
        </td>
        <td>
            @Html.DropDownListFor(model => model.RoleId,
                  new SelectList( (IEnumerable<SelectListItem>)ViewData["userRoles"], "Value", "Text", model.RoleId),
                  htmlAttributes: new { @class = "form-control" }
                  )
         </td>
     </tr>
 </table>

Directory Chooser in HTML page

Try this, I think it will work for you:

<input type="file" webkitdirectory directory multiple/>

You can find the demo of this at https://plus.google.com/+AddyOsmani/posts/Dk5UhZ6zfF3 , and if you need further information you can find it here.

NSRange to Range<String.Index>

The NSString version (as opposed to Swift String) of replacingCharacters(in: NSRange, with: NSString) accepts an NSRange, so one simple solution is to convert String to NSString first. The delegate and replacement method names are slightly different in Swift 3 and 2, so depending on which Swift you're using:

Swift 3.0

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

  let nsString = textField.text as NSString?
  let newString = nsString?.replacingCharacters(in: range, with: string)
}

Swift 2.x

func textField(textField: UITextField,
               shouldChangeCharactersInRange range: NSRange,
               replacementString string: String) -> Bool {

    let nsString = textField.text as NSString?
    let newString = nsString?.stringByReplacingCharactersInRange(range, withString: string)
}

Check if a record exists in the database

protected void btnsubmit_Click(object sender, EventArgs e)
{

        string s = @"SELECT * FROM tbl1 WHERE CodNo = @CodNo";
    SqlCommand cmd1 = new SqlCommand(s, con);
    cmd1.Parameters.AddWithValue("@CodNo", txtid.Text);
    con.Open();
    int records = (int)cmd1.ExecuteScalar();

    if (records > 0)
    {

        Response.Write("<script>alert('Record not Exist')</script>");

    }
    else
    {
        Response.Write("<script>alert('Record Exist')</script>"); 
     }
  }
        private void  insert_data()
{

        SqlCommand comm = new SqlCommand("Insert into tbl1(CodNo,name,lname,fname,gname,EmailID,PhonNo,gender,image,province,district,village,address,phonNo2,DateOfBirth,school,YearOfGraduation,exlanguage,province2,district2,village2,PlaceOfBirth,NIDnumber,IDchapter,IDpage,IDRecordNumber,NIDCard,Kankur1Year,Kankur1ID,Kankur1Mark,Kankur2Year,Kankur2ID,Kankur2Mark,Kankur3Year,Kankur3ID,Kankur3Mark) values(@CodNo,N'" + txtname.Text.ToString() + "',N'" + txtlname.Text.ToString() + "',N'" + txtfname.Text.ToString() + "',N'" + txtgname.Text.ToString() + "',N'" + txtemail.Text.ToString() + "','" + txtphonnumber.Text.ToString() + "',N'" + ddlgender.Text.ToString() + "',@image,N'" + txtprovince.Text.ToString() + "',N'" + txtdistrict.Text.ToString() + "',N'" + txtvillage.Text.ToString() + "',N'" + txtaddress.Value.ToString() + "','" + txtphonNo2.Text.ToString() + "',N'" + txtdbo.Text.ToString() + "',N'" + txtschool.Text.ToString() + "','" + txtgraduate.Text.ToString() + "',N'" + txtexlanguage.Text.ToString() + "',N'" + txtprovince1.Text.ToString() + "',N'" + txtdistrict1.Text.ToString() + "',N'" + txtvillage1.Text.ToString() + "',N'" + txtpbirth.Text.ToString() + "','" + txtNIDnumber.Text.ToString() + "','" + txtidchapter.Text.ToString() + "', '" + txtidpage.Text.ToString() + "','" + txtrecordNo.Text.ToString() + "',@NIDCard,'" + txtkankuryear1.Text.ToString() + "','" + txtkankurid1.Text.ToString() + "','" + txtkankurscore1.Text.ToString() + "','" + txtkankuryear2.Text.ToString() + "','" + txtkankurid2.Text.ToString() + "','" + txtkankurscore2.Text.ToString() + "','" + txtkankuryear3.Text.ToString() + "','" + txtkankurid3.Text.ToString() + "','" + txtkankurscore3.Text.ToString() + "')", con);

        flpimage.SaveAs(Server.MapPath("~/File/") + flpimage.FileName);
        string img = @"~/File/" + flpimage.FileName;
        flpnidcard.SaveAs(Server.MapPath("~/Tazkiera/") + flpnidcard.FileName);
        string img1 = @"~/Tazkiera/" + flpnidcard.FileName;

        comm.Parameters.AddWithValue("CodNo", Convert.ToInt32(txtid.Text));
        comm.Parameters.AddWithValue("image", flpimage.FileName);
        comm.Parameters.AddWithValue("NIDCard", flpnidcard.FileName);

        comm.ExecuteNonQuery();
        con.Close();

        Response.Redirect("~/SecondPage.aspx");
        //Response.Write("<script>alert('Record Inserted')</script>");

        }
    }

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.

Private Sub Open_multiple_sub_pages_from_main_page()


Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object


' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True

' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"

' Wait while IE loading...
While IE.Busy
        DoEvents
Wend


Set objCollection = IE.Document.getElementsByTagName("input")

i = 0
While i < objCollection.Length
    If objCollection(i).Name = "txtUserName" Then
        ' Set text for search
        objCollection(i).Value = "1234"
    End If
    If objCollection(i).Name = "txtPwd" Then
        ' Set text for search
        objCollection(i).Value = "password"
    End If

    If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
        Set objElement = objCollection(i)
    End If
    i = i + 1
Wend
objElement.Click    ' click button to load page

' Wait while IE re-loading...
While IE.Busy
        DoEvents
Wend

' Show IE
IE.Visible = True
Set Doc = IE.Document

Dim links, link

Dim j As Integer                                                                    'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n                                    'loop to go thru all "a" item so it loads next page
    links(j).Click
    While IE.Busy
        DoEvents
    Wend
    '-------------Do stuff here:  copy field value and paste in excel sheet.  Will post another question for this------------------------
    IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click              'save
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click            'close
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
    j = j + 2
Wend    
End Sub

How to get String Array from arrays.xml file

You can't initialize your testArray field this way, because the application resources still aren't ready.

Just change the code to:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
    String[] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        mTestArray = getResources().getStringArray(R.array.testArray);    

        /* Assign the name array to that adapter and 
        also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A slightly more concise example that builds on top of the other answers here. I leveraged the code generation that is shipped with Visual Studio to remove most of the extra invocation code and replaced it with typed objects instead.

    using System;
    using System.Management;

    namespace Utils
    {
        class NetworkManagement
        {
            /// <summary>
            /// Returns a list of all the network interface class names that are currently enabled in the system
            /// </summary>
            /// <returns>list of nic names</returns>
            public static string[] GetAllNicDescriptions()
            {
                List<string> nics = new List<string>();

                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                           .Where(mo => (bool)mo["IPEnabled"])
                                                                           .Select(x=> new NetworkAdapterConfiguration(x)))
                        {
                            nics.Add(config.Description);
                        }
                    }
                }

                return nics.ToArray();
            }

            /// <summary>
            /// Set's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false)
            {
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
                        {
                            // NAC class was generated by opening a developer console and entering:
                            // mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs
                            // See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/

                            using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS))
                            {
                                if (config.SetDNSServerSearchOrder(dnsServers) == 0)
                                {
                                    RestartNetworkAdapter(nicDescription);
                                }
                            }
                        }
                    }
                }

                return false;
            }

            /// <summary>
            /// Restarts a given Network adapter
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static void RestartNetworkAdapter(string nicDescription)
            {
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter"))
                {
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo=> (string)mo["Description"] == nicDescription))
                        {
                            // NA class was generated by opening dev console and entering
                            // mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs
                            using (NetworkAdapter adapter = new NetworkAdapter(mboDNS))
                            {
                                adapter.Disable();
                                adapter.Enable();
                                Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect
                                return;
                            }
                        }
                    }
                }
            }

            /// <summary>
            /// Get's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static string[] GetNameservers(string nicDescription)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config  in networkConfigs.Cast<ManagementObject>()
                                                              .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                              .Select( x => new NetworkAdapterConfiguration(x)))
                        {
                            return config.DNSServerSearchOrder;
                        }
                    }
                }

                return null;
            }

            /// <summary>
            /// Set's a new IP Address and it's Submask of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="ipAddresses">The IP Address</param>
            /// <param name="subnetMask">The Submask IP Address</param>
            /// <param name="gateway">The gateway.</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                       .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                                       .Select( x=> new NetworkAdapterConfiguration(x)))
                        {
                            // Set the new IP and subnet masks if needed
                            config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ => subnetMask));

                            // Set mew gateway if needed
                            if (!String.IsNullOrEmpty(gateway))
                            {
                                config.SetGateways(new[] {gateway}, new ushort[] {1});
                            }
                        }
                    }
                }
            }

        }
    }

Full source: https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs

make: Nothing to be done for `all'

Sometimes "Nothing to be done for all" error can be caused by spaces before command in makefile rule instead of tab. Please ensure that you use tabs instead of spaces inside of your rules.

all:
<\t>$(CC) $(CFLAGS) ...

instead of

all:
    $(CC) $(CFLAGS) ...

Please see the GNU make manual for the rule syntax description: https://www.gnu.org/software/make/manual/make.html#Rule-Syntax

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

Question 1: Do Erlang, Python and Haskell lose speed due to using arbitrary length integers or don't they as long as the values are less than MAXINT?

Question one can be answered in the negative for Erlang. The last question is answered by using Erlang appropriately, as in:

http://bredsaal.dk/learning-erlang-using-projecteuler-net

Since it's faster than your initial C example, I would guess there are numerous problems as others have already covered in detail.

This Erlang module executes on a cheap netbook in about 5 seconds ... It uses the network threads model in erlang and, as such demonstrates how to take advantage of the event model. It could be distributed over many nodes. And it's fast. Not my code.

-module(p12dist).  
-author("Jannich Brendle, [email protected], http://blog.bredsaal.dk").  
-compile(export_all).

server() ->  
  server(1).

server(Number) ->  
  receive {getwork, Worker_PID} -> Worker_PID ! {work,Number,Number+100},  
  server(Number+101);  
  {result,T} -> io:format("The result is: \~w.\~n", [T]);  
  _ -> server(Number)  
  end.

worker(Server_PID) ->  
  Server_PID ! {getwork, self()},  
  receive {work,Start,End} -> solve(Start,End,Server_PID)  
  end,  
  worker(Server_PID).

start() ->  
  Server_PID = spawn(p12dist, server, []),  
  spawn(p12dist, worker, [Server_PID]),  
  spawn(p12dist, worker, [Server_PID]),  
  spawn(p12dist, worker, [Server_PID]),  
  spawn(p12dist, worker, [Server_PID]).

solve(N,End,_) when N =:= End -> no_solution;

solve(N,End,Server_PID) ->  
  T=round(N*(N+1)/2),
  case (divisor(T,round(math:sqrt(T))) > 500) of  
    true ->  
      Server_PID ! {result,T};  
    false ->  
      solve(N+1,End,Server_PID)  
  end.

divisors(N) ->  
  divisor(N,round(math:sqrt(N))).

divisor(_,0) -> 1;  
divisor(N,I) ->  
  case (N rem I) =:= 0 of  
  true ->  
    2+divisor(N,I-1);  
  false ->  
    divisor(N,I-1)  
  end.

The test below took place on an: Intel(R) Atom(TM) CPU N270 @ 1.60GHz

~$ time erl -noshell -s p12dist start

The result is: 76576500.

^C

BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
       (v)ersion (k)ill (D)b-tables (d)istribution
a

real    0m5.510s
user    0m5.836s
sys 0m0.152s

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

Do the following in your terminal

sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php

After this you have to restart your server

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

How to convert JSON string into List of Java object?

Try this. It works with me. Hope you too!

_x000D_
_x000D_
List<YOUR_OBJECT> testList = new ArrayList<>();_x000D_
testList.add(test1);_x000D_
_x000D_
Gson gson = new Gson();_x000D_
_x000D_
String json = gson.toJson(testList);_x000D_
_x000D_
Type type = new TypeToken<ArrayList<YOUR_OBJECT>>(){}.getType();_x000D_
_x000D_
ArrayList<YOUR_OBJECT> array = gson.fromJson(json, type);
_x000D_
_x000D_
_x000D_

Find mouse position relative to element

I implemented an other solution that I think is very simple so I thought I'd share with you guys.

So, the problem for me was that the dragged div would jump to 0,0 for the mouse cursor. So I needed to capture the mouses position on the div to adjust the divs new position.

I read the divs PageX and PageY and set the top and left of the according to that and then to get the values to adjust the coordinates to keep the cursor in the initial position in the div I use a onDragStart listener and store the e.nativeEvent.layerX and e.nativeEvent.layerY that only in the initial trigger gives you the mouses position within the draggable div.

Example code :

 onDrag={(e) => {
          let newCoords;
          newCoords = { x: e.pageX - this.state.correctionX, y: e.pageY - this.state.correctionY };
          this.props.onDrag(newCoords, e, item.id);
        }}
        onDragStart={
          (e) => {
            this.setState({
              correctionX: e.nativeEvent.layerX,
              correctionY: e.nativeEvent.layerY,
            });
          }

I hope this will help someone that went through the same problems I went through :)

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

this should work

update table_name
  set column_b = case
                  when column_a = 1 then 'Y'
                  else null
                 end,
  set column_c = case
                  when column_a = 2 then 'Y'
                  else null
                 end,
  set column_d = case
                  when column_a = 3 then 'Y'
                  else null
                 end
where
 conditions

the question is why would you want to do that...you may want to rethink the data model. you can replace null with whatever you want.

Stylesheet not loaded because of MIME-type

Check if you have a compression enabled or disabled. If you use it or someone enabled it then app.use(express.static(xxx)) won't help. Make sure your server allows for compression.

I started to see the similar error when I added Brotli and Compression Plugins to my Webpack. Then your server needs to support this type of content compression too.

If you are using Express then the following should help:

app.use(url, expressStaticGzip(dir, gzipOptions)

Module is called: express-static-gzip

My settings are:

const gzipOptions = {
  enableBrotli: true,
  customCompressions: [{
  encodingName: 'deflate',
  fileExtension: 'zz'
 }],
 orderPreference: ['br']
}

Does Python have “private” variables in classes?

Python does not have any private variables like C++ or Java does. You could access any member variable at any time if wanted, too. However, you don't need private variables in Python, because in Python it is not bad to expose your classes member variables. If you have the need to encapsulate a member variable, you can do this by using "@property" later on without breaking existing client code.

In python the single underscore "_" is used to indicate, that a method or variable is not considered as part of the public api of a class and that this part of the api could change between different versions. You can use these methods/variables, but your code could break, if you use a newer version of this class.

The double underscore "__" does not mean a "private variable". You use it to define variables which are "class local" and which can not be easily overidden by subclasses. It mangles the variables name.

For example:

class A(object):
    def __init__(self):
        self.__foobar = None # will be automatically mangled to self._A__foobar

class B(A):
    def __init__(self):
        self.__foobar = 1 # will be automatically mangled to self._B__foobar

self.__foobar's name is automatically mangled to self._A__foobar in class A. In class B it is mangled to self._B__foobar. So every subclass can define its own variable __foobar without overriding its parents variable(s). But nothing prevents you from accessing variables beginning with double underscores. However, name-mangling prevents you from calling this variables /methods incidentally.

I strongly recommend to watch Raymond Hettingers talk "Pythons class development toolkit" from Pycon 2013 (should be available on Youtube), which gives a good example why and how you should use @property and "__"-instance variables.

If you have exposed public variables and you have the need to encapsulate them, then you can use @property. Therefore you can start with the simplest solution possible. You can leave member variables public unless you have a concrete reason to not do so. Here is an example:

class Distance:
    def __init__(self, meter):
        self.meter = meter


d = Distance(1.0)
print(d.meter)
# prints 1.0

class Distance:
    def __init__(self, meter):
        # Customer request: Distances must be stored in millimeters.
        # Public available internals must be changed.
        # This would break client code in C++.
        # This is why you never expose public variables in C++ or Java.
        # However, this is python.
        self.millimeter = meter * 1000

    # In python we have @property to the rescue.
    @property
    def meter(self):
        return self.millimeter *0.001

    @meter.setter
    def meter(self, value):
        self.millimeter = meter * 1000

d = Distance(1.0)
print(d.meter)
# prints 1.0

How to run single test method with phpunit?

  • Run this inside your project root directory i am using in laravel root directory.

vendor/bin/phpunit --filter 'Your method name'

Example with custom method name.

 /** @test //Initilize this for custom method name, without test keyword
  *  
  * Test case For Dashboard When User Not logged In it will redirect To login page
  */
  public function only_logged_in_user_see_dashboard()
  {
    $response = $this->get('/dashboard')
                   ->assertRedirect('/login');
  }

Example with test keyword

/**
* A basic test example.
*
* @return void
*/
 public function testBasicTest()
 {
  $this->assertTrue(true);
 }

How to import a module in Python with importlib.import_module

For relative imports you have to:

  • a) use relative name
  • b) provide anchor explicitly

    importlib.import_module('.c', 'a.b')
    

Of course, you could also just do absolute import instead:

importlib.import_module('a.b.c')

How can I make all images of different height and width the same via CSS?

Simplest way - This will keep the image size as it is and fill the other area with space, this way all the images will take same specified space regardless of the image size without stretching

.img{
   width:100px;
   height:100px;

/*Scale down will take the necessary specified space that is 100px x 100px without stretching the image*/
    object-fit:scale-down;

}

How do I create a comma-separated list using a SQL query?

Using COALESCE to Build Comma-Delimited String in SQL Server
http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string

Example:

DECLARE @EmployeeList varchar(100)

SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

SELECT @EmployeeList

How to serialize an Object into a list of URL query parameters?

ES6:

_x000D_
_x000D_
function params(data) {_x000D_
  return Object.keys(data).map(key => `${key}=${encodeURIComponent(data[key])}`).join('&');_x000D_
}_x000D_
_x000D_
console.log(params({foo: 'bar'}));_x000D_
console.log(params({foo: 'bar', baz: 'qux$'}));
_x000D_
_x000D_
_x000D_

Determine if variable is defined in Python

'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)

How to configure postgresql for the first time?

Note: textdb is the database which you are going to explore with 'alex' user 

root@kalilinux:~# sudo su - postgres 
postgres=#  psql   
postgres=#  create database testdb;
postgres=#  create user alex with password 'alex';
postgres=# GRANT ALL PRIVILEGES ON DATABASE testdb TO alex;`enter code here`

Can I use a min-height for table, tr or td?

The solution without div is used a pseudo element like ::after into first td in row with min-height. Save your HTML clean.

table tr td:first-child::after {
   content: "";
   display: inline-block;
   vertical-align: top;
   min-height: 60px;
}

apt-get for Cygwin?

you can always make a bash alias to setup*.exe files in $home/.bashrc

cygwin 32bit

alias cyg-get="/cygdrive/c/cygwin/setup-x86.exe -q -P"

cygwin 64bit

alias cyg-get="/cygdrive/c/cygwin64/setup-x86_64.exe -q -P"

now you can install packages with

cyg-get <package>

Create numpy matrix filled with NaNs

I compared the suggested alternatives for speed and found that, for large enough vectors/matrices to fill, all alternatives except val * ones and array(n * [val]) are equally fast.

enter image description here


Code to reproduce the plot:

import numpy
import perfplot

val = 42.0


def fill(n):
    a = numpy.empty(n)
    a.fill(val)
    return a


def colon(n):
    a = numpy.empty(n)
    a[:] = val
    return a


def full(n):
    return numpy.full(n, val)


def ones_times(n):
    return val * numpy.ones(n)


def list(n):
    return numpy.array(n * [val])


perfplot.show(
    setup=lambda n: n,
    kernels=[fill, colon, full, ones_times, list],
    n_range=[2 ** k for k in range(20)],
    logx=True,
    logy=True,
    xlabel="len(a)",
)

How to view log output using docker-compose run?

Update July 1st 2019

docker-compose logs <name-of-service>

From the documentation:

Usage: logs [options] [SERVICE...]

Options:

--no-color Produce monochrome output.

-f, --follow Follow log output.

-t, --timestamps Show timestamps.

--tail="all" Number of lines to show from the end of the logs for each container.

See docker logs

You can start Docker compose in detached mode and attach yourself to the logs of all container later. If you're done watching logs you can detach yourself from the logs output without shutting down your services.

  1. Use docker-compose up -d to start all services in detached mode (-d) (you won't see any logs in detached mode)
  2. Use docker-compose logs -f -t to attach yourself to the logs of all running services, whereas -f means you follow the log output and the -t option gives you timestamps (See Docker reference)
  3. Use Ctrl + z or Ctrl + c to detach yourself from the log output without shutting down your running containers

If you're interested in logs of a single container you can use the docker keyword instead:

  1. Use docker logs -t -f <name-of-service>

Save the output

To save the output to a file you add the following to your logs command:

  1. docker-compose logs -f -t >> myDockerCompose.log

Google Apps Script to open a URL

Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.

It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers

Deprecated. The UI service was deprecated on December 11, 2014. To create user interfaces, use the HTML service instead.

The example in the HTML Service linked page is pretty simple,

Code.gs

// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Dialog')
      .addItem('Open', 'openDialog')
      .addToUi();
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, 'Dialog title');
}

A customized version of index.html to show two hyperlinks

<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>

How to quickly and conveniently disable all console.log statements in my code?

This a hybrid of answers from SolutionYogi and Chris S. It maintains the console.log line numbers and file name. Example jsFiddle.

// Avoid global functions via a self calling anonymous one (uses jQuery)
(function(MYAPP, $, undefined) {
    // Prevent errors in browsers without console.log
    if (!window.console) window.console = {};
    if (!window.console.log) window.console.log = function(){};

    //Private var
    var console_log = console.log;  

    //Public methods
    MYAPP.enableLog = function enableLogger() { console.log = console_log; };   
    MYAPP.disableLog = function disableLogger() { console.log = function() {}; };

}(window.MYAPP = window.MYAPP || {}, jQuery));


// Example Usage:
$(function() {    
    MYAPP.disableLog();    
    console.log('this should not show');

    MYAPP.enableLog();
    console.log('This will show');
});

How to delete all data from solr and hbase

Solr I am not sure but you can delete all the data from hbase using truncate command like below:

truncate 'table_name'

It will delete all row-keys from hbase table.

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

Best practices for copying files with Maven

In order to copy a file use:

        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <id>copy-resource-one</id>
                    <phase>install</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>

                    <configuration>
                        <outputDirectory>${basedir}/destination-folder</outputDirectory>
                        <resources>
                            <resource>
                                <directory>/source-folder</directory>
                                <includes>
                                    <include>file.jar</include>
                                </includes>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
           </executions>
        </plugin>

In order to copy folder with sub-folders use next configuration:

           <configuration>
              <outputDirectory>${basedir}/target-folder</outputDirectory>
              <resources>          
                <resource>
                  <directory>/source-folder</directory>
                  <filtering>true</filtering>
                </resource>
              </resources>              
            </configuration>  

CSS - How to Style a Selected Radio Buttons Label?

You can add a span to your html and css .

Here's an example from my code ...

HTML ( JSX ):

<input type="radio" name="AMPM" id="radiostyle1" value="AM" checked={this.state.AMPM==="AM"} onChange={this.handleChange}/>  
<label for="radiostyle1"><span></span> am  </label>

<input type="radio" name="AMPM" id="radiostyle2" value="PM" checked={this.state.AMPM==="PM"} onChange={this.handleChange}/>
<label for="radiostyle2"><span></span> pm  </label>

CSS to make standard radio button vanish on screen and superimpose custom button image:

input[type="radio"] {  
    opacity:0;                                      
}

input[type="radio"] + label {
    font-size:1em;
    text-transform: uppercase;
    color: white ;  
    cursor: pointer;
    margin:auto 15px auto auto;                    
}

input[type="radio"] + label span {
    display:inline-block;
    width:30px;
    height:10px;
    margin:1px 0px 0 -30px;                       
    cursor:pointer;
    border-radius: 20%;
}


input[type="radio"] + label span {
    background-color: #FFFFFF 
}


input[type="radio"]:checked + label span{
     background-color: #660006;  
}

Openssl : error "self signed certificate in certificate chain"

The solution for the error is to add this line at the top of the code:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

Asynchronous method call in Python?

My solution is:

import threading

class TimeoutError(RuntimeError):
    pass

class AsyncCall(object):
    def __init__(self, fnc, callback = None):
        self.Callable = fnc
        self.Callback = callback

    def __call__(self, *args, **kwargs):
        self.Thread = threading.Thread(target = self.run, name = self.Callable.__name__, args = args, kwargs = kwargs)
        self.Thread.start()
        return self

    def wait(self, timeout = None):
        self.Thread.join(timeout)
        if self.Thread.isAlive():
            raise TimeoutError()
        else:
            return self.Result

    def run(self, *args, **kwargs):
        self.Result = self.Callable(*args, **kwargs)
        if self.Callback:
            self.Callback(self.Result)

class AsyncMethod(object):
    def __init__(self, fnc, callback=None):
        self.Callable = fnc
        self.Callback = callback

    def __call__(self, *args, **kwargs):
        return AsyncCall(self.Callable, self.Callback)(*args, **kwargs)

def Async(fnc = None, callback = None):
    if fnc == None:
        def AddAsyncCallback(fnc):
            return AsyncMethod(fnc, callback)
        return AddAsyncCallback
    else:
        return AsyncMethod(fnc, callback)

And works exactly as requested:

@Async
def fnc():
    pass

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I had the following configuration in my httpd.conf that denied executing the wpadmin/setup-config.php file from wordpress. Removing the |-config part solved the problem. I think this httpd.conf is from plesk but it could be some default suggested config from wordpress, i don't know. Anyway, I could safely add it back after the setup finished.

<LocationMatch "(?i:(?:wp-config\\.bak|\\.wp-config\\.php\\.swp|(?:readme|license|changelog|-config|-sample)\\.(?:php|md|txt|htm|html)))">
                        Require all denied
                </LocationMatch>

Put spacing between divs in a horizontal row?

This is because width when provided a % doesn't account for padding/margins. You will need to reduce the amount to possibly 24% or 24.5%. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.

How to do tag wrapping in VS code?

imo there's a better answer for this using Snippets

Create a snippet with a definition like this:

"name_of_your_snippet": {
    "scope": "javascript,html",
    "prefix": "name_of_your_snippet",
    "body": "<${0:b}>$TM_SELECTED_TEXT</${0:b}>"
}

Then bind it to a key in keybindings.json E.g. like this:

{ 
    "key": "alt+w",
    "command": "editor.action.insertSnippet",
    "args": { "name": "name_of_your_snippet" }
}

I think this should give you exactly the same result as htmltagwrap but without having to install an extension.

It will insert tags around selected text, defaults to <b> tag & selects the tag so typing lets you change it.

If you want to use a different default tag just change the b in the body property of the snippet.

C# Foreach statement does not contain public definition for GetEnumerator

Your CarBootSaleList class is not a list. It is a class that contain a list.

You have three options:

Make your CarBootSaleList object implement IEnumerable

or

make your CarBootSaleList inherit from List<CarBootSale>

or

if you are lazy this could almost do the same thing without extra coding

List<List<CarBootSale>>

How to find if a file contains a given string using Windows command line

I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

Hope it helps!

How to fire a button click event from JavaScript in ASP.NET

You can just place this line in a JavaScript function:

__doPostBack('btnSubmit','OnClick');

Or do something like this:

$('#btnSubmit').trigger('click');

How to clone a Date object?

This is the cleanest approach

_x000D_
_x000D_
let dat = new Date() _x000D_
let copyOf = new Date(dat.valueOf())_x000D_
_x000D_
console.log(dat);_x000D_
console.log(copyOf);
_x000D_
_x000D_
_x000D_

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Its just that you need multiple When for a single case to behave it like if.. Elseif else..

   Case when 1=1       //if
   Then
    When 1=1              //else if
     Then.... 
    When .....              //else if
    Then 
    Else                      //else
   ....... 
     End

*.h or *.hpp for your class definitions

I'm answering this as an reminder, to give point to my comment(s) on "user1949346" answer to this same OP.


So as many already answered: either way is fine. Followed by emphasizes of their own impressions.

Introductory, as also in the previous named comments stated, my opinion is C++ header extensions are proposed to be .h if there is actually no reason against it.

Since the ISO/IEC documents use this notation of header files and no string matching to .hpp even occurs in their language documentations about C++.

But I'm now aiming for an approvable reason WHY either way is ok, and especially why it's not subject of the language it self.

So here we go.

The C++ documentation (I'm actually taking reference from the version N3690) defines that a header has to conform to the following syntax:

2.9 Header names

header-name:
    < h-char-sequence >
    " q-char-sequence "
h-char-sequence:
    h-char
    h-char-sequence h-char
h-char:
    any member of the source character set except new-line and >
q-char-sequence:
    q-char
    q-char-sequence q-char
q-char:
    any member of the source character set except new-line and "

So as we can extract from this part, the header file name may be anything that is valid in the source code, too. Except containing '\n' characters and depending on if it is to be included by <> it is not allowed to contain a >. Or the other way if it is included by ""-include it is not allowed to contain a ".

In other words: if you had a environment supporting filenames like prettyStupidIdea.>, an include like:

#include "prettyStupidIdea.>"

would be valid, but:

#include <prettyStupidIdea.>>

would be invalid. The other way around the same.

And even

#include <<.<>

would be a valid includable header file name.

Even this would conform to C++, it would be a pretty pretty stupid idea, tho.

And that's why .hpp is valid, too.

But it's not an outcome of the committees designing decisions for the language!

So discussing about to use .hpp is same as doing it about .cc, .mm or what ever else I read in other posts on this topic.

I have to admit I have no clue where .hpp came from1, but I would bet an inventor of some parsing tool, IDE or something else concerned with C++ came to this idea to optimize some internal processes or just to invent some (probably even for them necessarily) new naming conventions.

But it is not part of the language.

And whenever one decides to use it this way. May it be because he likes it most or because some applications of the workflow require it, it never2 is a requirement of the language. So whoever says "the pp is because it is used with C++", simply is wrong in regards of the languages definition.

C++ allows anything respecting the previous paragraph. And if there is anything the committee proposed to use, then it is using .h since this is the extension sued in all examples of the ISO document.

Conclusion:

As long you don't see/feel any need of using .h over .hpp or vise versa, you shouldn't bother. Because both would be form a valid header name of same quality in respect to the standard. And therefore anything that REQUIRES you to use .h or .hpp is an additional restriction of the standard which could even be contradicting with other additional restrictions not conform with each other. But as OP doesn't mention any additional language restriction, this is the only correct and approvable answer to the question

"*.h or *.hpp for your class definitions" is:

Both are equally correct and applicable as long as no external restrictions are present.


1From what I know, apparently, it is the boost framework that came up with that .hpp extension.

2Of course I can't say what some future versions will bring with it!

Newline in markdown table?

When you're exporting to HTML, using <br> works. However, if you're using pandoc to export to LaTeX/PDF as well, you should use grid tables:

+---------------+---------------+--------------------+
| Fruit         | Price         | Advantages         |
+===============+===============+====================+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+

jinja2.exceptions.TemplateNotFound error

I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.

open program minimized via command prompt

I tried this commands in my PC.It is working fine....

To open notepad in minimized mode:

start /min "" "C:\Windows\notepad.exe"

To open MS word in minimized mode:

start /min "" "C:\Program Files\Microsoft Office\Office14\WINWORD.EXE"

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

yearofmoo did a great job at creating a reusable $safeApply function for us :

https://github.com/yearofmoo/AngularJS-Scope.SafeApply

Usage :

//use by itself
$scope.$safeApply();

//tell it which scope to update
$scope.$safeApply($scope);
$scope.$safeApply($anotherScope);

//pass in an update function that gets called when the digest is going on...
$scope.$safeApply(function() {

});

//pass in both a scope and a function
$scope.$safeApply($anotherScope,function() {

});

//call it on the rootScope
$rootScope.$safeApply();
$rootScope.$safeApply($rootScope);
$rootScope.$safeApply($scope);
$rootScope.$safeApply($scope, fn);
$rootScope.$safeApply(fn);

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

How can I check if an array contains a specific value in php?

Following is how you can do this:

<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
    echo 'this array contains kitchen';
}

Make sure that you search for kitchen and not Kitchen. This function is case sensitive. So, the below function simply won't work:

$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
    echo 'this array contains kitchen';
}

If you rather want a quick way to make this search case insensitive, have a look at the proposed solution in this reply: https://stackoverflow.com/a/30555568/8661779

Source: http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Why "Accepted Answer" works... but it wasn't enough for me

This works in the specification. At least swagger-tools (version 0.10.1) validates it as a valid.

But if you are using other tools like swagger-codegen (version 2.1.6) you will find some difficulties, even if the client generated contains the Authentication definition, like this:

this.authentications = {
  'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};

There is no way to pass the token into the header before method(endpoint) is called. Look into this function signature:

this.rootGet = function(callback) { ... }

This means that, I only pass the callback (in other cases query parameters, etc) without a token, which leads to a incorrect build of the request to server.

My alternative

Unfortunately, it's not "pretty" but it works until I get JWT Tokens support on Swagger.

Note: which is being discussed in

So, it's handle authentication like a standard header. On path object append an header paremeter:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: localhost
schemes:
  - http
  - https
paths:
  /:
    get:
      parameters:
        - 
          name: authorization
          in: header
          type: string
          required: true
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

This will generate a client with a new parameter on method signature:

this.rootGet = function(authorization, callback) {
  // ...
  var headerParams = {
    'authorization': authorization
  };
  // ...
}

To use this method in the right way, just pass the "full string"

// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);

And works.

npm install doesn't create node_modules directory

For node_modules you have to follow the below steps

1) In Command prompt -> Goto your project directory.

2) Command :npm init

3) It asks you to set up your package.json file

4) Command: npm install or npm update

Create directories using make file

OS independence is critical for me, so mkdir -p is not an option. I created this series of functions that use eval to create directory targets with the prerequisite on the parent directory. This has the benefit that make -j 2 will work without issue since the dependencies are correctly determined.

# convenience function for getting parent directory, will eventually return ./
#     $(call get_parent_dir,somewhere/on/earth/) -> somewhere/on/
get_parent_dir=$(dir $(patsubst %/,%,$1))

# function to create directory targets.
# All directories have order-only-prerequisites on their parent directories
# https://www.gnu.org/software/make/manual/html_node/Prerequisite-Types.html#Prerequisite-Types
TARGET_DIRS:=
define make_dirs_recursively
TARGET_DIRS+=$1
$1: | $(if $(subst ./,,$(call get_parent_dir,$1)),$(call get_parent_dir,$1))
    mkdir $1
endef

# function to recursively get all directories 
#     $(call get_all_dirs,things/and/places/) -> things/ things/and/ things/and/places/
#     $(call get_all_dirs,things/and/places) -> things/ things/and/
get_all_dirs=$(if $(subst ./,,$(dir $1)),$(call get_all_dirs,$(call get_parent_dir,$1)) $1)

# function to turn all targets into directories
#     $(call get_all_target_dirs,obj/a.o obj/three/b.o) -> obj/ obj/three/
get_all_target_dirs=$(sort $(foreach target,$1,$(call get_all_dirs,$(dir $(target)))))

# create target dirs
create_dirs=$(foreach dirname,$(call get_all_target_dirs,$1),$(eval $(call make_dirs_recursively,$(dirname))))

TARGETS := w/h/a/t/e/v/e/r/things.dat w/h/a/t/things.dat

all: $(TARGETS)

# this must be placed after your .DEFAULT_GOAL, or you can manually state what it is
# https://www.gnu.org/software/make/manual/html_node/Special-Variables.html
$(call create_dirs,$(TARGETS))

# $(TARGET_DIRS) needs to be an order-only-prerequisite
w/h/a/t/e/v/e/r/things.dat: w/h/a/t/things.dat | $(TARGET_DIRS)
    echo whatever happens > $@

w/h/a/t/things.dat: | $(TARGET_DIRS)
    echo whatever happens > $@

For example, running the above will create:

$ make
mkdir w/
mkdir w/h/
mkdir w/h/a/
mkdir w/h/a/t/
mkdir w/h/a/t/e/
mkdir w/h/a/t/e/v/
mkdir w/h/a/t/e/v/e/
mkdir w/h/a/t/e/v/e/r/
echo whatever happens > w/h/a/t/things.dat
echo whatever happens > w/h/a/t/e/v/e/r/things.dat

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

When an Abstract Class Implements an Interface

In the section on Interfaces, it was noted that a class that implements an interface must implement all of the interface's methods. It is possible, however, to define a class that does not implement all of the interface's methods, provided that the class is declared to be abstract. For example,

abstract class X implements Y {   
    // implements all but one method of Y
}

class XX extends X {   
    // implements the remaining method in Y 
} 

In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y.

Reference: http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

if (boolean == false) vs. if (!boolean)

- Here its more about the coding style than being the functionality....

- The 1st option is very clear, but then the 2nd one is quite elegant... no offense, its just my view..

What is a Windows Handle?

So at the most basic level a HANDLE of any sort is a pointer to a pointer or

#define HANDLE void **

Now as to why you would want to use it

Lets take a setup:

class Object{
   int Value;
}

class LargeObj{

   char * val;
   LargeObj()
   {
      val = malloc(2048 * 1000);
   }

}

void foo(Object bar){
    LargeObj lo = new LargeObj();
    bar.Value++;
}

void main()
{
   Object obj = new Object();
   obj.val = 1;
   foo(obj);
   printf("%d", obj.val);
}

So because obj was passed by value (make a copy and give that to the function) to foo, the printf will print the original value of 1.

Now if we update foo to:

void foo(Object * bar)
{
    LargeObj lo = new LargeObj();
    bar->val++;
}

There is a chance that the printf will print the updated value of 2. But there is also the possibility that foo will cause some form of memory corruption or exception.

The reason is this while you are now using a pointer to pass obj to the function you are also allocating 2 Megs of memory, this could cause the OS to move the memory around updating the location of obj. Since you have passed the pointer by value, if obj gets moved then the OS updates the pointer but not the copy in the function and potentially causing problems.

A final update to foo of:

void foo(Object **bar){
    LargeObj lo = LargeObj();
    Object * b = &bar;
    b->val++;
}

This will always print the updated value.

See, when the compiler allocates memory for pointers it marks them as immovable, so any re-shuffling of memory caused by the large object being allocated the value passed to the function will point to the correct address to find out the final location in memory to update.

Any particular types of HANDLEs (hWnd, FILE, etc) are domain specific and point to a certain type of structure to protect against memory corruption.

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Is recursion ever faster than looping?

This is a guess. Generally recursion probably doesn't beat looping often or ever on problems of decent size if both are using really good algorithms(not counting implementation difficulty) , it may be different if used with a language w/ tail call recursion(and a tail recursive algorithm and with loops also as part of the language)-which would probably have very similar and possibly even prefer recursion some of the time.

How to link to apps on the app store

Despite there being loads of answers here, none of the suggestions for linking to the developers apps seem to work anymore.

When I last visited I was able to get it working using the format:

itms-apps://itunes.apple.com/developer/developer-name/id123456789

This no longer works, but removing the developer name does:

itms-apps://itunes.apple.com/developer/id123456789

Endless loop in C/C++

I would recommend while (1) { } or while (true) { }. It's what most programmers would write, and for readability reasons you should follow the common idioms.

(Ok, so there is an obvious "citation needed" for the claim about most programmers. But from the code I've seen, in C since 1984, I believe it is true.)

Any reasonable compiler would compile all of them to the same code, with an unconditional jump, but I wouldn't be surprised if there are some unreasonable compilers out there, for embedded or other specialized systems.

import module from string variable

I developed these 3 useful functions:

def loadModule(moduleName):
    module = None
    try:
        import sys
        del sys.modules[moduleName]
    except BaseException as err:
        pass
    try:
        import importlib
        module = importlib.import_module(moduleName)
    except BaseException as err:
        serr = str(err)
        print("Error to load the module '" + moduleName + "': " + serr)
    return module

def reloadModule(moduleName):
    module = loadModule(moduleName)
    moduleName, modulePath = str(module).replace("' from '", "||").replace("<module '", '').replace("'>", '').split("||")
    if (modulePath.endswith(".pyc")):
        import os
        os.remove(modulePath)
        module = loadModule(moduleName)
    return module

def getInstance(moduleName, param1, param2, param3):
    module = reloadModule(moduleName)
    instance = eval("module." + moduleName + "(param1, param2, param3)")
    return instance

And everytime I want to reload a new instance I just have to call getInstance() like this:

myInstance = getInstance("MyModule", myParam1, myParam2, myParam3)

Finally I can call all the functions inside the new Instance:

myInstance.aFunction()

The only specificity here is to customize the params list (param1, param2, param3) of your instance.

Cant get text of a DropDownList in code - can get value but not text

AppendDataBoundItems="true" needs to be set.

What is duck typing?

Duck Typing is not Type Hinting!

Basically in order to use "duck typing" you will not target a specific type but rather a wider range of subtypes (not talking about inheritance, when I mean subtypes I mean "things" that fit within the same profiles) by using a common interface.

You can imagine a system that stores information. In order to write/read information you need some sort of storage and information.

Types of storage may be: file, database, session etc.

The interface will let you know the available options (methods) regardless of the storage type, meaning that at this point nothing is implemented! In another words the Interface doesn't know nothing about how to store information.

Every storage system must know the existence of the interface by implementing it's very same methods.

interface StorageInterface
{
   public function write(string $key, array $value): bool;
   public function read(string $key): array;
}


class File implements StorageInterface
{
    public function read(string $key): array {
        //reading from a file
    }

    public function write(string $key, array $value): bool {
         //writing in a file implementation
    }
}


class Session implements StorageInterface
{
    public function read(string $key): array {
        //reading from a session
    }

    public function write(string $key, array $value): bool {
         //writing in a session implementation
    }
}


class Storage implements StorageInterface
{
    private $_storage = null;

    function __construct(StorageInterface $storage) {
        $this->_storage = $storage;
    }

    public function read(string $key): array {
        return $this->_storage->read($key);
    }

    public function write(string $key, array $value): bool {
        return ($this->_storage->write($key, $value)) ? true : false;
    }
}

So now, every time you need to write/read information:

$file = new Storage(new File());
$file->write('filename', ['information'] );
echo $file->read('filename');

$session = new Storage(new Session());
$session->write('filename', ['information'] );
echo $session->read('filename');

In this example you end up using Duck Typing in Storage constructor:

function __construct(StorageInterface $storage) ...

Hope it helped ;)

Spring Data JPA map the native query result to Non-Entity POJO

In my computer, I get this code works.It's a little different from Daimon's answer.

_x000D_
_x000D_
@SqlResultSetMapping(_x000D_
    name="groupDetailsMapping",_x000D_
    classes={_x000D_
        @ConstructorResult(_x000D_
            targetClass=GroupDetails.class,_x000D_
            columns={_x000D_
                @ColumnResult(name="GROUP_ID",type=Integer.class),_x000D_
                @ColumnResult(name="USER_ID",type=Integer.class)_x000D_
            }_x000D_
        )_x000D_
    }_x000D_
)_x000D_
_x000D_
@NamedNativeQuery(name="User.getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")
_x000D_
_x000D_
_x000D_

Run text file as commands in Bash

Execute

. example.txt

That does exactly what you ask for, without setting an executable flag on the file or running an extra bash instance.

For a detailed explanation see e.g. https://unix.stackexchange.com/questions/43882/what-is-the-difference-between-sourcing-or-source-and-executing-a-file-i

How to combine GROUP BY and ROW_NUMBER?

The deduplication (to select the max T1) and the aggregation need to be done as distinct steps. I've used a CTE since I think this makes it clearer:

;WITH sumCTE
AS
(
    SELECT  Rel.t2ID, SUM(Price) price
    FROM    @t1         AS T1
    JOIN    @relation   AS Rel 
    ON      Rel.t1ID=T1.ID
    GROUP 
    BY      Rel.t2ID
)
,maxCTE
AS
(
    SELECT  Rel.t2ID, Rel.t1ID, 
            ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
    FROM    @t1         AS T1
    JOIN    @relation   AS Rel 
    ON      Rel.t1ID=T1.ID
)
SELECT T2.ID AS T2ID
,T2.Name as T2Name
,T2.Orders
,T1.ID AS T1ID
,T1.Name As T1Name
,sumT1.Price
FROM    @t2 AS T2
JOIN    sumCTE AS sumT1
ON      sumT1.t2ID = t2.ID
JOIN    maxCTE AS maxT1
ON      maxT1.t2ID = t2.ID
JOIN    @t1 AS T1
ON      T1.ID = maxT1.t1ID
WHERE   maxT1.PriceList = 1

What's better at freeing memory with PHP: unset() or $var = null

<?php
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    $a = NULL;
}
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds\r\n";



$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    unset($a);
}
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds\r\n";
?>

Per that it seems like "= null" is faster.

PHP 5.4 results:

  • took 0.88389301300049 seconds
  • took 2.1757180690765 seconds

PHP 5.3 results:

  • took 1.7235369682312 seconds
  • took 2.9490959644318 seconds

PHP 5.2 results:

  • took 3.0069220066071 seconds
  • took 4.7002630233765 seconds

PHP 5.1 results:

  • took 2.6272349357605 seconds
  • took 5.0403649806976 seconds

Things start to look different with PHP 5.0 and 4.4.

5.0:

  • took 10.038941144943 seconds
  • took 7.0874409675598 seconds

4.4:

  • took 7.5352551937103 seconds
  • took 6.6245851516724 seconds

Keep in mind microtime(true) doesn't work in PHP 4.4 so I had to use the microtime_float example given in php.net/microtime / Example #1.

How to Animate Addition or Removal of Android ListView Rows

After inserting new row to ListView, I just scroll the ListView to new position.

ListView.smoothScrollToPosition(position);

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Javascript select onchange='this.form.submit()'

Use :

<select onchange="myFunction()">

    function myFunction() {
        document.querySelectorAll("input[type=submit]")[0].click();
    }

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

Dynamically create and submit form

Like Purmou, but removing the form when submit will done.

$(function() {
   $('<form action="form2.html"></form>').appendTo('body').submit().remove();
});

What is the role of the package-lock.json?

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

It describes a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.It contains the following properties.

{
    "name": "mobileapp",
    "version": "1.0.0",
    "lockfileVersion": 1,
    "requires": true,
    "dependencies": {
    "@angular-devkit/architect": {
      "version": "0.11.4",
      "resolved": "https://registry.npmjs.org/@angular- devkit/architect/-/architect-0.11.4.tgz",
      "integrity": "sha512-2zi6S9tPlk52vyqNFg==",
      "dev": true,
      "requires": {
        "@angular-devkit/core": "7.1.4",
        "rxjs": "6.3.3"
      }
    },
}       

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

This is what I've used:

::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%

If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/

How to access iOS simulator camera

It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS version and any Simulator. You will have to use device for testing camera purpose.

Rolling back bad changes with svn in Eclipse

If you want to do 1 file at a time you can go to the History view for the file assuming you have an Eclipse SVN plugin installed. "Team->Show History"

In the History view, find the last good version of that file, right click and choose "Get Contents". This will replace your current version with that version's contents. Then you can commit the changes when you've fixed it all up.

Is it correct to use DIV inside FORM?

Absolutely not! It will render, but it will not validate. Use a label.

It is not correct. It is not accessible. You see it on some websites because some developers are just lazy. When I am hiring developers, this is one of the first things I check for in candidates work. Forms are nasty, but take the time and learn to do them properly

Python Hexadecimal

Another solution is:

>>> "".join(list(hex(255))[2:])
'ff'

Probably an archaic answer, but functional.

Run a Java Application as a Service on Linux

From Spring Boot application as a Service, I can recommend the Python-based supervisord application. See that stack overflow question for more information. It's really straightforward to set up.

How to send email attachments?

With my code you can send email attachments using gmail you will need to:

set your gmail address at "YOUR SMTP EMAIL HERE"

set your gmail account password at "YOUR SMTP PASSWORD HERE_"

In the ___EMAIL TO RECEIVE THE MESSAGE_ part you need to set the destination email address.

Alarm notification is the subject,

Someone has entered the room, picture attached is the body

["/home/pi/webcam.jpg"] is an image attachment.

#!/usr/bin/env python
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os

USERNAME = "___YOUR SMTP EMAIL HERE___"
PASSWORD = "__YOUR SMTP PASSWORD HERE___"

def sendMail(to, subject, text, files=[]):
    assert type(to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = USERNAME
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(file))
        msg.attach(part)

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo_or_helo_if_needed()
    server.starttls()
    server.ehlo_or_helo_if_needed()
    server.login(USERNAME,PASSWORD)
    server.sendmail(USERNAME, to, msg.as_string())
    server.quit()

sendMail( ["___EMAIL TO RECEIVE THE MESSAGE__"],
        "Alarm notification",
        "Someone has entered the room, picture attached",
        ["/home/pi/webcam.jpg"] )

MS-access reports - The search key was not found in any record - on save

Following on from @Wilf's answer, I was trying to import a spreadsheet which had spaces in one of the headings, which I eliminated. I checked for leading and trailing spaces, but still had the same problem - until I used Ctrl-Right from the last real heading cell, and found another cell on the first row that looked blank but obviously contained some whitespace. After deleting this, my import works. Thanks for the pointers :)

Writing to CSV with Python adds blank lines

If you're using Python 2.x on Windows you need to change your line open('test.csv', 'w') to open('test.csv', 'wb'). That is you should open the file as a binary file.

However, as stated by others, the file interface has changed in Python 3.x.

Trying Gradle build - "Task 'build' not found in root project"

Check your file: settings.gradle for presence lines with included subprojects (for example: include chapter1-bookstore )

git switch branch without discarding local changes

You could use --merge/-m git checkout option: git checkout -m <another-branch>

-m --merge

When switching branches, if you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context. However, with this option, a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch.

Source: https://git-scm.com/docs/git-checkout

Get total size of file in bytes

You don't need FileInputStream to calculate file size, new File(path_to_file).length() is enough. Or, if you insist, use fileinputstream.getChannel().size().

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

Change width of select tag in Twitter Bootstrap

with bootstrap use class input-md = medium, input-lg = large, for more info see https://getbootstrap.com/docs/3.3/css/#forms-control-sizes

Command for restarting all running docker containers?

Just run

docker restart $(docker ps -q)

Update

For Docker 1.13.1 use docker restart $(docker ps -a -q) as in answer lower.

Convert python long/int to fixed size byte array

One-liner:

bytearray.fromhex('{:0192x}'.format(big_int))

The 192 is 768 / 4, because OP wanted 768-bit numbers and there are 4 bits in a hex digit. If you need a bigger bytearray use a format string with a higher number. Example:

>>> big_int = 911085911092802609795174074963333909087482261102921406113936886764014693975052768158290106460018649707059449553895568111944093294751504971131180816868149233377773327312327573120920667381269572962606994373889233844814776702037586419
>>> bytearray.fromhex('{:0192x}'.format(big_int))
bytearray(b'\x96;h^\xdbJ\x8f3obL\x9c\xc2\xb0-\x9e\xa4Sj-\xf6i\xc1\x9e\x97\x94\x85M\x1d\x93\x10\\\x81\xc2\x89\xcd\xe0a\xc0D\x81v\xdf\xed\xa9\xc1\x83p\xdbU\xf1\xd0\xfeR)\xce\x07\xdepM\x88\xcc\x7fv\\\x1c\x8di\x87N\x00\x8d\xa8\xbd[<\xdf\xaf\x13z:H\xed\xc2)\xa4\x1e\x0f\xa7\x92\xa7\xc6\x16\x86\xf1\xf3')
>>> lepi_int = 0x963b685edb4a8f336f624c9cc2b02d9ea4536a2df669c19e9794854d1d93105c81c289cde061c0448176dfeda9c18370db55f1d0fe5229ce07de704d88cc7f765c1c8d69874e008da8bd5b3cdfaf137a3a48edc229a41e0fa792a7c61686f1f
>>> bytearray.fromhex('{:0192x}'.format(lepi_int))
bytearray(b'\tc\xb6\x85\xed\xb4\xa8\xf36\xf6$\xc9\xcc+\x02\xd9\xeaE6\xa2\xdff\x9c\x19\xe9yHT\xd1\xd91\x05\xc8\x1c(\x9c\xde\x06\x1c\x04H\x17m\xfe\xda\x9c\x187\r\xb5_\x1d\x0f\xe5"\x9c\xe0}\xe7\x04\xd8\x8c\xc7\xf7e\xc1\xc8\xd6\x98t\xe0\x08\xda\x8b\xd5\xb3\xcd\xfa\xf17\xa3\xa4\x8e\xdc"\x9aA\xe0\xfay*|aho\x1f')

[My answer had used hex() before. I corrected it with format() in order to handle ints with odd-sized byte expressions. This fixes previous complaints about ValueError.]

@ViewChild in *ngIf

An alternative to overcome this is running the change detector manually.

You first inject the ChangeDetectorRef:

constructor(private changeDetector : ChangeDetectorRef) {}

Then you call it after updating the variable that controls the *ngIf

show() {
        this.display = true;
        this.changeDetector.detectChanges();
    }

Including an anchor tag in an ASP.NET MVC Html.ActionLink

Here is the real life example

@Html.Grid(Model).Columns(columns =>
    {
           columns.Add()
                   .Encoded(false)
                   .Sanitized(false)
                   .SetWidth(10)
                   .Titled(string.Empty)
                   .RenderValueAs(x => @Html.ActionLink("Edit", "UserDetails", "Membership", null, null, "discount", new { @id = @x.Id }, new { @target = "_blank" }));

  }).WithPaging(200).EmptyText("There Are No Items To Display")

And the target page has TABS

<ul id="myTab" class="nav nav-tabs" role="tablist">

        <li class="active"><a href="#discount" role="tab" data-toggle="tab">Discount</a></li>
    </ul>

How to convert all elements in an array to integer in JavaScript?

_x000D_
_x000D_
var arr = ["1", "2", "3"];_x000D_
arr = arr.map(Number);_x000D_
console.log(arr); // [1, 2, 3]
_x000D_
_x000D_
_x000D_

Remove a symlink to a directory

# this works:
rm foo
# versus this, which doesn't:
rm foo/

Basically, you need to tell it to delete a file, not delete a directory. I believe the difference between rm and rmdir exists because of differences in the way the C library treats each.

At any rate, the first should work, while the second should complain about foo being a directory.

If it doesn't work as above, then check your permissions. You need write permission to the containing directory to remove files.

How to properly stop the Thread in Java?

Some supplementary info. Both flag and interrupt are suggested in the Java doc.

https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

private volatile Thread blinker;

public void stop() {
    blinker = null;
}

public void run() {
    Thread thisThread = Thread.currentThread();
    while (blinker == thisThread) {
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}

For a thread that waits for long periods (e.g., for input), use Thread.interrupt

public void stop() {
     Thread moribund = waiter;
      waiter = null;
      moribund.interrupt();
 }

Closing Applications

What role do they play when exiting an application in C#?

The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.

But what is the difference?

One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.

SQL Server 2005 Setting a variable to the result of a select query

What do you mean exactly? Do you want to reuse the result of your query for an other query?

In that case, why don't you combine both queries, by making the second query search inside the results of the first one (SELECT xxx in (SELECT yyy...)

how to stop Javascript forEach?

Breaking out of Array#forEach is not possible. (You can inspect the source code that implements it in Firefox on the linked page, to confirm this.)

Instead you should use a normal for loop:

function recurs(comment) {
    for (var i = 0; i < comment.comments.length; ++i) {
        var subComment = comment.comments[i];
        recurs(subComment);
        if (...) {
            break;
        }
    }
}

(or, if you want to be a little more clever about it and comment.comments[i] is always an object:)

function recurs(comment) {
    for (var i = 0, subComment; subComment = comment.comments[i]; ++i) {
        recurs(subComment);
        if (...) {
            break;
        }
    }
}

How to install sshpass on mac?

For the simple reason:

Andy-B-MacBook:~ l.admin$ brew install sshpass
Error: No available formula with the name "sshpass"
We won't add sshpass because it makes it too easy for novice SSH users to
ruin SSH's security.

Thus, the answer to do the curl / configure / install worked great for me on Mac.

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

How do I define the name of image built with docker-compose

Option 1: Hinting default image name

The name of the image generated by docker-compose depends on the folder name by default but you can override it by using --project-name argument:

$ docker-compose --project-name foo build bar
$ docker images foo_bar

Option 2: Specifying image name

Once docker-compose 1.6.0 is out, you may specify build: and image: to have an explicit image name (see arulraj.net's answer).

Option 3: Create image from container

A third is to create an image from the container:

$ docker-compose up -d bar
$ docker commit $(docker-compose ps -q bar) foo_bar
$ docker-compose rm -f bar

What's the difference between "2*2" and "2**2" in Python?

To specifically answer your question Why is the code1 used if we can use code2? I might suggest that the programmer was thinking in a mathematically broader sense. Specifically, perhaps the broader equation is a power equation, and the fact that both first numbers are "2" is more coincidence than mathematical reality. I'd want to make sure that the broader context of the code supports it being

var = x * x * y
in all cases, rather than in this specific case alone. This could get you in big trouble if x is anything but 2.

Creating instance list of different objects

How can I create a list without defining a class type? (<Employee>)

If I'm reading this correctly, you just want to avoid having to specify the type, correct?

In Java 7, you can do

List<Employee> list = new ArrayList<>();

but any of the other alternatives being discussed are just going to sacrifice type safety.

What regular expression will match valid international phone numbers?

The international numbering plan is based on the ITU E.164 numbering plan. I guess that's the starting point to your regular expression.

I'll update this if I get around to create a regular expression based on the ITU E.164 numbering.

Should operator<< be implemented as a friend or as a member function?

operator<< implemented as a friend function:

#include <iostream>
#include <string>
using namespace std;

class Samp
{
public:
    int ID;
    string strName; 
    friend std::ostream& operator<<(std::ostream &os, const Samp& obj);
};
 std::ostream& operator<<(std::ostream &os, const Samp& obj)
    {
        os << obj.ID<< “ ” << obj.strName;
        return os;
    }

int main()
{
   Samp obj, obj1;
    obj.ID = 100;
    obj.strName = "Hello";
    obj1=obj;
    cout << obj <<endl<< obj1;

} 

OUTPUT:
100 Hello
100 Hello

This can be a friend function only because the object is on the right hand side of operator<< and argument cout is on the left hand side. So this can't be a member function to the class, it can only be a friend function.

Image style height and width not taken in outlook mails

The px needs to be left off, for some odd reason.

List Git aliases

for windows:

git config --list | findstr "alias"

Inner join with 3 tables in mysql

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
 INNER JOIN student
   ON student.studentId = grade.fk_studentId
 INNER JOIN exam
   ON exam.examId = grade.fk_examId
 GROUP BY grade.gradeId
 ORDER BY exam.date

How to set Google Chrome in WebDriver

Aditya,

As you said in your last comment that you are trying to access chrome of some other system so based on that you should keep your chrome driver in that system itself.

for example: if you are trying to access linux chrome from windows then you need to put your chrome driver in linux at some place and give permission as 777 and use below code at your windows system.

System.setProperty("webdriver.chrome.driver", "\\var\\www\\Jar\\chromedriver");
Capability= DesiredCapabilities.chrome();   Capability.setPlatform(org.openqa.selenium.Platform.ANY);
browser=new RemoteWebDriver(new URL(nodeURL),Capability);

This is working code of my system.

Increasing the maximum number of TCP/IP connections in Linux

There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.

More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:

  • Check if your TCP window setting is large enough. Linux defaults are good for everything except really fast inet link (hundreds of mbps) or fast satellite links. What is your bandwidth*delay product?
  • Check for packet loss using ping with large packets (ping -s 1472 ...)
  • Check for rate limiting. On Linux, this is configured with tc
  • Confirm that the bandwidth you think exists actually exists using e.g., iperf
  • Confirm that your protocol is sane. Remember latency.
  • If this is a gigabit+ LAN, can you use jumbo packets? Are you?

Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat or lsof). If that number is substantial, you might:

  • Have a lot of bandwidth, e.g., 100mbps+. In this case, you may actually need to up the ulimit -n. Still, ~1000 connections (default on my system) is quite a few.
  • Have network problems which are slowing down your connections (e.g., packet loss)
  • Have something else slowing you down, e.g., IO bandwidth, especially if you're seeking. Have you checked iostat -x?

Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.

I hope this provides some help. You're really asking a networking question.

Using :before CSS pseudo element to add image to modal

1.this is my answer for your problem.

.ModalCarrot::before {
content:'';
background: url('blackCarrot.png'); /*url of image*/
height: 16px; /*height of image*/
width: 33px;  /*width of image*/
position: absolute;
}

Apply CSS rules to a nested class inside a div

Use Css Selector for this, or learn more about Css Selector just go here https://www.w3schools.com/cssref/css_selectors.asp

#main_text > .title {
  /* Style goes here */
}

#main_text .title {
  /* Style goes here */
}

ProgressDialog is deprecated.What is the alternate one to use?

You don't need to import any custom library.

I prefer to use the modern AlertDialog so this is the Kotlin version for the great answer posted by Kishan Donga in this page.

Kotlin code:

fun setProgressDialog(context:Context, message:String):AlertDialog {
    val llPadding = 30
    val ll = LinearLayout(context)
    ll.orientation = LinearLayout.HORIZONTAL
    ll.setPadding(llPadding, llPadding, llPadding, llPadding)
    ll.gravity = Gravity.CENTER
    var llParam = LinearLayout.LayoutParams(
                  LinearLayout.LayoutParams.WRAP_CONTENT,
                  LinearLayout.LayoutParams.WRAP_CONTENT)
    llParam.gravity = Gravity.CENTER
    ll.layoutParams = llParam

    val progressBar = ProgressBar(context)
    progressBar.isIndeterminate = true
    progressBar.setPadding(0, 0, llPadding, 0)
    progressBar.layoutParams = llParam

    llParam = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT)
    llParam.gravity = Gravity.CENTER
    val tvText = TextView(context)
    tvText.text = message
    tvText.setTextColor(Color.parseColor("#000000"))
    tvText.textSize = 20.toFloat()
    tvText.layoutParams = llParam

    ll.addView(progressBar)
    ll.addView(tvText)

    val builder = AlertDialog.Builder(context)
    builder.setCancelable(true)
    builder.setView(ll)

    val dialog = builder.create()
    val window = dialog.window
    if (window != null) {
        val layoutParams = WindowManager.LayoutParams()
        layoutParams.copyFrom(dialog.window?.attributes)
        layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT
        layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
                dialog.window?.attributes = layoutParams
    }
    return dialog
}

Usage:

val dialog = setProgressDialog(this, "Loading..")
dialog.show()

Output:

enter image description here

What's an easy way to read random line from a file in Unix command line?

Single bash line:

sed -n $((1+$RANDOM%`wc -l test.txt | cut -f 1 -d ' '`))p test.txt

Slight problem: duplicate filename.

How to smooth a curve in the right way?

This Question is already thoroughly answered, so I think a runtime analysis of the proposed methods would be of interest (It was for me, anyway). I will also look at the behavior of the methods at the center and the edges of the noisy dataset.

TL;DR

                    | runtime in s | runtime in s
method              | python list  | numpy array
--------------------|--------------|------------
kernel regression   | 23.93405     | 22.75967 
lowess              |  0.61351     |  0.61524 
naive average       |  0.02485     |  0.02326 
others*             |  0.00150     |  0.00150 
fft                 |  0.00021     |  0.00021 
numpy convolve      |  0.00017     |  0.00015 

*savgol with different fit functions and some numpy methods

Kernel regression scales badly, Lowess is a bit faster, but both produce smooth curves. Savgol is a middle ground on speed and can produce both jumpy and smooth outputs, depending on the grade of the polynomial. FFT is extremely fast, but only works on periodic data.

Moving average methods with numpy are faster but obviously produce a graph with steps in it.

Setup

I generated 1000 data points in the shape of a sin curve:

size = 1000
x = np.linspace(0, 4 * np.pi, size)
y = np.sin(x) + np.random.random(size) * 0.2
data = {"x": x, "y": y}

I pass these into a function to measure the runtime and plot the resulting fit:

def test_func(f, label):  # f: function handle to one of the smoothing methods
    start = time()
    for i in range(5):
        arr = f(data["y"], 20)
    print(f"{label:26s} - time: {time() - start:8.5f} ")
    plt.plot(data["x"], arr, "-", label=label)

I tested many different smoothing fuctions. arr is the array of y values to be smoothed and span the smoothing parameter. The lower, the better the fit will approach the original data, the higher, the smoother the resulting curve will be.

def smooth_data_convolve_my_average(arr, span):
    re = np.convolve(arr, np.ones(span * 2 + 1) / (span * 2 + 1), mode="same")

    # The "my_average" part: shrinks the averaging window on the side that 
    # reaches beyond the data, keeps the other side the same size as given 
    # by "span"
    re[0] = np.average(arr[:span])
    for i in range(1, span + 1):
        re[i] = np.average(arr[:i + span])
        re[-i] = np.average(arr[-i - span:])
    return re

def smooth_data_np_average(arr, span):  # my original, naive approach
    return [np.average(arr[val - span:val + span + 1]) for val in range(len(arr))]

def smooth_data_np_convolve(arr, span):
    return np.convolve(arr, np.ones(span * 2 + 1) / (span * 2 + 1), mode="same")

def smooth_data_np_cumsum_my_average(arr, span):
    cumsum_vec = np.cumsum(arr)
    moving_average = (cumsum_vec[2 * span:] - cumsum_vec[:-2 * span]) / (2 * span)

    # The "my_average" part again. Slightly different to before, because the
    # moving average from cumsum is shorter than the input and needs to be padded
    front, back = [np.average(arr[:span])], []
    for i in range(1, span):
        front.append(np.average(arr[:i + span]))
        back.insert(0, np.average(arr[-i - span:]))
    back.insert(0, np.average(arr[-2 * span:]))
    return np.concatenate((front, moving_average, back))

def smooth_data_lowess(arr, span):
    x = np.linspace(0, 1, len(arr))
    return sm.nonparametric.lowess(arr, x, frac=(5*span / len(arr)), return_sorted=False)

def smooth_data_kernel_regression(arr, span):
    # "span" smoothing parameter is ignored. If you know how to 
    # incorporate that with kernel regression, please comment below.
    kr = KernelReg(arr, np.linspace(0, 1, len(arr)), 'c')
    return kr.fit()[0]

def smooth_data_savgol_0(arr, span):  
    return savgol_filter(arr, span * 2 + 1, 0)

def smooth_data_savgol_1(arr, span):  
    return savgol_filter(arr, span * 2 + 1, 1)

def smooth_data_savgol_2(arr, span):  
    return savgol_filter(arr, span * 2 + 1, 2)

def smooth_data_fft(arr, span):  # the scaling of "span" is open to suggestions
    w = fftpack.rfft(arr)
    spectrum = w ** 2
    cutoff_idx = spectrum < (spectrum.max() * (1 - np.exp(-span / 2000)))
    w[cutoff_idx] = 0
    return fftpack.irfft(w)

Results

Speed

Runtime over 1000 elements, tested on a python list as well as a numpy array to hold the values.

method              | python list | numpy array
--------------------|-------------|------------
kernel regression   | 23.93405 s  | 22.75967 s
lowess              |  0.61351 s  |  0.61524 s
numpy average       |  0.02485 s  |  0.02326 s
savgol 2            |  0.00186 s  |  0.00196 s
savgol 1            |  0.00157 s  |  0.00161 s
savgol 0            |  0.00155 s  |  0.00151 s
numpy convolve + me |  0.00121 s  |  0.00115 s
numpy cumsum + me   |  0.00114 s  |  0.00105 s
fft                 |  0.00021 s  |  0.00021 s
numpy convolve      |  0.00017 s  |  0.00015 s

Especially kernel regression is very slow to compute over 1k elements, lowess also fails when the dataset becomes much larger. numpy convolve and fft are especially fast. I did not investigate the runtime behavior (O(n)) with increasing or decreasing sample size.

Edge behavior

I'll separate this part into two, to keep image understandable.

Numpy based methods + savgol 0:

Edge behaviour of numpy based methods

These methods calculate an average of the data, the graph is not smoothed. They all (with the exception of numpy.cumsum) result in the same graph when the window that is used to calculate the average does not touch the edge of the data. The discrepancy to numpy.cumsum is most likely due to a 'off by one' error in the window size.

There are different edge behaviours when the method has to work with less data:

  • savgol 0: continues with a constant to the edge of the data (savgol 1 and savgol 2 end with a line and parabola respectively)
  • numpy average: stops when the window reaches the left side of the data and fills those places in the array with Nan, same behaviour as my_average method on the right side
  • numpy convolve: follows the data pretty accurately. I suspect the window size is reduced symmetrically when one side of the window reaches the edge of the data
  • my_average/me: my own method that I implemented, because I was not satisfied with the other ones. Simply shrinks the part of the window that is reaching beyond the data to the edge of the data, but keeps the window to the other side the original size given with span

Complicated methods: Edge behaviour of the complicated methods

These methods all end with a nice fit to the data. savgol 1 ends with a line, savgol 2 with a parabola.

Curve behaviour

To showcase the behaviour of the different methods in the middle of the data.

Curve behavior of the different methods

The different savgol and average filters produce a rough line, lowess, fft and kernel regression produce a smooth fit. lowess appears to cut corners when the data changes.

Motivation

I have a Raspberry Pi logging data for fun and the visualization proved to be a small challenge. All data points, except RAM usage and ethernet traffic are only recorded in discrete steps and/or inherently noisy. For example the temperature sensor only outputs whole degrees, but differs by up to two degrees between consecutive measurements. No useful information can be gained from such a scatter plot. To visualize the data I therefore needed some method that is not too computationally expensive and produced a moving average. I also wanted nice behavior at the edges of the data, as this especially impacts the latest info when looking at live data. I settled on the numpy convolve method with my_average to improve the edge behavior.

Initializing a two dimensional std::vector

vector<vector<int>> board;
for(int i=0;i<m;i++) {
    board.push_back({});
    for(int j=0;j<n;j++) {
        board[i].push_back(0);
    }
}

This code snippet first inserts an empty vector at each turn, in the other nested loop it pushes the elements inside the vector created by the outer loop. Hope this solves the problem.

How to convert md5 string to normal text?

Md5 is a hashing algorithm. There is no way to retrieve the original input from the hashed result.

If you want to add a "forgotten password?" feature, you could send your user an email with a temporary link to create a new password.

Note: Sending passwords in plain text is a BAD idea :)

Converting string to number in javascript/jQuery

You can adding a + before the string without using parseInt and parseFloat and radix, Simply

sample:

var votevalue = +$('button').data('votevalue');

alert(typeof(votevalue));

navbar color in Twitter Bootstrap

You can customize your own version on the Bootstrap official website.

Stopping Docker containers by image name - Ubuntu

I was trying to wrap my Docker commands in gulp tasks and realised that you can do the following:

docker stop container-name
docker rm container-name

This might not work for scenarios where you have multiple containers with the same name (if that's possible), but for my use case it was perfect.

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

I ran into this same issue. Someone had logged onto my computer and used their TFS credentials. I'm running VS2012, Windows 7, and the network admins have Credential Manager disabled.

Run this command from a command window with the same user your running visual studio as.

rundll32.exe keymgr.dll,KRShowKeyMgr

You'll see a popup with all your stored credentials. Remove the one for your TFS server.

Note: You will need to restart visual studio because it caches the tfs credentials.

python mpl_toolkits installation issue

It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.

Solution

Uninstall matplotlib from pip then install it again with apt-get

python 2:

sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib

python 3:

sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib

How to install plugins to Sublime Text 2 editor?

Install the Package Control first.

The simplest method of installation is through the Sublime Text console. The console is accessed via the Ctrl+` shortcut or the View > Show Console menu. Once open, paste the appropriate Python code for your version of Sublime Text into the console.

Code for Sublime Text 3

import urllib.request,os; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); open(os.path.join(ipp, pf), 'wb').write(urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ','%20')).read())

Code for Sublime Text 2

import urllib2,os; pf='Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler( ))); open( os.path.join( ipp, pf), 'wb' ).write( urllib2.urlopen( 'http://sublime.wbond.net/' +pf.replace( ' ','%20' )).read()); print( 'Please restart Sublime Text to finish installation')

For the up-to-date installation code, please check Package Control Installation Guide.

Manual

If for some reason the console installation instructions do not work for you (such as having a proxy on your network), perform the following steps to manually install Package Control:

  1. Click the Preferences > Browse Packages… menu
  2. Browse up a folder and then into the Installed Packages/ folder
  3. Download Package Control.sublime-package and copy it into the Installed Packages/ directory
  4. Restart Sublime Text

Usage

Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+p (Win, Linux) or CMD+Shift+p (OSX). All Package Control commands begin with Package Control:, so start by typing Package.

Java way to check if a string is palindrome

I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:

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

public class PalindromeRecursiveBoolean {

    public static boolean isPalindrome(String str) {

        str = str.toUpperCase();
        char[] strChars = str.toCharArray();

        List<Character> word = new ArrayList<>();
        for (char c : strChars) {
            word.add(c);
        }

        while (true) {
            if ((word.size() == 1) || (word.size() == 0)) {
                return true;
            }
            if (word.get(0) == word.get(word.size() - 1)) {
                word.remove(0);
                word.remove(word.size() - 1);
            } else {
                return false;

            }

        }
    }
}
  1. If the string is made of no letters or just one letter, it is a palindrome.
  2. Otherwise, compare the first and last letters of the string.
    • If the first and last letters differ, then the string is not a palindrome
    • Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.

The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Reverse colormap in matplotlib

In matplotlib a color map isn't a list, but it contains the list of its colors as colormap.colors. And the module matplotlib.colors provides a function ListedColormap() to generate a color map from a list. So you can reverse any color map by doing

colormap_r = ListedColormap(colormap.colors[::-1])

How can I tell how many objects I've stored in an S3 bucket?

Go to AWS Billing, then reports, then AWS Usage reports. Select Amazon Simple Storage Service, then Operation StandardStorage. Then you can download a CSV file that includes a UsageType of StorageObjectCount that lists the item count for each bucket.

Accessing member of base class

Working example. Notes below.

class Animal {
    constructor(public name) {
    }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    move() {
        alert(this.name + " is Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    move() {
        alert(this.name + " is Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);
  1. You don't need to manually assign the name to a public variable. Using public name in the constructor definition does this for you.

  2. You don't need to call super(name) from the specialised classes.

  3. Using this.name works.

Notes on use of super.

This is covered in more detail in section 4.9.2 of the language specification.

The behaviour of the classes inheriting from Animal is not dissimilar to the behaviour in other languages. You need to specify the super keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move() or this.move() you would be dealing with the specialised Snake or Horse function, so using super.move() explicitly calls the base class function.

There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name and this.name - there is simply this.name. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.

How to change a DIV padding without affecting the width/height ?

Sounds like you're looking to simulate the IE6 box model. You could use the CSS 3 property box-sizing: border-box to achieve this. This is supported by IE8, but for Firefox you would need to use -moz-box-sizing and for Safari/Chrome, use -webkit-box-sizing.

IE6 already computes the height wrong, so you're good in that browser, but I'm not sure about IE7, I think it will compute the height the same in quirks mode.

Java - Convert image to Base64

The line

base64String = Base64.encode(byteArray);

converts the full array (102400 bytes) to Base64, not just the number of bytes you have read. You need to pass it the numbers of bytes.

How to get form values in Symfony2 controller

private function getFormDataArray($form)
{
    $data = [];
    foreach ( $form as $key => $value) {
        $data[$key] = $value->getData();
    }
    return $data;
}

Move a view up only when the keyboard covers an input field

Swift 3

@IBOutlet var scrollView: UIScrollView!
@IBOutlet var edtEmail: UITextField!
@IBOutlet var bottomTextfieldConstrain: NSLayoutConstraint! // <- this guy is the constrain that connect the bottom of textField to lower object or bottom of page!

 @IBAction func edtEmailEditingDidBegin(_ sender: Any) { 
        self.bottomTextfieldConstrain.constant = 200
        let point = CGPoint(x: 0, y: 200)
        scrollView.contentOffset = point
    }

@IBAction func edtEmailEditingDidEnd(_ sender: Any) { 
    self.bottomTextfieldConstrain.constant = 50
}

Create a new txt file using VB.NET

You can try writing into the Documents folder. Here is a "debug" function I did for the debugging needs of my project:

Private Sub writeDebug(ByVal x As String)
    Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    Dim FILE_NAME As String = path & "\mydebug.txt"
    MsgBox(FILE_NAME)
    If System.IO.File.Exists(FILE_NAME) = False Then
        System.IO.File.Create(FILE_NAME).Dispose()
    End If
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
    objWriter.WriteLine(x)
    objWriter.Close()
End Sub

There are more standard folders you can access through the "SpecialFolder" object.

Javascript validation: Block special characters

A few of the options are deprecated as of today. So watch out for those.

If you try <input onkeypress="blockSpecialCharacters(event)" />, an IDE like WebStorm will slash out event and tell you:

Deprecated symbol used, consults docs for better alternative

Then when you get to the JavaScript, console.log(e.keyCode) will also give keyCode and say:

Deprecated symbol used, consults docs for better alternative

Anyways I did it using jQuery.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

<input id="theInput" />

<script>
    function blockSpecialCharacters(e) {
            let key = e.key;
            let keyCharCode = key.charCodeAt(0);

            // 0-9
            if(keyCharCode >= 48 && keyCharCode <= 57) {
                return key;
            }
            // A-Z
            if(keyCharCode >= 65 && keyCharCode <= 90) {
                return key;
            }
            // a-z
            if(keyCharCode >= 97 && keyCharCode <= 122) {
                return key;
            }

            return false;
    }

    $('#theInput').keypress(function(e) {
        blockSpecialCharacters(e);
    });
</script>

How do I download NLTK data?

If you are running a really old version of nltk, then there is indeed no download module available (reference)

Try this:

import nltk
print(nltk.__version__)

As per the reference, anything after 0.9.5 should be fine

Regular expression to extract numbers from a string

you could use something like:

[^0-9]+([0-9]+)[^0-9]+([0-9]+).+

Then get the first and second capture groups.

Setting the selected attribute on a select list using jQuery

I'd iterate through the options, comparing the text to what I want to be selected, then set the selected attribute on that option. Once you find the correct one, terminate the iteration (unless you have a multiselect).

 $('#dropdown').find('option').each( function() {
      var $this = $(this);
      if ($this.text() == 'B') {
         $this.attr('selected','selected');
         return false;
      }
 });

How to "grep" out specific line ranges of a file

The following command will do what you asked for "extract the lines between 1234 and 5555" in someFile.

sed -n '1234,5555p' someFile

Printing image with PrintDocument. how to adjust the image to fit paper size

You can use my code here

//Print Button Event Handeler
private void btnPrint_Click(object sender, EventArgs e)
{
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += PrintPage;
    //here to select the printer attached to user PC
    PrintDialog printDialog1 = new PrintDialog();
    printDialog1.Document = pd;
    DialogResult result = printDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        pd.Print();//this will trigger the Print Event handeler PrintPage
    }
}

//The Print Event handeler
private void PrintPage(object o, PrintPageEventArgs e)
{
    try
    {
        if (File.Exists(this.ImagePath))
        {
            //Load the image from the file
            System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");

            //Adjust the size of the image to the page to print the full image without loosing any part of it
            Rectangle m = e.MarginBounds;

            if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
            {
                m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
            }
            else
            {
                m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
            }
            e.Graphics.DrawImage(img, m);
        }
    }
    catch (Exception)
    {

    }
}

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

How to increment datetime by custom months in python without using library

This is what I came up with

from calendar  import monthrange

def same_day_months_after(start_date, months=1):
    target_year = start_date.year + ((start_date.month + months) / 12)
    target_month = (start_date.month + months) % 12
    num_days_target_month = monthrange(target_year, target_month)[1]
    return start_date.replace(year=target_year, month=target_month, 
        day=min(start_date.day, num_days_target_month))

Target WSGI script cannot be loaded as Python module

If you install your project’s Python dependencies inside a virtualenv, you’ll need to add the path to this virtualenv’s directory to your Python path as well. To do this, add an additional path to your WSGIPythonPath directive, with multiple paths separated by a colon (:) if using a UNIX-like system, or a semicolon (;) if using Windows

iOS app 'The application could not be verified' only on one device

just delete the app and try again, it happens to me when i try to launch over a device that has the same app but generated by an ipa file.

How to move/rename a file using an Ansible task on a remote system

I have found the creates option in the command module useful. How about this:

- name: Move foo to bar
  command: creates="path/to/bar" mv /path/to/foo /path/to/bar

I used to do a 2 task approach using stat like Bruce P suggests. Now I do this as one task with creates. I think this is a lot clearer.

How can I manually generate a .pyc file from a .py file

You can compile individual files(s) from the command line with:

python -m compileall <file_1>.py <file_n>.py

MySQL Join Where Not Exists

I'd use a 'where not exists' -- exactly as you suggest in your title:

SELECT `voter`.`ID`, `voter`.`Last_Name`, `voter`.`First_Name`,
       `voter`.`Middle_Name`, `voter`.`Age`, `voter`.`Sex`,
       `voter`.`Party`, `voter`.`Demo`, `voter`.`PV`,
       `household`.`Address`, `household`.`City`, `household`.`Zip`
FROM (`voter`)
JOIN `household` ON `voter`.`House_ID`=`household`.`id`
WHERE `CT` = '5'
AND `Precnum` = 'CTY3'
AND  `Last_Name`  LIKE '%Cumbee%'
AND  `First_Name`  LIKE '%John%'

AND NOT EXISTS (
  SELECT * FROM `elimination`
   WHERE `elimination`.`voter_id` = `voter`.`ID`
)

ORDER BY `Last_Name` ASC
LIMIT 30

That may be marginally faster than doing a left join (of course, depending on your indexes, cardinality of your tables, etc), and is almost certainly much faster than using IN.

How do I delete from multiple tables using INNER JOIN in SQL server

  1. You can always set up cascading deletes on the relationships of the tables.

  2. You can encapsulate the multiple deletes in one stored procedure.

  3. You can use a transaction to ensure one unit of work.

Check if value exists in dataTable?

DataRow rw = table.AsEnumerable().FirstOrDefault(tt => tt.Field<string>("Author") == "Name");
if (rw != null)
{
// row exists
}

add to your using clause :

using System.Linq;

and add :

System.Data.DataSetExtensions

to references.

Mock functions in Go

If you change your function definition to use a variable instead:

var get_page = func(url string) string {
    ...
}

You can override it in your tests:

func TestDownloader(t *testing.T) {
    get_page = func(url string) string {
        if url != "expected" {
            t.Fatal("good message")
        }
        return "something"
    }
    downloader()
}

Careful though, your other tests might fail if they test the functionality of the function you override!

The Go authors use this pattern in the Go standard library to insert test hooks into code to make things easier to test:

how to use ng-option to set default value of select element

So assuming that object is in your scope:

<div ng-controller="MyCtrl">
  <select ng-model="prop.value" ng-options="v for v in prop.values">
  </select>
</div>

 

function MyCtrl($scope) {
  $scope.prop = {
    "type": "select", 
    "name": "Service",
    "value": "Service 3", 
    "values": [ "Service 1", "Service 2", "Service 3", "Service 4"] 
  };
}

Working Plunkr: http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g

Cleaning up old remote git branches

Consider to run :

git fetch --prune

On a regular basis in each repo to remove local branches that have been tracking a remote branch that is deleted (no longer exists in remote GIT repo).

This can be further simplified by

git config remote.origin.prune true

this is a per-repo setting that will make any future git fetch or git pull to automatically prune.

To set this up for your user, you may also edit the global .gitconfig and add

[fetch]
    prune = true

However, it's recommended that this is done using the following command:

git config --global fetch.prune true

or to apply it system wide (not just for the user)

git config --system fetch.prune true

Why Java Calendar set(int year, int month, int date) not returning correct date?

1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:

c1.set(2000, Calendar.JANUARY, 30);

vagrant login as root by default

Adding this to the Vagrantfile worked for me. These lines are the equivalent of you entering sudo su - every time you login. Please notice that this requires reprovisioning the VM.

config.vm.provision "shell", inline: <<-SHELL
    echo "sudo su -" >> .bashrc
SHELL

Converting integer to string in Python

If you need unary numeral system, you can convert an integer like this:

>> n = 6
>> '1' * n
'111111'

If you need a support of negative ints you can just write like that:

>> n = -6
>> '1' * n if n >= 0 else '-' + '1' * (-n)
'-111111'

Zero is special case which takes an empty string in this case, which is correct.

>> n = 0
>> '1' * n if n >= 0 else '-' + '1' * (-n)
''

How to copy directories with spaces in the name

After some trial and error and observing the results (in other words, I hacked it), I got it to work.

Quotes ARE required to use a path name with spaces. The trick is there MUST be a space after the path names before the closing quote...like this...

robocopy "C:\Source Path " "C:\Destination Path " /option1 /option2...

This almost seems like a bug and certainly not very intuitive.

Todd K.

Bootstrap modal appearing under background

Also, make sure that version of BootStrap css and js are the same ones. Different versions can also make modal appearing under background:

For example:

Bad:

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>

Good:

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

How do I check that multiple keys are in a dict in a single pass?

In case you want to:

  • also get the values for the keys
  • check more than one dictonary

then:

from operator import itemgetter
foo = {'foo':1,'zip':2,'zam':3,'bar':4}
keys = ("foo","bar") 
getter = itemgetter(*keys) # returns all values
try:
    values = getter(foo)
except KeyError:
    # not both keys exist
    pass

What does SQL clause "GROUP BY 1" mean?

In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.

This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.

If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

In my case I had written const Tab = createBottomTabNavigator instead of const Tab = createBottomTabNavigator()

How to set UICollectionViewCell Width and Height programmatically

Size ratio according to iPhone size :

Here's what you can do to have different width and height for cell's regarding the iPhone size :

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let width = (self.view.frame.size.width - 12 * 3) / 3 //some width
    let height = width * 1.5 //ratio
    return CGSize(width: width, height: height)
}

And maybe you should also disable your AutoLayout constraints on cell for this answer to work.

printf not printing on console

Apparently this is a known bug of Eclipse. This bug is resolved with the resolution of WONT-FIX. I have no idea why though. here is the link: Eclipse C Console Bug.

getting file size in javascript

If it's not a local application powered by JavaScript with full access permissions, you can't get the size of any file just from the path name. Web pages running javascript do not have access to the local filesystem for security reasons.

You can use a graceful degrading file uploader like SWFUpload if you want to show a progress bar. HTML5 also has the File API, but that is not widely supported just yet. If a user selects the file for an input[type=file] element, you can get details about the file from the files collection:

alert(myInp.files[0].size);

How to access the php.ini from my CPanel?

Cpanel 60.0.26 (Latest Version) Php.ini moved under Software > Select PHP Version > Switch to Php Options > Change Value > save.

How to create a JQuery Clock / Timer

################## JQuery (use API) #################   
 $(document).ready(function(){
         function getdate(){
                var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
             if(s<10){
                 s = "0"+s;
             }
             if (m < 10) {
                m = "0" + m;
            }
            $("h1").text(h+" : "+m+" : "+s);
             setTimeout(function(){getdate()}, 500);
            }

        $("button").click(getdate);
    });

################## HTML ###################
<button>start clock</button>
<h1></h1>

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

In other words...

IDE Even your notepad is an IDE. Every software you write/compile code with is an IDE.

Library A bunch of code which simplifies functions/methods for quick use.

API A programming interface for functions/configuration which you work with, its usage is often documented.

SDK Extras and/or for development/testing purposes.

ToolKit Tiny apps for quick use, often GUIs.

GUI Apps with a graphical interface, requires no knowledge of programming unlike APIs.

Framework Bunch of APIs/huge Library/Snippets wrapped in a namespace/or encapsulated from outer scope for compact handling without conflicts with other code.

MVC A design pattern separated in Models, Views and Controllers for huge applications. They are not dependent on each other and can be changed/improved/replaced without to take care of other code.

Example:

Car (Model)
The object that is being presented.
Example in IT: A HTML form.


Camera (View)
Something that is able to see the object(car).
Example in IT: Browser that renders a website with the form.


Driver (Controller)
Someone who drives that car.
Example in IT: Functions which handle form data that's being submitted.

Snippets Small codes of only a few lines, may not be even complete but worth for a quick share.

Plug-ins Exclusive functions for specified frameworks/APIs/libraries only.

Add-ons Additional modules or services for specific GUIs.

Dockerfile if else condition with external arguments

The accepted answer may solve the question, but if you want multiline if conditions in the dockerfile, you can do that placing \ at the end of each line (similar to how you would do in a shell script) and ending each command with ;. You can even define someting like set -eux as the 1st command.

Example:

RUN set -eux; \
  if [ -f /path/to/file ]; then \
    mv /path/to/file /dest; \
  fi; \
  if [ -d /path/to/dir ]; then \
    mv /path/to/dir /dest; \
  fi

In your case:

FROM centos:7
ARG arg
RUN if [ -z "$arg" ] ; then \
    echo Argument not provided; \
  else \
    echo Argument is $arg; \
  fi

Then build with:

docker build -t my_docker . --build-arg arg=42

How to run JUnit tests with Gradle?

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

sourceSets {
    test {
        java.srcDirs += [
                'src/customDir/test/kotlin'
        ]
        print(java.srcDirs)   // Clean
    }
}

Pay attention to the operator += and if you want to run integration tests change test to androidTest.

GL

Can you set a border opacity in CSS?

No, there is no way to only set the opacity of a border with css.

For example, if you did not know the color, there is no way to only change the opacity of the border by simply using rgba().

Only read selected columns

You could also use JDBC to achieve this. Let's create a sample csv file.

write.table(x=mtcars, file="mtcars.csv", sep=",", row.names=F, col.names=T) # create example csv file

Download and save the the CSV JDBC driver from this link: http://sourceforge.net/projects/csvjdbc/files/latest/download

> library(RJDBC)

> path.to.jdbc.driver <- "jdbc//csvjdbc-1.0-18.jar"
> drv <- JDBC("org.relique.jdbc.csv.CsvDriver", path.to.jdbc.driver)
> conn <- dbConnect(drv, sprintf("jdbc:relique:csv:%s", getwd()))

> head(dbGetQuery(conn, "select * from mtcars"), 3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1   21   6  160 110  3.9  2.62 16.46  0  1    4    4
2   21   6  160 110  3.9 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85  2.32 18.61  1  1    4    1

> head(dbGetQuery(conn, "select mpg, gear from mtcars"), 3)
   MPG GEAR
1   21    4
2   21    4
3 22.8    4

How to enable C++17 compiling in Visual Studio?

MSBuild (Visual Studio project/solution *.vcproj/*.sln):

Add to Additional options in Project Settings: /std:c++latest to enable latest features - currently C++17 as of VS2017, VS2015 Update 3.

https://blogs.msdn.microsoft.com/vcblog/2016/06/07/standards-version-switches-in-the-compiler/

/permissive- will disable non-standard C++ extensions and will enable standard conformance in VS2017.

https://blogs.msdn.microsoft.com/vcblog/2016/11/16/permissive-switch/

EDIT (Oct 2018): The latest VS2017 features are documented here:

https://docs.microsoft.com/en-gb/cpp/build/reference/std-specify-language-standard-version

VS2017 supports: /std:[c++14|c++17|c++latest] now. These flags can be set via the project's property pages:

To set this compiler option in the Visual Studio development environment

  1. Open the project's Property Pages dialog box. For details, see Working with Project Properties.
  2. Select Configuration Properties, C/C++, Language.
  3. In C++ Language Standard, choose the language standard to support from the dropdown control, then choose OK or Apply to save your changes.

CMake:

Visual Studio 2017 (15.7+) supports CMake projects. CMake makes it possible to enable modern C++ features in various ways. The most basic option is to enable a modern C++ standard by setting a target's property in CMakeLists.txt:

add_library (${PROJECT_NAME})
set_property (TARGET ${PROJECT_NAME}
  PROPERTY
    # Enable C++17 standard compliance
    CXX_STANDARD 17
)

In the case of an interface library:

add_library (${PROJECT_NAME} INTERFACE)
target_compile_features (${PROJECT_NAME}
  INTERFACE
    # Enable C++17 standard compliance
    cxx_std_17
)

Sending credentials with cross-domain posts?

In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:

$.ajax(
        'https://foo.bar.com,
        {
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: successFunc
        }
    );

The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:

An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT

Return value from exec(@sql)

On the one hand you could use sp_executesql:

exec sp_executesql N'select @rowcount=count(*) from anytable', 
                    N'@rowcount int output', @rowcount output;

On the other hand you could use a temporary table:

declare @result table ([rowcount] int);
insert into @result ([rowcount])
exec (N'select count(*) from anytable');
declare @rowcount int = (select top (1) [rowcount] from @result);

jQuery - Dynamically Create Button and Attach Event Handler

Your problem is that you're converting the button into an HTML snippet when you add it to the table, but that snippet is not the same object as the one that has the click handler on it.

$("#myButton").click(function () {
    var test = $('<button>Test</button>').click(function () {
        alert('hi');
    });

    $("#nodeAttributeHeader").css('display', 'table-row'); // NB: changed

    var tr = $('<tr>').insertBefore('#addNodeTable tr:last');
    var td = $('<td>').append(test).appendTo(tr);
});

How can I set NODE_ENV=production on Windows?

If you are using Visual Studio with NTVS, you can set the environment variables on the project properties page:

Visual Studio NTVS Project Properties

As you can see, the Configuration and Platform dropdowns are disabled (I haven't looked too far into why this is), but if you edit your .njsproj file as follows:

  <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
    <DebugSymbols>true</DebugSymbols>
    <Environment>NODE_ENV=development</Environment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
    <DebugSymbols>true</DebugSymbols>
    <Environment>NODE_ENV=production</Environment>
  </PropertyGroup>

The 'Debug / Release' dropdown will then control how the variable is set before starting Node.js.

Assign result of dynamic sql to variable

You should try this while getting SEQUENCE value in a variable from the dynamic table.

DECLARE @temp table (#temp varchar (MAX));
DECLARE @SeqID nvarchar(150);
DECLARE @Name varchar(150); 

SET @Name = (Select Name from table)
SET @SeqID = 'SELECT NEXT VALUE FOR '+ @Name + '_Sequence'
insert @temp exec (@SeqID)

SET @SeqID = (select * from @temp )
PRINT @SeqID

Result:

(1 row(s) affected)
 1

Range of values in C Int and Long 32 - 64 bits

In C and C++ you have these least requirements (i.e actual implementations can have larger magnitudes)

signed char: -2^07+1 to +2^07-1
short:       -2^15+1 to +2^15-1
int:         -2^15+1 to +2^15-1
long:        -2^31+1 to +2^31-1
long long:   -2^63+1 to +2^63-1

Now, on particular implementations, you have a variety of bit ranges. The wikipedia article describes this nicely.

The result of a query cannot be enumerated more than once

Try explicitly enumerating the results by calling ToList().

Change

foreach (var item in query)

to

foreach (var item in query.ToList())

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

I had such error while trying to build a docker image and push to the container registry. Inside my docker file I tried to copy a jar file from target folder and try to execute it with java -jar command.

I was solving the issue by removing .jar file and target folder from .gitignore file.

Programmatically check Play Store for app updates

Apart from using JSoup, we can alternatively do pattern matching for getting the app version from playStore.

To match the latest pattern from google playstore ie <div class="BgcNfc">Current Version</div><span class="htlgb"><div><span class="htlgb">X.X.X</span></div> we first have to match the above node sequence and then from above sequence get the version value. Below is the code snippet for same:

    private String getAppVersion(String patternString, String inputString) {
        try{
            //Create a pattern
            Pattern pattern = Pattern.compile(patternString);
            if (null == pattern) {
                return null;
            }

            //Match the pattern string in provided string
            Matcher matcher = pattern.matcher(inputString);
            if (null != matcher && matcher.find()) {
                return matcher.group(1);
            }

        }catch (PatternSyntaxException ex) {

            ex.printStackTrace();
        }

        return null;
    }


    private String getPlayStoreAppVersion(String appUrlString) {
        final String currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>";
        final String appVersion_PatternSeq = "htlgb\">([^<]*)</s";
        String playStoreAppVersion = null;

        BufferedReader inReader = null;
        URLConnection uc = null;
        StringBuilder urlData = new StringBuilder();

        final URL url = new URL(appUrlString);
        uc = url.openConnection();
        if(uc == null) {
           return null;
        }
        uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
        inReader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        if (null != inReader) {
            String str = "";
            while ((str = inReader.readLine()) != null) {
                           urlData.append(str);
            }
        }

        // Get the current version pattern sequence 
        String versionString = getAppVersion (currentVersion_PatternSeq, urlData.toString());
        if(null == versionString){ 
            return null;
        }else{
            // get version from "htlgb">X.X.X</span>
            playStoreAppVersion = getAppVersion (appVersion_PatternSeq, versionString);
        }

        return playStoreAppVersion;
    }

I got it solved through this, as this works for latest Google playstore changes also. Hope that helps.

How to start a background process in Python?

Note: This answer is less current than it was when posted in 2009. Using the subprocess module shown in other answers is now recommended in the docs

(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)


If you want your process to start in the background you can either use system() and call it in the same way your shell script did, or you can spawn it:

import os
os.spawnl(os.P_DETACH, 'some_long_running_command')

(or, alternatively, you may try the less portable os.P_NOWAIT flag).

See the documentation here.

<DIV> inside link (<a href="">) tag

Nesting of 'a' will not be possible. However if you badly want to keep the structure and still make it work like the way you want, then override the anchor tag click in javascript /jquery .

so you can have 2 event listeners for the two and control them accordingly.

Default values in a C Struct

Since it looks like that you only need this structure for the update() function, don't use a structure for this at all, it will only obfuscate your intention behind that construct. You should maybe rethink why you are changing and updating those fields and define separate functions or macros for this "little" changes.

e.g.


#define set_current_route(id, route) update(id, dont_care, dont_care, route)
#define set_route(id, route) update(id, dont_care, route, dont_care)
#define set_backup_route(id, route) update(id, route, dont_care, dont_care)

Or even better write a function for every change case. As you already noticed you don't change every property at the same time, so make it possible to change only one property at a time. This doesn't only improve the readability, but also helps you handling the different cases, e.g. you don't have to check for all the "dont_care" because you know that only the current route is changed.