Programs & Examples On #Stringwriter

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

Just put the

Response.End();

within a finally block instead of within the try block.

This has worked for me!!!.

I had the following problematic (with the Exception) code structure

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);
   Response.End();

   return;

 } 

 some_more_code...

 Reponse.Write(...);
 Response.End();

}
catch(Exception){
}
finally{}

and it throws the exception. I suspect the Exception is thrown where there is code / work to execute after response.End(); . In my case the extra code was just the return itself.

When I just moved the response.End(); to the finally block (and left the return in its place - which causes skipping the rest of code in the try block and jumping to the finally block (not just exiting the containing function) ) the Exception ceased to take place.

The following works OK:

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);

   return;

 } 

 some_more_code...

 Reponse.Write(...);

}
catch(Exception){
}
finally{
    Response.End();
}

Pretty printing JSON from Jackson 2.2's ObjectMapper

If you'd like to turn this on by default for ALL ObjectMapper instances in a process, here's a little hack that will set the default value of INDENT_OUTPUT to true:

val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

Step 1: View page code

<input type="button" id="btnExport" value="Export" class="btn btn-primary" />
<script>
  $(document).ready(function () {

 $('#btnExport').click(function () {          

  window.location = '/Inventory/ExportInventory';

        });
});
</script>

Step 2: Controller Code

  public ActionResult ExportInventory()
        {
            //Load Data
            var dataInventory = _inventoryService.InventoryListByPharmacyId(pId);
            string xml=String.Empty;
            XmlDocument xmlDoc = new XmlDocument();

            XmlSerializer xmlSerializer = new XmlSerializer(dataInventory.GetType());

            using (MemoryStream xmlStream = new MemoryStream())
            {
                xmlSerializer.Serialize(xmlStream, dataInventory);
                xmlStream.Position = 0;
                xmlDoc.Load(xmlStream);
                xml = xmlDoc.InnerXml;
            }

            var fName = string.Format("Inventory-{0}", DateTime.Now.ToString("s"));

            byte[] fileContents = Encoding.UTF8.GetBytes(xml);

            return File(fileContents, "application/vnd.ms-excel", fName);
        }

Jackson serialization: ignore empty values (or null)

Or you can use GSON [https://code.google.com/p/google-gson/], where these null fields will be automatically removed.

SampleDTO.java

public class SampleDTO {

    String username;
    String email;
    String password;
    String birthday;
    String coinsPackage;
    String coins;
    String transactionId;
    boolean isLoggedIn;

    // getters/setters
}

Test.java

import com.google.gson.Gson;

public class Test {

    public static void main(String[] args) {
        SampleDTO objSampleDTO = new SampleDTO();
        Gson objGson = new Gson();
        System.out.println(objGson.toJson(objSampleDTO));
    }
}

OUTPUT:

{"isLoggedIn":false}

I used gson-2.2.4

gridview data export to excel in asp.net

The Best way is to use closedxml. Below is the link for reference

https://closedxml.codeplex.com/wikipage?title=Adding%20DataTable%20as%20Worksheet&referringTitle=Documentation

and you can simple use

    var wb = new ClosedXML.Excel.XLWorkbook();
DataTable dt = GeDataTable();//refer documentaion

wb.Worksheets.Add(dt);

Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\"");

using (var ms = new System.IO.MemoryStream()) {
    wb.SaveAs(ms);
    ms.WriteTo(Response.OutputStream);
    ms.Close();
}

Response.End();

Convert an object to an XML string

I realize this is a very old post, but after looking at L.B's response I thought about how I could improve upon the accepted answer and make it generic for my own application. Here's what I came up with:

public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new System.IO.StringWriter();
        var serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(stringwriter, dataToSerialize);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}

These methods can now be placed in a static helper class, which means no code duplication to every class that needs to be serialized.

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

In my case, the problem was caused by some Response.Write commands at Master Page of the website (code behind). They were there only for debugging purposes (that's not the best way, I know)...

Setting HttpContext.Current.Session in a unit test

You can "fake it" by creating a new HttpContext like this:

http://www.necronet.org/archive/2010/07/28/unit-testing-code-that-uses-httpcontext-current-session.aspx

I've taken that code and put it on an static helper class like so:

public static HttpContext FakeHttpContext()
{
    var httpRequest = new HttpRequest("", "http://example.com/", "");
    var stringWriter = new StringWriter();
    var httpResponse = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponse);

    var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                            new HttpStaticObjectsCollection(), 10, true,
                                            HttpCookieMode.AutoDetect,
                                            SessionStateMode.InProc, false);

    httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                BindingFlags.NonPublic | BindingFlags.Instance,
                                null, CallingConventions.Standard,
                                new[] { typeof(HttpSessionStateContainer) },
                                null)
                        .Invoke(new object[] { sessionContainer });

    return httpContext;
}

Or instead of using reflection to construct the new HttpSessionState instance, you can just attach your HttpSessionStateContainer to the HttpContext (as per Brent M. Spell's comment):

SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);

and then you can call it in your unit tests like:

HttpContext.Current = MockHelper.FakeHttpContext();

Unable to find velocity template resources

I have put this working code snippet for future references. The code sample was written with Apache velocity version 1.7 with embedded Jetty.

Velocity template path is located at the resource folder email_templates subfolder.

enter image description here

Code Snippet in Java (Snippets are worked both running on eclipse and inside a Jar)

    templateName = "/email_templates/byoa.tpl.vm"
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();
    Template t = ve.getTemplate(this.templateName);
    VelocityContext velocityContext = new VelocityContext();
    velocityContext.put("","") // put your template values here
    StringWriter writer = new StringWriter();
    t.merge(this.velocityContext, writer);

System.out.println(writer.toString()); // print the updated template as string

For OSGI plugging code snippets.

final String TEMPLATE = "resources/template.vm" // located in the resources folder
Thread current = Thread.currentThread();
       ClassLoader oldLoader = current.getContextClassLoader();
       try {
          current.setContextClassLoader(TemplateHelper.class.getClassLoader()); // TemplateHelper is a class inside your jar file
          Properties p = new Properties();
          p.setProperty("resource.loader", "class");
          p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
          Velocity.init( p );       
          VelocityEngine ve = new VelocityEngine();
          Template template = Velocity.getTemplate( TEMPLATE );
          VelocityContext context = new VelocityContext();
          context.put("tc", obj);
          StringWriter writer = new StringWriter();
          template.merge( context, writer );
          return writer.toString() ;  
       }  catch(Exception e){
          e.printStackTrace();
       } finally {
          current.setContextClassLoader(oldLoader);
       }

How to convert String to DOM Document object in java?

Either escape the double quotes with \

String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"

or use single quotes instead

String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"

How do I use a custom Serializer with Jackson?

In my case (Spring 3.2.4 and Jackson 2.3.1), XML configuration for custom serializer:

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                    <property name="serializers">
                        <array>
                            <bean class="com.example.business.serializer.json.CustomObjectSerializer"/>
                        </array>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

was in unexplained way overwritten back to default by something.

This worked for me:

CustomObject.java

@JsonSerialize(using = CustomObjectSerializer.class)
public class CustomObject {

    private Long value;

    public Long getValue() {
        return value;
    }

    public void setValue(Long value) {
        this.value = value;
    }
}

CustomObjectSerializer.java

public class CustomObjectSerializer extends JsonSerializer<CustomObject> {

    @Override
    public void serialize(CustomObject value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException,JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeNumberField("y", value.getValue());
        jgen.writeEndObject();
    }

    @Override
    public Class<CustomObject> handledType() {
        return CustomObject.class;
    }
}

No XML configuration (<mvc:message-converters>(...)</mvc:message-converters>) is needed in my solution.

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just after your Page_Load add this:

public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
}

Note that I don't do anything in the function.

EDIT: Tim answered the same thing. :) You can also find the answer Here

Converting xml to string using C#

There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

How to store printStackTrace into a string

Along the lines of Guava, Apache Commons Lang has ExceptionUtils.getFullStackTrace in org.apache.commons.lang.exception. From a prior answer on StackOverflow.

Export to CSV using MVC, C# and jQuery

yan.kun was on the right track but this is much much easier.

    public FileContentResult DownloadCSV()
    {
        string csv = "Charlie, Chaplin, Chuckles";
        return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");
    }

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

You could also use the RenderView Controller extension from here (source)

and use it like this:

public ActionResult Do() {
var html = this.RenderView("index", theModel);
...
}

it works for razor and web-forms viewengines

Fastest way to serialize and deserialize .NET objects

I took the liberty of feeding your classes into the CGbR generator. Because it is in an early stage it doesn't support DateTime yet, so I simply replaced it with long. The generated serialization code looks like this:

public int Size
{
    get 
    { 
        var size = 24;
        // Add size for collections and strings
        size += Cts == null ? 0 : Cts.Count * 4;
        size += Tes == null ? 0 : Tes.Count * 4;
        size += Code == null ? 0 : Code.Length;
        size += Message == null ? 0 : Message.Length;

        return size;              
    }
}

public byte[] ToBytes(byte[] bytes, ref int index)
{
    if (index + Size > bytes.Length)
        throw new ArgumentOutOfRangeException("index", "Object does not fit in array");

    // Convert Cts
    // Two bytes length information for each dimension
    GeneratorByteConverter.Include((ushort)(Cts == null ? 0 : Cts.Count), bytes, ref index);
    if (Cts != null)
    {
        for(var i = 0; i < Cts.Count; i++)
        {
            var value = Cts[i];
            value.ToBytes(bytes, ref index);
        }
    }
    // Convert Tes
    // Two bytes length information for each dimension
    GeneratorByteConverter.Include((ushort)(Tes == null ? 0 : Tes.Count), bytes, ref index);
    if (Tes != null)
    {
        for(var i = 0; i < Tes.Count; i++)
        {
            var value = Tes[i];
            value.ToBytes(bytes, ref index);
        }
    }
    // Convert Code
    GeneratorByteConverter.Include(Code, bytes, ref index);
    // Convert Message
    GeneratorByteConverter.Include(Message, bytes, ref index);
    // Convert StartDate
    GeneratorByteConverter.Include(StartDate.ToBinary(), bytes, ref index);
    // Convert EndDate
    GeneratorByteConverter.Include(EndDate.ToBinary(), bytes, ref index);
    return bytes;
}

public Td FromBytes(byte[] bytes, ref int index)
{
    // Read Cts
    var ctsLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
    var tempCts = new List<Ct>(ctsLength);
    for (var i = 0; i < ctsLength; i++)
    {
        var value = new Ct().FromBytes(bytes, ref index);
        tempCts.Add(value);
    }
    Cts = tempCts;
    // Read Tes
    var tesLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
    var tempTes = new List<Te>(tesLength);
    for (var i = 0; i < tesLength; i++)
    {
        var value = new Te().FromBytes(bytes, ref index);
        tempTes.Add(value);
    }
    Tes = tempTes;
    // Read Code
    Code = GeneratorByteConverter.GetString(bytes, ref index);
    // Read Message
    Message = GeneratorByteConverter.GetString(bytes, ref index);
    // Read StartDate
    StartDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));
    // Read EndDate
    EndDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));

    return this;
}

I created a list of sample objects like this:

var objects = new List<Td>();
for (int i = 0; i < 1000; i++)
{
    var obj = new Td
    {
        Message = "Hello my friend",
        Code = "Some code that can be put here",
        StartDate = DateTime.Now.AddDays(-7),
        EndDate = DateTime.Now.AddDays(2),
        Cts = new List<Ct>(),
        Tes = new List<Te>()
    };
    for (int j = 0; j < 10; j++)
    {
        obj.Cts.Add(new Ct { Foo = i * j });
        obj.Tes.Add(new Te { Bar = i + j });
    }
    objects.Add(obj);
}

Results on my machine in Release build:

var watch = new Stopwatch();
watch.Start();
var bytes = BinarySerializer.SerializeMany(objects);
watch.Stop();

Size: 149000 bytes

Time: 2.059ms 3.13ms

Edit: Starting with CGbR 0.4.3 the binary serializer supports DateTime. Unfortunately the DateTime.ToBinary method is insanely slow. I will replace it with somehting faster soon.

Edit2: When using UTC DateTime by invoking ToUniversalTime() the performance is restored and clocks in at 1.669ms.

Convert XmlDocument to String

" is shown as \" in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.

Using StringWriter for XML Serialization

One problem with StringWriter is that by default it doesn't let you set the encoding which it advertises - so you can end up with an XML document advertising its encoding as UTF-16, which means you need to encode it as UTF-16 if you write it to a file. I have a small class to help with that though:

public sealed class StringWriterWithEncoding : StringWriter
{
    public override Encoding Encoding { get; }

    public StringWriterWithEncoding (Encoding encoding)
    {
        Encoding = encoding;
    }    
}

Or if you only need UTF-8 (which is all I often need):

public sealed class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

As for why you couldn't save your XML to the database - you'll have to give us more details about what happened when you tried, if you want us to be able to diagnose/fix it.

Write HTML to string

You could use some third party open-source libraries to generated strong typed verified (X)HTML, such as CityLizard Framework or Sharp DOM.

Update For example

html
    [head
        [title["Title of the page"]]
        [meta_(
            content: "text/html;charset=UTF-8",
            http_equiv: "Content-Type")
        ]
        [link_(href: "css/style.css", rel: "stylesheet", type: "text/css")]
        [script_(type: "text/javascript", src: "/JavaScript/jquery-1.4.2.min.js")]
    ]
    [body
        [div
            [h1["Test Form to Test"]]
            [form_(action: "post", id: "Form1")
                [div
                    [label["Parameter"]]
                    [input_(type: "text", value: "Enter value")]
                    [input_(type: "submit", value: "Submit!")]
                ]
            ]
            [div
                [p["Textual description of the footer"]]
                [a_(href: "http://google.com/")
                    [span["You can find us here"]]
                ]
                [div["Another nested container"]]
            ]
        ]
    ];

Convert DataTable to CSV stream

You can try using something like this. In this case I used one stored procedure to get more data tables and export all of them using CSV.

using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace bo
{
class Program
{
    static private void CreateCSVFile(DataTable dt, string strFilePath)
    {
        #region Export Grid to CSV
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(strFilePath, false);
        int iColCount = dt.Columns.Count;

        // First we will write the headers.

        //DataTable dt = m_dsProducts.Tables[0];
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(";");
            }
        }
        sw.Write(sw.NewLine);

        // Now write all the rows.
        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount -1 )
                {
                    sw.Write(";");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();

        #endregion
    }
    static void Main(string[] args)
    {
        string strConn = "connection string to sql";
        string direktorij = @"d:";
        SqlConnection conn = new SqlConnection(strConn); 
        SqlCommand command = new SqlCommand("sp_ado_pos_data", conn);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add('@skl_id', SqlDbType.Int).Value = 158;
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        adapter.Fill(ds);
        for (int i = 0; i < ds.Tables.Count; i++)
        {
            string datoteka  = (string.Format(@"{0}tablea{1}.csv", direktorij, i));
            DataTable tabela = ds.Tables[i];
            CreateCSVFile(tabela,datoteka );
            Console.WriteLine("Generišem tabelu {0}", datoteka);
        }
        Console.ReadKey();
    }
  }
}

Why catch and rethrow an exception in C#?

Don't do this,

try 
{
...
}
catch(Exception ex)
{
   throw ex;
}

You'll lose the stack trace information...

Either do,

try { ... }
catch { throw; }

OR

try { ... }
catch (Exception ex)
{
    throw new Exception("My Custom Error Message", ex);
}

One of the reason you might want to rethrow is if you're handling different exceptions, for e.g.

try
{
   ...
}
catch(SQLException sex)
{
   //Do Custom Logging 
   //Don't throw exception - swallow it here
}
catch(OtherException oex)
{
   //Do something else
   throw new WrappedException("Other Exception occured");
}
catch
{
   System.Diagnostics.Debug.WriteLine("Eeep! an error, not to worry, will be handled higher up the call stack");
   throw; //Chuck everything else back up the stack
}

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

Image Greyscale with CSS & re-color on mouse-over?

There are numerous methods of accomplishing this, which I'll detail with a few examples below.

Pure CSS (using only one colored image)

img.grayscale {
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
  filter: gray; /* IE6-9 */
  -webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
}

img.grayscale:hover {
  filter: none;
  -webkit-filter: grayscale(0%);
}

_x000D_
_x000D_
img.grayscale {_x000D_
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");_x000D_
  /* Firefox 3.5+, IE10 */_x000D_
  filter: gray;_x000D_
  /* IE6-9 */_x000D_
  -webkit-filter: grayscale(100%);_x000D_
  /* Chrome 19+ & Safari 6+ */_x000D_
  -webkit-transition: all .6s ease;_x000D_
  /* Fade to color for Chrome and Safari */_x000D_
  -webkit-backface-visibility: hidden;_x000D_
  /* Fix for transition flickering */_x000D_
}_x000D_
_x000D_
img.grayscale:hover {_x000D_
  filter: none;_x000D_
  -webkit-filter: grayscale(0%);_x000D_
}_x000D_
_x000D_
svg {_x000D_
  background: url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);_x000D_
}_x000D_
_x000D_
svg image {_x000D_
  transition: all .6s ease;_x000D_
}_x000D_
_x000D_
svg image:hover {_x000D_
  opacity: 0;_x000D_
}
_x000D_
<p>Firefox, Chrome, Safari, IE6-9</p>_x000D_
<img class="grayscale" src="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" width="400">_x000D_
<p>IE10 with inline SVG</p>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 400 377" width="400" height="377">_x000D_
  <defs>_x000D_
     <filter id="filtersPicture">_x000D_
       <feComposite result="inputTo_38" in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />_x000D_
       <feColorMatrix id="filter_38" type="saturate" values="0" data-filterid="38" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image filter="url(&quot;#filtersPicture&quot;)" x="0" y="0" width="400" height="377" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" />_x000D_
   </svg>
_x000D_
_x000D_
_x000D_

You can find an article related to this technique here.

Pure CSS (using a grayscale and colored images)

This approach requires two copies of an image: one in grayscale and the other in full color. Using the CSS :hover psuedoselector, you can update the background of your element to toggle between the two:

#yourimage { 
    background: url(../grayscale-image.png);
}
#yourImage:hover { 
    background: url(../color-image.png};
}

_x000D_
_x000D_
#google {_x000D_
  background: url('http://www.google.com/logos/keystroke10-hp.png');_x000D_
  height: 95px;_x000D_
  width: 275px;_x000D_
  display: block;_x000D_
  /* Optional for a gradual animation effect */_x000D_
  transition: 0.5s;_x000D_
}_x000D_
_x000D_
#google:hover {_x000D_
  background: url('https://graphics217b.files.wordpress.com/2011/02/logo1w.png');_x000D_
}
_x000D_
<a id='google' href='http://www.google.com'></a>
_x000D_
_x000D_
_x000D_

This could also be accomplished by using a Javascript-based hover effect such as jQuery's hover() function in the same manner.

Consider a Third-Party Library

The desaturate library is a common library that allows you to easily switch between a grayscale version and full-colored version of a given element or image.

How can I get a Unicode character's code?

Just convert it to int:

char registered = '®';
int code = (int) registered;

In fact there's an implicit conversion from char to int so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.

This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt().

Once you've got the UTF-16 code unit or Unicode code points, but of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+, e.g. "U+0020" for space.) That's beyond the scope of this question though, as we don't know what the requirements are.

Logo image and H1 heading on the same line

Just stick the img tag inside the h1 tag as part of the content.

Speed up rsync with Simultaneous/Concurrent File Transfers?

rsync transfers files as fast as it can over the network. For example, try using it to copy one large file that doesn't exist at all on the destination. That speed is the maximum speed rsync can transfer data. Compare it with the speed of scp (for example). rsync is even slower at raw transfer when the destination file exists, because both sides have to have a two-way chat about what parts of the file are changed, but pays for itself by identifying data that doesn't need to be transferred.

A simpler way to run rsync in parallel would be to use parallel. The command below would run up to 5 rsyncs in parallel, each one copying one directory. Be aware that the bottleneck might not be your network, but the speed of your CPUs and disks, and running things in parallel just makes them all slower, not faster.

run_rsync() {
    # e.g. copies /main/files/blah to /main/filesTest/blah
    rsync -av "$1" "/main/filesTest/${1#/main/files/}"
}
export -f run_rsync
parallel -j5 run_rsync ::: /main/files/*

how to assign a block of html code to a javascript variable

we can use backticks (``) without any error.. eg: <div>"test"<div>

we can store large template(HTML) inside the backticks which was introduced in ES6 javascript standard

No need to escape any special characters

if no backticks.. we need to escape characters by appending backslash() eg:" \"test\""

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

Just to complete the answer - on Ubuntu/Mint you can just run:

zcat /usr/share/doc/phpmyadmin/examples/create_tables.sql.gz | mysql

(of course this assumes development environment where your default mysql user is root and you use no password; in other case use | mysql -uuser_name -p)

How to concat a string to xsl:value-of select="...?

Not the most readable solution, but you can mix the result from a value-of with plain text:

<a>
  <xsl:attribute name="href"> 
    Text<xsl:value-of select="/*/properties/property[@name='report']/@value"/>Text
  </xsl:attribute>
</a>

How to expire a cookie in 30 minutes using jQuery?

If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.

As one day is 1, one minute would be 1 / 1440 (there's 1440 minutes in a day).

So 30 minutes is 30 / 1440 = 0.02083333.

Final code:

$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });

I've added path: '/' so that you don't forget that the cookie is set on the current path. If you're on /my-directory/ the cookie is only set for this very directory.

Counting Number of Letters in a string variable

If you don't need the leading and trailing spaces :

str.Trim().Length

How to suppress Update Links warning?

Open the VBA Editor of Excel and type this in the Immediate Window (See Screenshot)

Application.AskToUpdateLinks = False 

Close Excel and then open your File. It will not prompt you again. Remember to reset it when you close the workbook else it will not work for other workbooks as well.

ScreenShot:

enter image description here

EDIT

So applying it to your code, your code will look like this

Function getWorkbook(bkPath As String) As Workbook
    Application.AskToUpdateLinks = False
    Set getWorkbook = Workbooks.Open(bkPath, False)
    Application.AskToUpdateLinks = True
End Function

FOLLOWUP

Sigil, The code below works on files with broken links as well. Here is my test code.

Test Conditions

  1. Create 2 new files. Name them Sample1.xlsx and Sample2.xlsx and save them on C:\
  2. In cell A1 of Sample1.xlsx, type this formula ='C:\[Sample2.xlsx]Sheet1'!$A$1
  3. Save and close both the files
  4. Delete Sample2.xlsx!!!
  5. Open a New workbook and it's module paste this code and run Sample. You will notice that you will not get a prompt.

Code

Option Explicit

Sub Sample()
    getWorkbook "c:\Sample1.xlsx"
End Sub

Function getWorkbook(bkPath As String) As Workbook
    Application.AskToUpdateLinks = False
    Set getWorkbook = Workbooks.Open(bkPath, False)
    Application.AskToUpdateLinks = True
End Function

What is the difference between SQL, PL-SQL and T-SQL?

Structured Query Language - SQL: is an ANSI-standard used by almost all SGBD's vendors around the world. Basically, SQL is a language used to define and manipulate data [DDL and DML].

PL/SQL is a language created by Oracle universe. PL/SQL combine programming procedural instructions and allows the creation of programs that operates directly on database scenario.

T-SQL is Microsoft product align SQL patterns, with some peculiarities. So, feel free to test your limits.

How do you change text to bold in Android?

In my case, Passing value through string.xml worked out with html Tag..

<string name="your_string_tag"> <b> your_text </b></string>

How do I create directory if it doesn't exist to create a file?

An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:

public static class FileInfoExtension
{
    //second parameter is need to avoid collision with native MoveTo
    public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.MoveTo(destination);
    }
}

Then use brand new MoveTo extension:

 using <namespace of FileInfoExtension>;
 ...
 new FileInfo("some path")
     .MoveTo("target path",true);

Check Methods extension documentation.

How to read integer value from the standard input in Java

You can use java.util.Scanner (API):

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).

Convert to date format dd/mm/yyyy

There is also the DateTime object if you want to go that way: http://www.php.net/manual/en/datetime.construct.php

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

This thread has some great tips. However....

@GirishB's answer isn't correct - sorry. Jartender's is best.

Also, every post in here seems to assume you're logging in to the Linux guest as root, except for @tomoguisuru. Yuck! Don't use root, use a separate user account and "sudo" when you need root privileges. Then this user (or any other user who needs the shared folder) should have membership in the vboxsf group, and @tomoguisuru's command is perfect, even terser than what I use.

Forget running mount yourself. Set up the shared folder to auto mount and you'll find the shared folder - it's under /media in my OEL (RH and Centos probably the same). If it's not there, just run "mount" with no arguments and look for the mounted directory of type vboxsf.

Terminal showing 'mount' and where to find mounted shared folder

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

If you need a single quote inside of a string, since \' is undefined by the spec, use \u0027 see http://www.utf8-chartable.de/ for all of them

edit: please excuse my misuse of the word backticks in the comments. I meant backslash. My point here is that in the event you have nested strings inside other strings, I think it can be more useful and readable to use unicode instead of lots of backslashes to escape a single quote. If you are not nested however it truly is easier to just put a plain old quote in there.

Recommended website resolution (width and height)?

All of the answers so far talk about desktop monitors, but I'm using stack overflow on my iPhone and I don't think you should exclude any mobile platform by targeting 1024 or 1280 horizontal pixels. Mark up your page so the browser knows what it all means and making it usable will come for free, even on screen readers and other kit you haven't thought of.

Why is String immutable in Java?

The most important reason of a String being made immutable in Java is Security consideration. Next would be Caching.

I believe other reasons given here, such as efficiency, concurrency, design and string pool follows from the fact that String in made immutable. For eg. String Pool could be created because String was immutable and not the other way around.

Check Gosling interview transcript here

From a strategic point of view, they tend to more often be trouble free. And there are usually things you can do with immutables that you can't do with mutable things, such as cache the result. If you pass a string to a file open method, or if you pass a string to a constructor for a label in a user interface, in some APIs (like in lots of the Windows APIs) you pass in an array of characters. The receiver of that object really has to copy it, because they don't know anything about the storage lifetime of it. And they don't know what's happening to the object, whether it is being changed under their feet.

You end up getting almost forced to replicate the object because you don't know whether or not you get to own it. And one of the nice things about immutable objects is that the answer is, "Yeah, of course you do." Because the question of ownership, who has the right to change it, doesn't exist.

One of the things that forced Strings to be immutable was security. You have a file open method. You pass a String to it. And then it's doing all kind of authentication checks before it gets around to doing the OS call. If you manage to do something that effectively mutated the String, after the security check and before the OS call, then boom, you're in. But Strings are immutable, so that kind of attack doesn't work. That precise example is what really demanded that Strings be immutable

Curl Command to Repeat URL Request

If you want to add an interval before executing the cron the next time you can add a sleep

for i in {1..100}; do echo $i && curl "http://URL" >> /tmp/output.log && sleep 120; done

What's the difference between utf8_general_ci and utf8_unicode_ci?

See the mysql manual, Unicode Character Sets section:

For any Unicode character set, operations performed using the _general_ci collation are faster than those for the _unicode_ci collation. For example, comparisons for the utf8_general_ci collation are faster, but slightly less correct, than comparisons for utf8_unicode_ci. The reason for this is that utf8_unicode_ci supports mappings such as expansions; that is, when one character compares as equal to combinations of other characters. For example, in German and some other languages “ß” is equal to “ss”. utf8_unicode_ci also supports contractions and ignorable characters. utf8_general_ci is a legacy collation that does not support expansions, contractions, or ignorable characters. It can make only one-to-one comparisons between characters.

So to summarize, utf_general_ci uses a smaller and less correct (according to the standard) set of comparisons than utf_unicode_ci which should implement the entire standard. The general_ci set will be faster because there is less computation to do.

Python: create dictionary using dict() with integer keys?

There are also these 'ways':

>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}

Selenium Webdriver: Entering text into text field

Agree with Subir Kumar Sao and Faiz.

element_enter.findElement(By.xpath("//html/body/div[1]/div[3]/div[1]/form/div/div/input")).sendKeys(barcode);

OSError: [Errno 8] Exec format error

It wouldn't be wrong to mention that Pexpect does throw a similar error

#python -c "import pexpect; p=pexpect.spawn('/usr/local/ssl/bin/openssl_1.1.0f  version'); p.interact()"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/pexpect.py", line 430, in __init__
    self._spawn (command, args)
  File "/usr/lib/python2.7/site-packages/pexpect.py", line 560, in _spawn
    os.execv(self.command, self.args)
OSError: [Errno 8] Exec format error

Over here, the openssl_1.1.0f file at the specified path has exec command specified in it and is running the actual openssl binary when called.

Usually, I wouldn't mention this unless I have the root cause, but this problem was not there earlier. Unable to find the similar problem, the closest explanation to make it work is the same as the one provided by @jfs above.

what worked for me is both

  • adding /bin/bash at the beginning of the command or file you are
    facing the problem with, or
  • adding shebang #!/bin/sh as the first line.

for ex.

#python -c "import pexpect; p=pexpect.spawn('/bin/bash /usr/local/ssl/bin/openssl_1.1.0f  version'); p.interact()"
OpenSSL 1.1.0f  25 May 2017

How do I read a resource file from a Java jar file?

Outside of your technique, why not use the standard Java JarFile class to get the references you want? From there most of your problems should go away.

Accessing JPEG EXIF rotation data in JavaScript on the client side

https://github.com/blueimp/JavaScript-Load-Image is a modern javascript library that can not only extract the exif orientation flag - it can also correctly mirror/rotate JPEG images on the client side.

I just solved the same problem with this library: JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

CSS display:table-row does not expand when width is set to 100%

You can nest table-cell directly within table. You muslt have a table. Starting eith table-row does not work. Try it with this HTML:

<html>
  <head>
    <style type="text/css">
.table {
  display: table;
  width: 100%;
}
.tr {
  display: table-row;
  width: 100%;
}
.td {
  display: table-cell;
}
    </style>
  </head>
  <body>

    <div class="table">
      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>
    </div>

      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>

    <div class="table">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
    </div>

  </body>
</html>

Tab Escape Character?

For someone who needs quick reference of C# Escape Sequences that can be used in string literals:

\t     Horizontal tab (ASCII code value: 9)

\n     Line feed (ASCII code value: 10)

\r     Carriage return (ASCII code value: 13)

\'     Single quotation mark

\"     Double quotation mark

\\     Backslash

\?     Literal question mark

\x12     ASCII character in hexadecimal notation (e.g. for 0x12)

\x1234     Unicode character in hexadecimal notation (e.g. for 0x1234)

It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline which gets adjusted to current OS settings. With .Net Core it gets really important.

How do I write a RGB color value in JavaScript?

Here's a simple function that creates a CSS color string from RGB values ranging from 0 to 255:

function rgb(r, g, b){
  return "rgb("+r+","+g+","+b+")";
}

Alternatively (to create fewer string objects), you could use array join():

function rgb(r, g, b){
  return ["rgb(",r,",",g,",",b,")"].join("");
}

The above functions will only work properly if (r, g, and b) are integers between 0 and 255. If they are not integers, the color system will treat them as in the range from 0 to 1. To account for non-integer numbers, use the following:

function rgb(r, g, b){
  r = Math.floor(r);
  g = Math.floor(g);
  b = Math.floor(b);
  return ["rgb(",r,",",g,",",b,")"].join("");
}

You could also use ES6 language features:

const rgb = (r, g, b) => 
  `rgb(${Math.floor(r)},${Math.floor(g)},${Math.floor(b)})`;

How to beautifully update a JPA entity in Spring Data?

Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)

Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);

Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.

How to post data to specific URL using WebClient in C#

I just found the solution and yea it was easier than I thought :)

so here is the solution:

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(URI, myParameters);
}

it works like charm :)

Emulator in Android Studio doesn't start

Check if the following tools are installed or not in the Android SDK Manager as shown in this picture: enter image description here

req.query and req.param in ExpressJS

req.query is the query string sent to the server, example /page?test=1, req.param is the parameters passed to the handler.

app.get('/user/:id', handler);, going to /user/blah, req.param.id would return blah;

How to access a preexisting collection with Mongoose?

Are you sure you've connected to the db? (I ask because I don't see a port specified)

try:

mongoose.connection.on("open", function(){
  console.log("mongodb is connected!!");
});

Also, you can do a "show collections" in mongo shell to see the collections within your db - maybe try adding a record via mongoose and see where it ends up?

From the look of your connection string, you should see the record in the "test" db.

Hope it helps!

How to log Apache CXF Soap Request and Soap Response using Log4j?

In case somebody wants to do this, using Play Framework (and using LogBack http://logback.qos.ch/), then you can configure the application-logger.xml with this line:

 <logger name="org.apache.cxf" level="DEBUG"/>

For me, it did the trick ;)

How to store phone numbers on MySQL databases?

  • All as varchar (they aren't numbers but "collections of digits")
  • Country + area + number separately
  • Not all countries have area code (eg Malta where I am)
  • Some countries drop the leading zero from the area code when dialling internal (eg UK)
  • Format in the client code

How to recursively find the latest modified file in a directory?

Ignoring hidden files — with nice & fast time stamp

$ find . -type f -not -path '*/\.*' -printf '%TY.%Tm.%Td %THh%TM %Ta %p\n' |sort -nr |head -n 10

Result

Handles spaces in filenames well — not that these should be used!

2017.01.25 18h23 Wed ./indenting/Shifting blocks visually.mht
2016.12.11 12h33 Sun ./tabs/Converting tabs to spaces.mht
2016.12.02 01h46 Fri ./advocacy/2016.Vim or Emacs - Which text editor do you prefer?.mht
2016.11.09 17h05 Wed ./Word count - Vim Tips Wiki.mht

More

More find galore following the link.

How to create a date object from string in javascript

You definitely want to use the second expression since months in JS are enumerated from 0.

Also you may use Date.parse method, but it uses different date format:

var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);

Git resolve conflict using --ours/--theirs for all files

Just grep through the working directory and send the output through the xargs command:

grep -lr '<<<<<<<' . | xargs git checkout --ours

or

grep -lr '<<<<<<<' . | xargs git checkout --theirs

How this works: grep will search through every file in the current directory (the .) and subdirectories recursively (the -r flag) looking for conflict markers (the string '<<<<<<<')

the -l or --files-with-matches flag causes grep to output only the filename where the string was found. Scanning stops after first match, so each matched file is only output once.

The matched file names are then piped to xargs, a utility that breaks up the piped input stream into individual arguments for git checkout --ours or --theirs

More at this link.

Since it would be very inconvenient to have to type this every time at the command line, if you do find yourself using it a lot, it might not be a bad idea to create an alias for your shell of choice: Bash is the usual one.

This method should work through at least Git versions 2.4.x

Java 8 Streams: multiple filters vs. complex condition

A complex filter condition is better in performance perspective, but the best performance will show old fashion for loop with a standard if clause is the best option. The difference on a small array 10 elements difference might ~ 2 times, for a large array the difference is not that big.
You can take a look on my GitHub project, where I did performance tests for multiple array iteration options

For small array 10 element throughput ops/s: 10 element array For medium 10,000 elements throughput ops/s: enter image description here For large array 1,000,000 elements throughput ops/s: 1M elements

NOTE: tests runs on

  • 8 CPU
  • 1 GB RAM
  • OS version: 16.04.1 LTS (Xenial Xerus)
  • java version: 1.8.0_121
  • jvm: -XX:+UseG1GC -server -Xmx1024m -Xms1024m

UPDATE: Java 11 has some progress on the performance, but the dynamics stay the same

Benchmark mode: Throughput, ops/time Java 8vs11

Freely convert between List<T> and IEnumerable<T>

A List<T> is an IEnumerable<T>, so actually, there's no need to 'convert' a List<T> to an IEnumerable<T>. Since a List<T> is an IEnumerable<T>, you can simply assign a List<T> to a variable of type IEnumerable<T>.

The other way around, not every IEnumerable<T> is a List<T> offcourse, so then you'll have to call the ToList() member method of the IEnumerable<T>.

How to convert a time string to seconds?

import time
from datetime import datetime

t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())

result: 3.0

Java JSON serialization - best practice

Have your tried json-io (https://github.com/jdereg/json-io)?

This library allows you to serialize / deserialize any Java object graph, including object graphs with cycles in them (e.g., A->B, B->A). It does not require your classes to implement any particular interface or inherit from any particular Java class.

In addition to serialization of Java to JSON (and JSON to Java), you can use it to format (pretty print) JSON:

String niceFormattedJson = JsonWriter.formatJson(jsonString)

Create an array of strings

Another option:

names = repmat({'Sample Text'}, 10, 1)

How do I clear the content of a div using JavaScript?

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

$("#cart_item").html("");

enabling cross-origin resource sharing on IIS7

The solution for me was to add :

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule"/>
    </modules>
</system.webServer>

To my web.config

Bootstrap dropdown not working

For me, it was a CORS issue. I removed crossorigin="anonymous" from my script importing tags, and it started working again.

BTW the latest script tags, in the correct order, can always be found here: https://getbootstrap.com/

Edit: Apparently adding defer to the script tag will also break all the Bootstrap goodies.

React: why child component doesn't update when prop changes

According to React philosophy component can't change its props. they should be received from the parent and should be immutable. Only parent can change the props of its children.

nice explanation on state vs props

also, read this thread Why can't I update props in react.js?

What is the difference between require() and library()?

Always use library. Never use require.

In a nutshell, this is because, when using require, your code might yield different, erroneous results, without signalling an error. This is rare but not hypothetical! Consider this code, which yields different results depending on whether {dplyr} can be loaded:

require(dplyr)

x = data.frame(y = seq(100))
y = 1
filter(x, y == 1)

This can lead to subtly wrong results. Using library instead of require throws an error here, signalling clearly that something is wrong. This is good.

It also makes debugging all other failures more difficult: If you require a package at the start of your script and use its exports in line 500, you’ll get an error message “object ‘foo’ not found” in line 500, rather than an error “there is no package called ‘bla’”.

The only acceptable use case of require is when its return value is immediately checked, as some of the other answers show. This is a fairly common pattern but even in these cases it is better (and recommended, see below) to instead separate the existence check and the loading of the package. That is: use requireNamespace instead of require in these cases.

More technically, require actually calls library internally (if the package wasn’t already attached — require thus performs a redundant check, because library also checks whether the package was already loaded). Here’s a simplified implementation of require to illustrate what it does:

require = function (package) {
    already_attached = paste('package:', package) %in% search()
    if (already_attached) return(TRUE)
    maybe_error = try(library(package, character.only = TRUE)) 
    success = ! inherits(maybe_error, 'try-error')
    if (! success) cat("Failed")
    success
}

Experienced R developers agree:

Yihui Xie, author of {knitr}, {bookdown} and many other packages says:

Ladies and gentlemen, I've said this before: require() is the wrong way to load an R package; use library() instead

Hadley Wickham, author of more popular R packages than anybody else, says

Use library(x) in data analysis scripts. […] You never need to use require() (requireNamespace() is almost always better)

Printing the correct number of decimal points with cout

with templates

#include <iostream>

// d = decimal places
template<int d> 
std::ostream& fixed(std::ostream& os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

int main(){
    double d = 122.345;
    std::cout << fixed<2> << d;
}

similar for scientific as well, with a width option also (useful for columns)

// d = decimal places
template<int d> 
std::ostream& f(std::ostream &os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

// w = width, d = decimal places
template<int w, int d> 
std::ostream& f(std::ostream &os){
    os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
    os.precision(d); 
    os.width(w);
    return os; 
}

// d = decimal places
template<int d> 
std::ostream& e(std::ostream &os){
    os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
    os.precision(d); 
    return os; 
}

// w = width, d = decimal places
template<int w, int d> 
std::ostream& e(std::ostream &os){
    os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
    os.precision(d); 
    os.width(w);
    return os; 
}

int main(){
    double d = 122.345;
    std::cout << f<10,2> << d << '\n'
        << e<10,2> << d << '\n';
}

Log to the base 2 in python

Using numpy:

In [1]: import numpy as np

In [2]: np.log2?
Type:           function
Base Class:     <type 'function'>
String Form:    <function log2 at 0x03049030>
Namespace:      Interactive
File:           c:\python26\lib\site-packages\numpy\lib\ufunclike.py
Definition:     np.log2(x, y=None)
Docstring:
    Return the base 2 logarithm of the input array, element-wise.

Parameters
----------
x : array_like
  Input array.
y : array_like
  Optional output array with the same shape as `x`.

Returns
-------
y : ndarray
  The logarithm to the base 2 of `x` element-wise.
  NaNs are returned where `x` is negative.

See Also
--------
log, log1p, log10

Examples
--------
>>> np.log2([-1, 2, 4])
array([ NaN,   1.,   2.])

In [3]: np.log2(8)
Out[3]: 3.0

Import pfx file into particular certificate store from command line

To anyone else looking for this, I wasn't able to use certutil -importpfx into a specific store, and I didn't want to download the importpfx tool supplied by jaspernygaard's answer in order to avoid the requirement of copying the file to a large number of servers. I ended up finding my answer in a powershell script shown here.

The code uses System.Security.Cryptography.X509Certificates to import the certificate and then moves it into the desired store:

function Import-PfxCertificate { 

    param([String]$certPath,[String]$certRootStore = “localmachine”,[String]$certStore = “My”,$pfxPass = $null) 
    $pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 

    if ($pfxPass -eq $null) 
    {
        $pfxPass = read-host "Password" -assecurestring
    } 

    $pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet") 

    $store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore) 
    $store.open("MaxAllowed") 
    $store.add($pfx) 
    $store.close() 
}

Generate preview image from Video file?

Solution #1 (Older) (not recommended)

Firstly install ffmpeg-php project (http://ffmpeg-php.sourceforge.net/)

And then you can use of this simple code:

<?php
$frame = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$mov = new ffmpeg_movie($movie);
$frame = $mov->getFrame($frame);
if ($frame) {
    $gd_image = $frame->toGDImage();
    if ($gd_image) {
        imagepng($gd_image, $thumbnail);
        imagedestroy($gd_image);
        echo '<img src="'.$thumbnail.'">';
    }
}
?>

Description: This project use binary extension .so file, It's very old and last update was for 2008. So, maybe don't works with newer version of FFMpeg or PHP.


Solution #2 (Update 2018) (recommended)

Firstly install PHP-FFMpeg project (https://github.com/PHP-FFMpeg/PHP-FFMpeg)
(just run for install: composer require php-ffmpeg/php-ffmpeg)

And then you can use of this simple code:

<?php
require 'vendor/autoload.php';

$sec = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($movie);
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($sec));
$frame->save($thumbnail);
echo '<img src="'.$thumbnail.'">';

Description: It's newer and more modern project and works with latest version of FFMpeg and PHP. Note that it's required to proc_open() PHP function.

twitter bootstrap navbar fixed top overlapping site

All you have to do is

@media (min-width: 980px) { body { padding-top: 40px; } } 

How to add an onchange event to a select box via javascript?

yourSelect.setAttribute( "onchange", "yourFunction()" );

What is function overloading and overriding in php?

Function overloading occurs when you define the same function name twice (or more) using different set of parameters. For example:

class Addition {
  function compute($first, $second) {
    return $first+$second;
  }

  function compute($first, $second, $third) {
    return $first+$second+$third;
  }
}

In the example above, the function compute is overloaded with two different parameter signatures. *This is not yet supported in PHP. An alternative is to use optional arguments:

class Addition {
  function compute($first, $second, $third = 0) {
    return $first+$second+$third;
  }
}

Function overriding occurs when you extend a class and rewrite a function which existed in the parent class:

class Substraction extends Addition {
  function compute($first, $second, $third = 0) {
    return $first-$second-$third;
  }
}

For example, compute overrides the behavior set forth in Addition.

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

As stated in the other responses, the response body needs special treatment so it can be read repeatedly (by default, its contents get consumed on the first read).

Instead of using the BufferingClientHttpRequestFactory when setting up the request, the interceptor itself can wrap the response and make sure the content is retained and can be repeatedly read (by the logger as well as by the consumer of the response):

My interceptor, which

  • buffers the response body using a wrapper
  • logs in a more compact way
  • logs the status code identifier as well (e.g. 201 Created)
  • includes a request sequence number allowing to easily distinguish concurrent log entries from multiple threads

Code:

public class LoggingInterceptor implements ClientHttpRequestInterceptor {

    private final Logger log = LoggerFactory.getLogger(getClass());
    private AtomicInteger requestNumberSequence = new AtomicInteger(0);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        int requestNumber = requestNumberSequence.incrementAndGet();
        logRequest(requestNumber, request, body);
        ClientHttpResponse response = execution.execute(request, body);
        response = new BufferedClientHttpResponse(response);
        logResponse(requestNumber, response);
        return response;
    }

    private void logRequest(int requestNumber, HttpRequest request, byte[] body) {
        if (log.isDebugEnabled()) {
            String prefix = requestNumber + " > ";
            log.debug("{} Request: {} {}", prefix, request.getMethod(), request.getURI());
            log.debug("{} Headers: {}", prefix, request.getHeaders());
            if (body.length > 0) {
                log.debug("{} Body: \n{}", prefix, new String(body, StandardCharsets.UTF_8));
            }
        }
    }

    private void logResponse(int requestNumber, ClientHttpResponse response) throws IOException {
        if (log.isDebugEnabled()) {
            String prefix = requestNumber + " < ";
            log.debug("{} Response: {} {} {}", prefix, response.getStatusCode(), response.getStatusCode().name(), response.getStatusText());
            log.debug("{} Headers: {}", prefix, response.getHeaders());
            String body = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);
            if (body.length() > 0) {
                log.debug("{} Body: \n{}", prefix, body);
            }
        }
    }

    /**
     * Wrapper around ClientHttpResponse, buffers the body so it can be read repeatedly (for logging & consuming the result).
     */
    private static class BufferedClientHttpResponse implements ClientHttpResponse {

        private final ClientHttpResponse response;
        private byte[] body;

        public BufferedClientHttpResponse(ClientHttpResponse response) {
            this.response = response;
        }

        @Override
        public HttpStatus getStatusCode() throws IOException {
            return response.getStatusCode();
        }

        @Override
        public int getRawStatusCode() throws IOException {
            return response.getRawStatusCode();
        }

        @Override
        public String getStatusText() throws IOException {
            return response.getStatusText();
        }

        @Override
        public void close() {
            response.close();
        }

        @Override
        public InputStream getBody() throws IOException {
            if (body == null) {
                body = StreamUtils.copyToByteArray(response.getBody());
            }
            return new ByteArrayInputStream(body);
        }

        @Override
        public HttpHeaders getHeaders() {
            return response.getHeaders();
        }
    }
}

Configuration:

 @Bean
    public RestTemplateBuilder restTemplateBuilder() {
        return new RestTemplateBuilder()
                .additionalInterceptors(Collections.singletonList(new LoggingInterceptor()));
    }

Example log output:

2018-10-08 10:58:53 [main] DEBUG x.y.z.LoggingInterceptor - 2 >  Request: POST http://localhost:53969/payment/v4/private/payment-lists/10022/templates
2018-10-08 10:58:53 [main] DEBUG x.y.z.LoggingInterceptor - 2 >  Headers: {Accept=[application/json, application/json], Content-Type=[application/json;charset=UTF-8], Content-Length=[986]}
2018-10-08 10:58:53 [main] DEBUG x.y.z.LoggingInterceptor - 2 >  Body: 
{"idKey":null, ...}
2018-10-08 10:58:53 [main] DEBUG x.y.z.LoggingInterceptor - 2 <  Response: 200 OK 
2018-10-08 10:58:53 [main] DEBUG x.y.z.LoggingInterceptor - 2 <  Headers: {Content-Type=[application/json;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Mon, 08 Oct 2018 08:58:53 GMT]}
2018-10-08 10:58:53 [main] DEBUG x.y.z.LoggingInterceptor - 2 <  Body: 
{ "idKey" : "10022", ...  }

batch script - run command on each file in directory

Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES

in your case

forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert @file @fname.xlsx"

the only weird thing with this command is that forfiles automatically adds double quotes around @file and @fname. but it should work anyway

Which sort algorithm works best on mostly sorted data?

ponder Try Heap. I believe it's the most consistent of the O(n lg n) sorts.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

What is w3wp.exe?

w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.

You can get more information on w3wp.exe here

http://www.processlibrary.com/en/directory/files/w3wp/25761/

initializing strings as null vs. empty string

I would prefere

if (!myStr.empty())
{
    //do something
}

Also you don't have to write std::string a = "";. You can just write std::string a; - it will be empty by default

What does if [ $? -eq 0 ] mean for shell scripts?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded.

The grep manpage states:

The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)

So in this case it's checking whether any ERROR lines were found.

How to show validation message below each textbox using jquery?

is only the matter of finding the dom where you want to insert the the text.

DEMO jsfiddle

$().text(); 

When do I need to use a semicolon vs a slash in Oracle SQL?

It's a matter of preference, but I prefer to see scripts that consistently use the slash - this way all "units" of work (creating a PL/SQL object, running a PL/SQL anonymous block, and executing a DML statement) can be picked out more easily by eye.

Also, if you eventually move to something like Ant for deployment it will simplify the definition of targets to have a consistent statement delimiter.

Erase whole array Python

It's simple:

array = []

will set array to be an empty list. (They're called lists in Python, by the way, not arrays)

If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Add this line at the bottom of the gradle.

apply plugin: 'com.google.gms.google-services'

because it the top it does not work.I was facing similar problem.

Convert Unicode to ASCII without errors in Python

I use this helper function throughout all of my projects. If it can't convert the unicode, it ignores it. This ties into a django library, but with a little research you could bypass it.

from django.utils import encoding

def convert_unicode_to_string(x):
    """
    >>> convert_unicode_to_string(u'ni\xf1era')
    'niera'
    """
    return encoding.smart_str(x, encoding='ascii', errors='ignore')

I no longer get any unicode errors after using this.

How to convert a Java String to an ASCII byte array?

Try this:

/**
 * @(#)demo1.java
 *
 *
 * @author 
 * @version 1.00 2012/8/30
 */

import java.util.*;

public class demo1 
{
    Scanner s=new Scanner(System.in);

    String str;
    int key;

    void getdata()
    {
        System.out.println ("plase enter a string");
        str=s.next();
        System.out.println ("plase enter a key");
        key=s.nextInt();
    }

    void display()
    {
        char a;
        int j;
        for ( int i = 0; i < str.length(); ++i )
        {

            char c = str.charAt( i );
            j = (int) c + key;
            a= (char) j;

            System.out.print(a);  
        }

        public static void main(String[] args)
        {
            demo1 obj=new demo1();
            obj.getdata();
            obj.display();
        }
    }
}

Authentication issues with WWW-Authenticate: Negotiate

Putting this information here for future readers' benefit.

  • 401 (Unauthorized) response header -> Request authentication header

  • Here are several WWW-Authenticate response headers. (The full list is at IANA: HTTP Authentication Schemes.)

    • WWW-Authenticate: Basic-> Authorization: Basic + token - Use for basic authentication
    • WWW-Authenticate: NTLM-> Authorization: NTLM + token (2 challenges)
    • WWW-Authenticate: Negotiate -> Authorization: Negotiate + token - used for Kerberos authentication
      • By the way: IANA has this angry remark about Negotiate: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).

You can set the Authorization: Basic header only when you also have the WWW-Authenticate: Basic header on your 401 challenge.

But since you have WWW-Authenticate: Negotiate this should be the case for Kerberos based authentication.

Java 8 Distinct by property

Set<YourPropertyType> set = new HashSet<>();
list
        .stream()
        .filter(it -> set.add(it.getYourProperty()))
        .forEach(it -> ...);

Parameter "stratify" from method "train_test_split" (scikit Learn)

In this context, stratification means that the train_test_split method returns training and test subsets that have the same proportions of class labels as the input dataset.

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

How to find Current open Cursors in Oracle

Here's how to find open cursors that have been parsed. You need to be logged in as a user with access to v$open_cursor and v$session.

COLUMN USER_NAME FORMAT A15

SELECT s.machine, oc.user_name, oc.sql_text, count(1) 
FROM v$open_cursor oc, v$session s
WHERE oc.sid = s.sid
GROUP BY user_name, sql_text, machine
HAVING COUNT(1) > 2
ORDER BY count(1) DESC
;

If gives you part of the SQL text so it can be useful for identifying leaky applications. If a cursor has not been parsed, then it does not appear here. Note that Oralce will sometimes keep things open longer than you do.

OR operator in switch-case?

foreach (array('one', 'two', 'three') as $v) {
    switch ($v) {
        case (function ($v) {
            if ($v == 'two') return $v;
            return 'one';
        })($v):
            echo "$v min \n";
            break;


    }
}

this works fine for languages supporting enclosures

How do you manually execute SQL commands in Ruby On Rails using NuoDB

res = ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query( "SELECT 1;" ) }

The above code is an example for

  1. executing arbitrary SQL on your database-connection
  2. returning the connection back to the connection pool afterwards

Transport security has blocked a cleartext HTTP

On 2015-09-25 (after Xcode updates on 2015-09-18):

I used a non-lazy method, but it didn't work. The followings are my tries.

First,

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>www.xxx.yyy.zzz</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

And second,

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>www.xxx.yyy.zzz</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

Finally, I used the lazy method:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

It might be a little insecure, but I couldn't find other solutions.

How do I space out the child elements of a StackPanel?

The thing you really want to do is wrap all child elements. In this case you should use an items control and not resort to horrible attached properties which you will end up having a million of for every property you wish to style.

<ItemsControl>

    <!-- target the wrapper parent of the child with a style -->
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="Control">
            <Setter Property="Margin" Value="0 0 5 0"></Setter>
        </Style>
    </ItemsControl.ItemContainerStyle>

    <!-- use a stack panel as the main container -->
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <!-- put in your children -->
    <ItemsControl.Items>
        <Label>Auto Zoom Reset?</Label>
        <CheckBox x:Name="AutoResetZoom"/>
        <Button x:Name="ProceedButton" Click="ProceedButton_OnClick">Next</Button>
        <ComboBox SelectedItem="{Binding LogLevel }" ItemsSource="{Binding LogLevels}" />
    </ItemsControl.Items>
</ItemsControl>

enter image description here

How do I add a margin between bootstrap columns without wrapping

I was facing the same issue; and the following worked well for me. Hope this helps someone landing here:

<div class="row">
    <div class="col-md-6">
        <div class="col-md-12">
            Set room heater temperature
        </div>
    </div>
    <div class="col-md-6">
        <div class="col-md-12">
            Set room heater temperature
        </div>
    </div>
</div>

This will automatically render some space between the 2 divs. enter image description here

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

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

I see that you've tagged this question with the google-spreadsheet-api tag. So by "drop-down" do you mean Google App Script's ListBox? If so, you may toggle a user's ability to select multiple items from the ListBox with a simple true/false value.
Here's an example:

`var lb = app.createListBox(true).setId('myId').setName('myLbName');` 

Notice that multiselect is enabled because of the word true.

Kafka consumer list

Kafka stores all the information in zookeeper. You can see all the topic related information under brokers->topics. If you wish to get all the topics programmatically you can do that using Zookeeper API.

It is explained in detail in below links Tutorialspoint, Zookeeper Programmer guide

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

Try using No Wrap - In Head or No wrap - in body in your fiddle:

Working fiddle: http://jsfiddle.net/Q5hd6/

Explanation:

Angular begins compiling the DOM when the DOM is fully loaded. You register your code to run onLoad (onload option in fiddle) => it's too late to register your myApp module because angular begins compiling the DOM and angular sees that there is no module named myApp and throws an exception.

By using No Wrap - In Head, your code looks like this:

<head>

    <script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js'></script>

    <script type='text/javascript'>
      //Your script.
    </script>

</head>

Your script has a chance to run before angular begins compiling the DOM and myApp module is already created when angular starts compiling the DOM.

Combine two or more columns in a dataframe into a new column with a new name

Instead of

  • paste (default spaces),
  • paste0 (force the inclusion of missing NA as character) or
  • unite (constrained to 2 columns and 1 separator),

I'd suggest an alternative as flexible as paste0 but more careful with NA: stringr::str_c

library(tidyverse)

# check the missing value!!
df <- tibble(
  n = c(2, 2, 8),
  s = c("aa", "aa", NA_character_),
  b = c(TRUE, FALSE, TRUE)
)

df %>% 
  mutate(
    paste = paste(n,"-",s,".",b),
    paste0 = paste0(n,"-",s,".",b),
    str_c = str_c(n,"-",s,".",b)
  ) %>% 

  # convert missing value to ""
  mutate(
    s_2=str_replace_na(s,replacement = "")
  ) %>% 
  mutate(
    str_c_2 = str_c(n,"-",s_2,".",b)
  )
#> # A tibble: 3 x 8
#>       n s     b     paste          paste0     str_c      s_2   str_c_2   
#>   <dbl> <chr> <lgl> <chr>          <chr>      <chr>      <chr> <chr>     
#> 1     2 aa    TRUE  2 - aa . TRUE  2-aa.TRUE  2-aa.TRUE  "aa"  2-aa.TRUE 
#> 2     2 aa    FALSE 2 - aa . FALSE 2-aa.FALSE 2-aa.FALSE "aa"  2-aa.FALSE
#> 3     8 <NA>  TRUE  8 - NA . TRUE  8-NA.TRUE  <NA>       ""    8-.TRUE

Created on 2020-04-10 by the reprex package (v0.3.0)

extra note from str_c documentation

Like most other R functions, missing values are "infectious": whenever a missing value is combined with another string the result will always be missing. Use str_replace_na() to convert NA to "NA"

TypeError: 'float' object not iterable

for i in count: means for i in 7:, which won't work. The bit after the in should be of an iterable type, not a number. Try this:

for i in range(count):

shorthand If Statements: C#

Yes. Use the ternary operator.

condition ? true_expression : false_expression;

Close a div by clicking outside

Add a transparent background taking up the whole window size, just before your popup div

.transparent-back{
    position: fixed;
    top: 0px;
    left:0px;
    width: 100%;
    height: 100%;
    background-color: rgba(255,255,255,0.5);
}

Then on its click, dismiss the popup.

$(".transparent-back").on('click',function(){
    $('popup').fadeOut(300);
});

How to list imported modules?

If you want to do this from outside the script:

Python 2

from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script("myscript.py")
for name, mod in finder.modules.iteritems():
    print name

Python 3

from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script("myscript.py")
for name, mod in finder.modules.items():
    print(name)

This will print all modules loaded by myscript.py.

Generate random 5 characters string

Similar to Brad Christie's answer, but using sha1 alrorithm for characters 0-9a-zA-Z and prefixed with a random value :

$str = substr(sha1(mt_rand() . microtime()), mt_rand(0,35), 5);

But if you have set a defined (allowed) characters :

$validChars = array('0','1','2' /*...*/,'?','-','_','a','b','c' /*...*/);
$validCharsCount = count($validChars);

$str = '';
for ($i=0; $i<5; $i++) {
    $str .= $validChars[rand(0,$validCharsCount - 1)];
}

** UPDATE **

As Archimedix pointed out, this will not guarantee to return a "least possibility of getting duplicated" as the number of combination is low for the given character range. You will either need to increase the number of characters, or allow extra (special) characters in the string. The first solution would be preferable, I think, in your case.

How to pass in a react component into another react component to transclude the first component's content?

You can pass in a component via. the props and render it with interpolation.

var DivWrapper = React.createClass({
    render: function() {
        return <div>{ this.props.child }</div>;
    }
});

You would then pass in a prop called child, which would be a React component.

How do I configure HikariCP in my Spring Boot app in my application.properties files?

You can use the dataSourceClassName approach, here is an example with MySQL. (Tested with spring boot 1.3 and 1.4)

First you need to exclude tomcat-jdbc from the classpath as it will be picked in favor of hikaricp.

pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

application.properties

spring.datasource.dataSourceClassName=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
spring.datasource.dataSourceProperties.serverName=localhost
spring.datasource.dataSourceProperties.portNumber=3311
spring.datasource.dataSourceProperties.databaseName=mydb
spring.datasource.username=root
spring.datasource.password=root

Then just add

@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

I created a test project here: https://github.com/ydemartino/spring-boot-hikaricp

How to clear or stop timeInterval in angularjs?

You can store the promise returned by the interval and use $interval.cancel() to that promise, which cancels the interval of that promise. To delegate the starting and stopping of the interval, you can create start() and stop() functions whenever you want to stop and start them again from a specific event. I have created a snippet below showing the basics of starting and stopping an interval, by implementing it in view through the use of events (e.g. ng-click) and in the controller.

_x000D_
_x000D_
angular.module('app', [])_x000D_
_x000D_
  .controller('ItemController', function($scope, $interval) {_x000D_
  _x000D_
    // store the interval promise in this variable_x000D_
    var promise;_x000D_
  _x000D_
    // simulated items array_x000D_
    $scope.items = [];_x000D_
    _x000D_
    // starts the interval_x000D_
    $scope.start = function() {_x000D_
      // stops any running interval to avoid two intervals running at the same time_x000D_
      $scope.stop(); _x000D_
      _x000D_
      // store the interval promise_x000D_
      promise = $interval(setRandomizedCollection, 1000);_x000D_
    };_x000D_
  _x000D_
    // stops the interval_x000D_
    $scope.stop = function() {_x000D_
      $interval.cancel(promise);_x000D_
    };_x000D_
  _x000D_
    // starting the interval by default_x000D_
    $scope.start();_x000D_
 _x000D_
    // stops the interval when the scope is destroyed,_x000D_
    // this usually happens when a route is changed and _x000D_
    // the ItemsController $scope gets destroyed. The_x000D_
    // destruction of the ItemsController scope does not_x000D_
    // guarantee the stopping of any intervals, you must_x000D_
    // be responsible for stopping it when the scope is_x000D_
    // is destroyed._x000D_
    $scope.$on('$destroy', function() {_x000D_
      $scope.stop();_x000D_
    });_x000D_
            _x000D_
    function setRandomizedCollection() {_x000D_
      // items to randomize 1 - 11_x000D_
      var randomItems = parseInt(Math.random() * 10 + 1); _x000D_
        _x000D_
      // empties the items array_x000D_
      $scope.items.length = 0; _x000D_
      _x000D_
      // loop through random N times_x000D_
      while(randomItems--) {_x000D_
        _x000D_
        // push random number from 1 - 10000 to $scope.items_x000D_
        $scope.items.push(parseInt(Math.random() * 10000 + 1)); _x000D_
      }_x000D_
    }_x000D_
  _x000D_
  });
_x000D_
<div ng-app="app" ng-controller="ItemController">_x000D_
  _x000D_
  <!-- Event trigger to start the interval -->_x000D_
  <button type="button" ng-click="start()">Start Interval</button>_x000D_
  _x000D_
  <!-- Event trigger to stop the interval -->_x000D_
  <button type="button" ng-click="stop()">Stop Interval</button>_x000D_
  _x000D_
  <!-- display all the random items -->_x000D_
  <ul>_x000D_
    <li ng-repeat="item in items track by $index" ng-bind="item"></li>_x000D_
  </ul>_x000D_
  <!-- end of display -->_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
_x000D_
_x000D_

How can I simulate mobile devices and debug in Firefox Browser?

Most web applications detects mobile devices based on the HTTP Headers.

If your web site also uses HTTP Headers to identify mobile device, you can do the following:

  1. Add Modify Headers plug in to your Firefox browser ( https://addons.mozilla.org/en-US/firefox/addon/modify-headers/ )
  2. Using plugin modify headers:
    • select Headers tab-> select Action 'ADD'
    • to simulate e.g. iPhone add a header with name User-Agent and value: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
    • click 'Add' button
  3. After that you should be able to see mobile version of you web application in Firefox and use Firebug plugin.

Hope it helps!

How do I loop through a list by twos?

You can also use this syntax (L[start:stop:step]):

mylist = [1,2,3,4,5,6,7,8,9,10]
for i in mylist[::2]:
    print i,
# prints 1 3 5 7 9

for i in mylist[1::2]:
    print i,
# prints 2 4 6 8 10

Where the first digit is the starting index (defaults to beginning of list or 0), 2nd is ending slice index (defaults to end of list), and the third digit is the offset or step.

How to round the corners of a button

updated for Swift 3 :

used below code to make UIButton corner round:

 yourButtonOutletName.layer.cornerRadius = 0.3 *
        yourButtonOutletName.frame.size.height

Find Process Name by its Process ID

The basic one, ask tasklist to filter its output and only show the indicated process id information

tasklist /fi "pid eq 4444" 

To only get the process name, the line must be splitted

for /f "delims=," %%a in ('
    tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a

In this case, the list of processes is retrieved without headers (/nh) in csv format (/fo:csv). The commas are used as token delimiters and the first token in the line is the image name

note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command

for /f "delims=," %%a in ('
    tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a

This will generate the task list and filter it searching for the process id in the second column of the csv output.

edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.

tasklist /fi "idp eq 4444" 

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

Check element CSS display with JavaScript

Basic JavaScript:

if (document.getElementById("elementId").style.display == 'block') { 
  alert('this Element is block'); 
}

Java AES encryption and decryption

If for a block cipher you're not going to use a Cipher transformation that includes a padding scheme, you need to have the number of bytes in the plaintext be an integral multiple of the block size of the cipher.

So either pad out your plaintext to a multiple of 16 bytes (which is the AES block size), or specify a padding scheme when you create your Cipher objects. For example, you could use:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Unless you have a good reason not to, use a padding scheme that's already part of the JCE implementation. They've thought out a number of subtleties and corner cases you'll have to realize and deal with on your own otherwise.


Ok, your second problem is that you are using String to hold the ciphertext.

In general,

String s = new String(someBytes);
byte[] retrievedBytes = s.getBytes();

will not have someBytes and retrievedBytes being identical.

If you want/have to hold the ciphertext in a String, base64-encode the ciphertext bytes first and construct the String from the base64-encoded bytes. Then when you decrypt you'll getBytes() to get the base64-encoded bytes out of the String, then base64-decode them to get the real ciphertext, then decrypt that.

The reason for this problem is that most (all?) character encodings are not capable of mapping arbitrary bytes to valid characters. So when you create your String from the ciphertext, the String constructor (which applies a character encoding to turn the bytes into characters) essentially has to throw away some of the bytes because it can make no sense of them. Thus, when you get bytes out of the string, they are not the same bytes you put into the string.

In Java (and in modern programming in general), you cannot assume that one character = one byte, unless you know absolutely you're dealing with ASCII. This is why you need to use base64 (or something like it) if you want to build strings from arbitrary bytes.

Changing the browser zoom level

Possible in IE and chrome although it does not work in firefox:

<script>
   function toggleZoomScreen() {
       document.body.style.zoom = "80%";
   } 
</script>

<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">

SFTP Libraries for .NET

I've used IP*Works SSH and it is great. Easy to setup and use. Plus, their support is top-notch when you run into questions or problems.

How to scroll to top of page with JavaScript/jQuery?

Is there a way to PREVENT the browser scrolling to its past position, or to re-scroll to the top AFTER it does its thing?

The following jquery solution works for me:

$(window).unload(function() {
    $('body').scrollTop(0);
});

Update multiple rows using select statement

If you have ids in both tables, the following works:

update table2
    set value = (select value from table1 where table1.id = table2.id)

Perhaps a better approach is a join:

update table2
    set value = table1.value
    from table1
    where table1.id = table2.id

Note that this syntax works in SQL Server but may be different in other databases.

What does .shape[] do in "for i in range(Y.shape[0])"?

shape() consists of array having two arguments rows and columns.

if you search shape[0] then it will gave you the number of rows. shape[1] will gave you number of columns.

How to fix "unable to write 'random state' " in openssl

The quickest solution is: set environment variable RANDFILE to path where the 'random state' file can be written (of course check the file access permissions), eg. in your command prompt:

set RANDFILE=C:\MyDir\.rnd
openssl genrsa -out my-prvkey.pem 1024

More explanations: OpenSSL on Windows tries to save the 'random state' file in the following order:

  1. Path taken from RANDFILE environment variable
  2. If HOME environment variable is set then : ${HOME}\.rnd
  3. C:\.rnd

I'm pretty sure that in your case it ends up trying to save it in C:\.rnd (and it fails because lack of sufficient access rights). Unfortunately OpenSSL does not print the path that is actually tries to use in any error messages.

How to round up the result of integer division?

For C# the solution is to cast the values to a double (as Math.Ceiling takes a double):

int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);

In java you should do the same with Math.ceil().

java.net.SocketException: Connection reset by peer: socket write error When serving a file

It is possible for the TCP socket to be "closing" and your code to not have yet been notified.

Here is a animation for the life cycle. http://tcp.cs.st-andrews.ac.uk/index.shtml?page=connection_lifecycle

Basically, the connection was closed by the client. You already have throws IOException and SocketException extends IOException. This is working just fine. You just need to properly handle IOException because it is a normal part of the api.

EDIT: The RST packet occurs when a packet is received on a socket which does not exist or was closed. There is no difference to your application. Depending on the implementation the reset state may stick and closed will never officially occur.

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

I see there's a lot of good answers already, but this should provide the closest to native OSX functionality as possible in more than just your shell. I verified that this works in ZSH, Bash, node, python -i, iex and irb/pry sessions (using rb-readline gem for readline, but should work for all).

Open the iTerm preferences ?+, and navigate to the Profiles tab (the Keys tab can be used, but adding keybinding to your profile allows you to save your profile and sync it to multiple computers) and keys sub-tab and enter the following:

Delete all characters left of the cursor

?+?Delete Send Hex Codes:

0x15 More compatible, but functionality sometimes is to delete the entire line rather than just the characters to the left of the curser. I personally use this and then overwrite my zsh bindkey for ^U to delete only stuff to the left of the cursor (see below).

or

0x18 0x7f Less compatible, doesn't work in node and won't work in zsh by default, see below to fix zsh (bash/irb/pry should be fine), performs desired functionality when it does work.

Delete all characters right of the cursor

?+fn+?Delete or ?+Delete? Send Hex Codes: 0x0b

Delete one word to left of cursor

?+?Delete Send Hex Codes:

0x1b 0x08 Breaks in Elixir's IEX, seems to work fine everywhere else

or

0x17 Works everywhere, but doesn't stop at normal word breaks in IRB and will instead delete until it sees a literal space.

Delete one word to right of cursor

?+fn?Delete or ?+Delete? Send Hex Codes: 0x1b 0x64

Move cursor to the front of line

?+? Send Hex Codes: 0x01

Move cursor to the end of line

?+? Send Hex Codes: 0x05

Move cursor one word left

?+? Send Hex Codes: 0x1b 0x62

Move cursor one word right

?+? Send Hex Codes: 0x1b 0x66

Undo

?+z Send Hex Codes: 0x1f

Redo typically not bound in bash, zsh or readline, so we can set it to a unused hexcode which we can then fix in zsh

?+?+Z or ?+y Send Hex Codes: 0x18 0x1f

Now how to fix any that don't work

For zsh, you can setup binding for the not yet functional ?+?Delete and ?+?+Z/?+y by running:

# changes hex 0x15 to delete everything to the left of the cursor,
# rather than the whole line
$ echo 'bindkey "^U" backward-kill-line' >> ~/.zshrc

# binds hex 0x18 0x7f with deleting everything to the left of the cursor
$ echo 'bindkey "^X\\x7f" backward-kill-line' >> ~/.zshrc

# adds redo
$ echo 'bindkey "^X^_" redo' >> ~/.zshrc

# reload your .zshrc for changes to take effect
$ source ~/.zshrc

I'm unable to find a solution for adding redo in bash or readline, so if anyone know a solution for either of those, please comment below and I'll try to add them in.

For anyone looking for the lookup table on how to convert key sequences to hex, I find this table very helpful.

Update statement using with clause

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

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

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

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

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

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

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I had a very similar problem. I was trying to use Newtonsoft.Json.dll in a .NET DLL, in the same way that I am successfully using it in .NET EXEs on my computer. I used NuGet in my Visual Studio 2017 to add Newtonsoft.Json to MyDll.dll. MyExecutable.exe references MyDll.dll. Calling a Newtonsoft.Json method from code within MyDll.dll raised "System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)".

I ran Microsoft's fuslogvw.exe https://docs.microsoft.com/en-us/dotnet/framework/tools/fuslogvw-exe-assembly-binding-log-viewer to check what was being loaded and found the following:

LOG: Post-policy reference: Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///C:/MyExecutable/bin/Debug/Newtonsoft.Json.DLL.
LOG: Assembly download was successful. Attempting setup of file: C:\MyExecutable\bin\Debug\Newtonsoft.Json.dll
LOG: Entering run-from-source setup phase.
LOG: Assembly Name is: Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: The assembly reference did not match the assembly definition found.
ERR: Run-from-source setup phase failed with hr = 0x80131040.
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

MyExecutable.exe had no references or calls to Newtonsoft.Json, yet I found a 6.0.0.0 Newtonsoft.Json.dll in bin\Debug directories of copies of my MyExecutable source tree from before I added any Newtonsoft.Json references to any of my code. I do not know why the 6.0.0.0 Newtonsoft.Json.dll was there. Perhaps it was referenced by another DLL referenced by MyExecutable. I avoided the FileLoadException by using NuGet to add a reference to 12.0.0.0 Newtonsoft.Json to MyExecutable.

I expected that binding redirect in MyExecutable’s App.config as illustrated below would be an alternative to MyExecutable’s referencing Newtonsoft.Json, but it did not work. …

How can I encode a string to Base64 in Swift?

Swift 4.0.3

import UIKit

extension String {

func fromBase64() -> String? {
    guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else {
        return nil
    }

    return String(data: data as Data, encoding: String.Encoding.utf8)
}

func toBase64() -> String? {
    guard let data = self.data(using: String.Encoding.utf8) else {
        return nil
    }

    return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
    }
}

How to edit nginx.conf to increase file size upload

Add client_max_body_size

Now that you are editing the file you need to add the line into the server block, like so;

server {
    client_max_body_size 8M;

    //other lines...
}

If you are hosting multiple sites add it to the http context like so;

http {
    client_max_body_size 8M;

    //other lines...
}

And also update the upload_max_filesize in your php.ini file so that you can upload files of the same size.

Saving in Vi

Once you are done you need to save, this can be done in vi with pressing esc key and typing :wq and returning.

Restarting Nginx and PHP

Now you need to restart nginx and php to reload the configs. This can be done using the following commands;

sudo service nginx restart
sudo service php5-fpm restart

Or whatever your php service is called.

How can I disable the UITableView selection?

You can use :

cell.selectionStyle = UITableViewCellSelectionStyleNone;

in the cell for row at index path method of your UITableView.

Also you can use :

[tableView deselectRowAtIndexPath:indexPath animated:NO];

in the tableview didselectrowatindexpath method.

Change directory in PowerShell

Unlike the CMD.EXE CHDIR or CD command, the PowerShell Set-Location cmdlet will change drive and directory, both. Get-Help Set-Location -Full will get you more detailed information on Set-Location, but the basic usage would be

PS C:\> Set-Location -Path Q:\MyDir

PS Q:\MyDir> 

By default in PowerShell, CD and CHDIR are alias for Set-Location.

(Asad reminded me in the comments that if the path contains spaces, it must be enclosed in quotes.)

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

you can use transition in css3:

_x000D_
_x000D_
.carousel-fade .carousel-inner .item {_x000D_
  -webkit-transition-property: opacity;_x000D_
  transition-property: opacity;_x000D_
}_x000D_
.carousel-fade .carousel-inner .item,_x000D_
.carousel-fade .carousel-inner .active.left,_x000D_
.carousel-fade .carousel-inner .active.right {_x000D_
  opacity: 0;_x000D_
}_x000D_
.carousel-fade .carousel-inner .active,_x000D_
.carousel-fade .carousel-inner .next.left,_x000D_
.carousel-fade .carousel-inner .prev.right {_x000D_
  opacity: 1;_x000D_
}_x000D_
.carousel-fade .carousel-inner .next,_x000D_
.carousel-fade .carousel-inner .prev,_x000D_
.carousel-fade .carousel-inner .active.left,_x000D_
.carousel-fade .carousel-inner .active.right {_x000D_
  left: 0;_x000D_
  -webkit-transform: translate3d(0, 0, 0);_x000D_
          transform: translate3d(0, 0, 0);_x000D_
}_x000D_
.carousel-fade .carousel-control {_x000D_
  z-index: 2;_x000D_
}
_x000D_
_x000D_
_x000D_

Android Studio - How to Change Android SDK Path

This is how its done,in Android Studio for windows First got to Project Structure

Then to sdk location tab

From there select android sdk location and select your sdk path and then click on OK button

Done

PHP: cannot declare class because the name is already in use

I had this problem before and to fix this, Just make sure :

  1. You did not create an instance of this class before
  2. If you call this from a class method, make sure the __destruct is set on the class you called from.

My problem (before) :
I had class : Core, Router, Permissions and Render Core include's the Router class, Router then calls Permissions class, then Router __destruct calls the Render class and the error "Cannot declare class because the name is already in use" appeared.

Solution :
I added __destruct on Permission class and the __destruct was empty and it's fixed...

Android device chooser - My device seems offline

When you attach your android with your PC, you will get couple of options mentioning the way you may connect with the computer. In my case, I am using HTC Wildfire and it displays

  1. Charge only
  2. HTC Sync
  3. Disk Drive
  4. USB Tethering

I was also facing the problem the Question states and I have tested the way David Caunt answered but yet device was showing offline. *

I rechecked the options and found I selected the Disk Drive option. Then I changed the option to Charge only mode and again follow David Caunt's steps. I don't know why, but this time it worked for me.

How do I get first element rather than using [0] in jQuery?

You can use the first method:

$('li').first()

http://api.jquery.com/first/

btw I agree with Nick Craver -- use document.getElementById()...

How can I initialize an array without knowing it size?

Use LinkedList instead. Than, you can create an array if necessary.

Webpack - webpack-dev-server: command not found

I noticed the same problem after installing VSCode and adding a remote Git repository. Somehow the /node_modules/.bin folder was deleted and running npm install --save webpack-dev-server in the command line re-installed the missing folder and fixed my problem.

Python loop that also accesses previous and next values

Pythonic and elegant way:

objects = [1, 2, 3, 4, 5]
value = 3
if value in objects:
   index = objects.index(value)
   previous_value = objects[index-1]
   next_value = objects[index+1] if index + 1 < len(objects) else None

How to place and center text in an SVG rectangle

Full Detail Blog :http://blog.techhysahil.com/svg/how-to-center-text-in-svg-shapes/

_x000D_
_x000D_
<svg width="600" height="600">_x000D_
  <!--   Circle -->_x000D_
  <g transform="translate(50,40)">_x000D_
    <circle cx="0" cy="0" r="35" stroke="#aaa" stroke-width="2" fill="#fff"></circle>_x000D_
    <text x="0" y="0" alignment-baseline="middle" font-size="12" stroke-width="0" stroke="#000" text-anchor="middle">HueLink</text>_x000D_
  </g>_x000D_
  _x000D_
  <!--   In Rectangle text position needs to be given half of width and height of rectangle respectively -->_x000D_
  <!--   Rectangle -->_x000D_
  <g transform="translate(150,20)">_x000D_
    <rect width="150" height="40" stroke="#aaa" stroke-width="2" fill="#fff"></rect>_x000D_
    <text x="75" y="20" alignment-baseline="middle" font-size="12" stroke-width="0" stroke="#000" text-anchor="middle">HueLink</text>_x000D_
  </g>_x000D_
  _x000D_
  <!--   Rectangle -->_x000D_
  <g transform="translate(120,140)">_x000D_
    <ellipse cx="0" cy="0" rx="100" ry="50" stroke="#aaa" stroke-width="2" fill="#fff"></ellipse>_x000D_
    <text x="0" y="0" alignment-baseline="middle" font-size="12" stroke-width="0" stroke="#000" text-anchor="middle">HueLink</text>_x000D_
  </g>_x000D_
  _x000D_
  _x000D_
</svg>
_x000D_
_x000D_
_x000D_

Which Python memory profiler is recommended?

I found meliae to be much more functional than Heapy or PySizer. If you happen to be running a wsgi webapp, then Dozer is a nice middleware wrapper of Dowser

NSDate get year/month/day

In Swift 2.0:

    let date = NSDate()
    let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
    let components = calendar.components([.Month, .Day], fromDate: date)

    let (month, day) = (components.month, components.day)

How can I set a custom date time format in Oracle SQL Developer?

You can change this in preferences:

  1. From Oracle SQL Developer's menu go to: Tools > Preferences.
  2. From the Preferences dialog, select Database > NLS from the left panel.
  3. From the list of NLS parameters, enter DD-MON-RR HH24:MI:SS into the Date Format field.
  4. Save and close the dialog, done!

Here is a screenshot:

Changing Date Format preferences in Oracle SQL Developer

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

For "partial" I always use it as follows:

If there's something you need to include in a page that you need to go via the controller (like you would with an Ajax call) then use "Html.RenderPartial".

If you have a 'static' include that isn't linked to a controller per-se and just in the 'shared' folder for example, use "HTML.partial"

How to apply slide animation between two activities in Android?

Here is a Slide Animation for you.

enter image description here

Let's say you have two activities.

  1. MovieDetailActivity
  2. AllCastActivity

And on click of a Button, this happens.

enter image description here

You can achieve this in 3 simple steps

1) Enable Content Transition

Go to your style.xml and add this line to enable the content transition.

<item name="android:windowContentTransitions">true</item>

2) Write Default Enter and Exit Transition for your AllCastActivity

public void setAnimation()
{
    if(Build.VERSION.SDK_INT>20) {
        Slide slide = new Slide();
        slide.setSlideEdge(Gravity.LEFT);
        slide.setDuration(400);
        slide.setInterpolator(new AccelerateDecelerateInterpolator());
        getWindow().setExitTransition(slide);
        getWindow().setEnterTransition(slide);
    }
}

3) Start Activity with Intent

Write this method in Your MovieDetailActivity to start AllCastActivity

public void startActivity(){

Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putStringArrayListExtra(MOVIE_LIST, movie.getImages());

  if(Build.VERSION.SDK_INT>20)
   {
       ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(BlankActivity.this);
       startActivity(i,options.toBundle());
   }
   else {
       startActivity(i);
   }
}

Most important!

put your setAnimation()method before setContentView() method otherwise the animation will not work.
So your AllCastActivity.javashould look like this

 class AllCastActivity extends AppcompatActivity {

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

      setAnimation();

      setContentView(R.layout.all_cast_activity);

      .......
   }

   private void setAnimation(){

      if(Build.VERSION.SDK_INT>20) {
      Slide slide = new Slide();
      slide.setSlideEdge(Gravity.LEFT);
      ..........
  }
}

c# .net change label text

Have you tried running the code in the Page_Load() method?

protected void Page_Load(object sender, EventArgs e) 
{

         Label1.Text = "test";
        if (Request.QueryString["ID"] != null)
        {

            string test = Request.QueryString["ID"];
            Label1.Text = "Du har nu lånat filmen:" + test;
        }
}

POST: sending a post request in a url itself

If you are sending a request through url from browser(like consuming webservice) without using html pages by default it will be GET because GET has/needs no body. if you want to make url as POST you need html/jsp pages and you have to mention in form tag as "method=post" beacause post will have body and data will be transferred in that body for security reasons. So you need a medium (like html page) to make a POST request. You cannot make an URL as POST manually unless you specify it as POST through some medium. For example in URL (http://example.com/details?name=john&phonenumber=445566)you have attached data(name, phone number) so server will identify it as a GET data because server is receiving data is through URL but not inside a request body

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

I've solved using only @JsonIgnore like @kryger has suggested. So your getter will become:

@JsonIgnore
public String getEncryptedPwd() {
    return this.encryptedPwd;
}

You can set @JsonIgnore of course on field, setter or getter like described here.

And, if you want to protect encrypted password only on serialization side (e.g. when you need to login your users), add this @JsonProperty annotation to your field:

@JsonProperty(access = Access.WRITE_ONLY)
private String encryptedPwd;

More info here.

How to run python script on terminal (ubuntu)?

Sorry, Im a newbie myself and I had this issue:

./hello.py: line 1: syntax error near unexpected token "Hello World"' ./hello.py: line 1:print("Hello World")'

I added the file header for the python 'deal' as #!/usr/bin/python

Then simple executed the program with './hello.py'

C# looping through an array

Not too difficult. Just increment the counter of the for loop by 3 each iteration and then offset the indexer to get the batch of 3 at a time:

for(int i=0; i < theData.Length; i+=3)
{
    var item1 = theData[i];
    var item2 = theData[i+1];
    var item3 = theData[i+2];
}

If the length of the array wasn't garuanteed to be a multiple of three, you would need to check the upper bound with theData.Length - 2 instead.

How to call a method daily, at specific time, in C#?

I found this very useful:

using System;
using System.Timers;

namespace ScheduleTimer
{
    class Program
    {
        static Timer timer;

        static void Main(string[] args)
        {
            schedule_Timer();
            Console.ReadLine();
        }

        static void schedule_Timer()
        {
            Console.WriteLine("### Timer Started ###");

            DateTime nowTime = DateTime.Now;
            DateTime scheduledTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 8, 42, 0, 0); //Specify your scheduled time HH,MM,SS [8am and 42 minutes]
            if (nowTime > scheduledTime)
            {
                scheduledTime = scheduledTime.AddDays(1);
            }

            double tickTime = (double)(scheduledTime - DateTime.Now).TotalMilliseconds;
            timer = new Timer(tickTime);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }

        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("### Timer Stopped ### \n");
            timer.Stop();
            Console.WriteLine("### Scheduled Task Started ### \n\n");
            Console.WriteLine("Hello World!!! - Performing scheduled task\n");
            Console.WriteLine("### Task Finished ### \n\n");
            schedule_Timer();
        }
    }
}

How do I convert a String object into a Hash object?

Please consider this solution. Library+spec:

File: lib/ext/hash/from_string.rb:

require "json"

module Ext
  module Hash
    module ClassMethods
      # Build a new object from string representation.
      #
      #   from_string('{"name"=>"Joe"}')
      #
      # @param s [String]
      # @return [Hash]
      def from_string(s)
        s.gsub!(/(?<!\\)"=>nil/, '":null')
        s.gsub!(/(?<!\\)"=>/, '":')
        JSON.parse(s)
      end
    end
  end
end

class Hash    #:nodoc:
  extend Ext::Hash::ClassMethods
end

File: spec/lib/ext/hash/from_string_spec.rb:

require "ext/hash/from_string"

describe "Hash.from_string" do
  it "generally works" do
    [
      # Basic cases.
      ['{"x"=>"y"}', {"x" => "y"}],
      ['{"is"=>true}', {"is" => true}],
      ['{"is"=>false}', {"is" => false}],
      ['{"is"=>nil}', {"is" => nil}],
      ['{"a"=>{"b"=>"c","ar":[1,2]}}', {"a" => {"b" => "c", "ar" => [1, 2]}}],
      ['{"id"=>34030, "users"=>[14105]}', {"id" => 34030, "users" => [14105]}],

      # Tricky cases.
      ['{"data"=>"{\"x\"=>\"y\"}"}', {"data" => "{\"x\"=>\"y\"}"}],   # Value is a `Hash#inspect` string which must be preserved.
    ].each do |input, expected|
      output = Hash.from_string(input)
      expect([input, output]).to eq [input, expected]
    end
  end # it
end

How to make a DIV not wrap?

The min-width property does not work correctly in Internet Explorer, which is most likely the cause of your problems.

Read info and a brilliant script that fixes many IE CSS problems.

Calculating average of an array list?

List.stream().mapToDouble(a->a).average()

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Unobtrusive validation is enabled by default in new version of ASP.NET. Unobtrusive validation aims to decrease the page size by replacing the inline JavaScript for performing validation with a small JavaScript library that uses jQuery.

You can either disable it by editing web.config to include the following:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Or better yet properly configure it by modifying the Application_Start method in global.asax:

void Application_Start(object sender, EventArgs e) 
{
    RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
        new ScriptResourceDefinition
        {
            Path = "/~Scripts/jquery-2.1.1.min.js"
        }
    );
}

Page 399 of Beginning ASP.NET 4.5.1 in C# and VB provides a discussion on the benefit of unobtrusive validation and a walkthrough for configuring it.

For those looking for RouteConfig. It is added automatically when you make a new project in visual studio to the App_Code folder. The contents look something like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace @default
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);
        }
    }
}

Get selected row item in DataGrid WPF

@Krytox answer with MVVM

    <DataGrid 
        Grid.Column="1" 
        Grid.Row="1"
        Margin="10" Grid.RowSpan="2"
        ItemsSource="{Binding Data_Table}"
        SelectedItem="{Binding Select_Request, Mode=TwoWay}" SelectionChanged="DataGrid_SelectionChanged"/>//The binding



    #region View Model
    private DataRowView select_request;
    public DataRowView Select_Request
    {
        get { return select_request; }
        set
        {
            select_request = value;
            OnPropertyChanged("Select_Request"); //INotifyPropertyChange
            OnSelect_RequestChange();//do stuff
        }
     }

Delete a row in DataGridView Control in VB.NET

If dgv(11, dgv.CurrentRow.Index).Selected = True Then
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
    Exit Sub
End If

Where do I get servlet-api.jar from?

You can find a recent servlet-api.jar in Tomcat 6 or 7 lib directory. If you don't have Tomcat on your machine, download the binary distribution of version 6 or 7 from http://tomcat.apache.org/download-70.cgi

How to display request headers with command line curl

curl's -v or --verbose option shows the HTTP request headers, among other things. Here is some sample output:

$ curl -v http://google.com/
* About to connect() to google.com port 80 (#0)
*   Trying 66.102.7.104... connected
* Connected to google.com (66.102.7.104) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.16.4 (i386-apple-darwin9.0) libcurl/7.16.4 OpenSSL/0.9.7l zlib/1.2.3
> Host: google.com
> Accept: */*
> 
< HTTP/1.1 301 Moved Permanently
< Location: http://www.google.com/
< Content-Type: text/html; charset=UTF-8
< Date: Thu, 15 Jul 2010 06:06:52 GMT
< Expires: Sat, 14 Aug 2010 06:06:52 GMT
< Cache-Control: public, max-age=2592000
< Server: gws
< Content-Length: 219
< X-XSS-Protection: 1; mode=block
< 
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact
* Closing connection #0

Apache shutdown unexpectedly

I have also faced the same issue while installing the XAMPP. The reason being the port 80 as configured in httpd.conf is already in use in other application (eg., in Skype). You can change the port value in httpd.conf to 8080 or other number. Click on config icon and open http.conf file. Search for 80 and do the following steps

In httpd.conf change
Listen 80 to Listen 8080
and
ServerName localhost:80 to
ServerName localhost:8080

You can check the ports used currently by clicking on netstatt icon in the XAMPP Control Panel

How to create custom spinner like border around the spinner with down triangle on the right side?

You could design a simple nine-patch png image and use it as the background of spinner. Using GIMP you can put both border and right triangle in image.

Best way to read a large file into a byte array in C#?

Simply replace the whole thing with:

return File.ReadAllBytes(fileName);

However, if you are concerned about the memory consumption, you should not read the whole file into memory all at once at all. You should do that in chunks.

How to get the previous url using PHP

$_SERVER['HTTP_REFERER'] is the answer

Java Garbage Collection Log messages

I just wanted to mention that one can get the detailed GC log with the

-XX:+PrintGCDetails 

parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.

Also -Xloggc:gc.log seems to generate the same output like -verbose:gc but you can specify an output file in the first.

Example usage:

java -Xloggc:./memory.log -XX:+PrintGCDetails Memory

To visualize the data better you can try gcviewer (a more recent version can be found on github).

Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!

How do I set a column value to NULL in SQL Server Management Studio?

CTRL+0 doesn't seem to work when connected to an Azure DB.

However, to create an empty string, you can always just hit 'anykey then delete' inside a cell.

How to display JavaScript variables in a HTML page without document.write

hi here is a simple example: <div id="test">content</div> and

var test = 5;
document.getElementById('test').innerHTML = test;

and you can test it here : http://jsfiddle.net/SLbKX/

Strip Leading and Trailing Spaces From Java String

trim() is your choice, but if you want to use replace method -- which might be more flexiable, you can try the following:

String stripppedString = myString.replaceAll("(^ )|( $)", "");

Can I override and overload static methods in Java?

class SuperType {

    public static void  classMethod(){
        System.out.println("Super type class method");
    }
    public void instancemethod(){
        System.out.println("Super Type instance method");
    }
}


public class SubType extends SuperType{


    public static void classMethod(){
        System.out.println("Sub type class method");
    }
    public void instancemethod(){
        System.out.println("Sub Type instance method");
    }
    public static void main(String args[]){
        SubType s=new SubType();
        SuperType su=s;
        SuperType.classMethod();// Prints.....Super type class method
        su.classMethod();   //Prints.....Super type class method
        SubType.classMethod(); //Prints.....Sub type class method 
    }
}

This example for static method overriding

Note: if we call a static method with object reference, then reference type(class) static method will be called, not object class static method.

Static method belongs to class only.

How to set null to a GUID property

Since "Guid" is not nullable, use "Guid.Empty" as default value.

Adding new files to a subversion repository

Probably svn import would be the best option around. Check out Getting Data into Your Repository (in Version Control with Subversion, For Subversion).

The svn import command is a quick way to copy an unversioned tree of files into a repository, creating intermediate directories as necessary. svn import doesn't require a working copy, and your files are immediately committed to the repository. You typically use this when you have an existing tree of files that you want to begin tracking in your Subversion repository. For example:

$ svn import /path/to/mytree \
             http://svn.example.com/svn/repo/some/project \
             -m "Initial import"
Adding         mytree/foo.c
Adding         mytree/bar.c
Adding         mytree/subdir
Adding         mytree/subdir/quux.h

Committed revision 1.
$

The previous example copied the contents of the local directory mytree into the directory some/project in the repository. Note that you didn't have to create that new directory first—svn import does that for you. Immediately after the commit, you can see your data in the repository:

$ svn list http://svn.example.com/svn/repo/some/project
bar.c
foo.c
subdir/
$

Note that after the import is finished, the original local directory is not converted into a working copy. To begin working on that data in a versioned fashion, you still need to create a fresh working copy of that tree.

Note: if you are on the same machine as the Subversion repository you can use the file:// specifier with a path rather than the https:// with a URL specifier.

Laravel 5.5 ajax call 419 (unknown status)

It's possible your session domain does not match your app URL and/or the host being used to access the application.

1.) Check your .env file:

SESSION_DOMAIN=example.com
APP_URL=example.com

2.) Check config/session.php

Verify values to make sure they are correct.

SQL keys, MUL vs PRI vs UNI

It means that the field is (part of) a non-unique index. You can issue

show create table <table>;

To see more information about the table structure.

Java JTable setting Column Width

This code is worked for me without setAutoResizeModes.

        TableColumnModel columnModel = jTable1.getColumnModel();
        columnModel.getColumn(1).setPreferredWidth(170);
        columnModel.getColumn(1).setMaxWidth(170);
        columnModel.getColumn(2).setPreferredWidth(150);
        columnModel.getColumn(2).setMaxWidth(150);
        columnModel.getColumn(3).setPreferredWidth(40);
        columnModel.getColumn(3).setMaxWidth(40);

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

Some other service may be using port 80: try to stop the other services: HTTPD, SSL, NGINX, PHP, with the command sudo systemctl stop and then use the command sudo systemctl start httpd

Definition of int64_t

int64_t is typedef you can find that in <stdint.h> in C

fatal: bad default revision 'HEAD'

I got the same error and couldn't solve it.

Then I noticed 3 extra files in one of my directories.

The files were named:

config, HEAD, description

I deleted the files, and the error didn't appear.

config contained:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = true

HEAD contained:

ref: refs/heads/master

description contained:

Unnamed repository; edit this file 'description' to name the repository.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

This work around will fix the issue found by @Cletus.

function submitForm(form) {
    //get the form element's document to create the input control with
    //(this way will work across windows in IE8)
    var button = form.ownerDocument.createElement('input');
    //make sure it can't be seen/disrupts layout (even momentarily)
    button.style.display = 'none';
    //make it such that it will invoke submit if clicked
    button.type = 'submit';
    //append it and click it
    form.appendChild(button).click();
    //if it was prevented, make sure we don't get a build up of buttons
    form.removeChild(button);
}

Will work on all modern browsers.
Will work across tabs/spawned child windows (yes, even in IE<9).
And is in vanilla!

Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.

How to get index of object by its property in JavaScript?

collection.findIndex(item => item.value === 'smth') !== -1

Difference between os.getenv and os.environ.get

One difference observed (Python27):

os.environ raises an exception if the environmental variable does not exist. os.getenv does not raise an exception, but returns None

How to undo a git merge with conflicts

Latest Git:

git merge --abort

This attempts to reset your working copy to whatever state it was in before the merge. That means that it should restore any uncommitted changes from before the merge, although it cannot always do so reliably. Generally you shouldn't merge with uncommitted changes anyway.

Prior to version 1.7.4:

git reset --merge

This is older syntax but does the same as the above.

Prior to version 1.6.2:

git reset --hard

which removes all uncommitted changes, including the uncommitted merge. Sometimes this behaviour is useful even in newer versions of Git that support the above commands.

Creating files in C++

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

string filename = "/tmp/filename.txt";

int main() {
  std::ofstream o(filename.c_str());

  o << "Hello, World\n" << std::endl;

  return 0;
}

This is what I had to do in order to use a variable for the filename instead of a regular string.

Interfaces with static fields in java for sharing 'constants'

There is a lot of hate for this pattern in Java. However, an interface of static constants does sometimes have value. You need to basically fulfill the following conditions:

  1. The concepts are part of the public interface of several classes.

  2. Their values might change in future releases.

  3. Its critical that all implementations use the same values.

For example, suppose that you are writing an extension to a hypothetical query language. In this extension you are going to expand the language syntax with some new operations, which are supported by an index. E.g. You are going to have a R-Tree supporting geospatial queries.

So you write a public interface with the static constant:

public interface SyntaxExtensions {
     // query type
     String NEAR_TO_QUERY = "nearTo";

     // params for query
     String POINT = "coordinate";
     String DISTANCE_KM = "distanceInKm";
}

Now later, a new developer thinks he needs to build a better index, so he comes and builds an R* implementation. By implementing this interface in his new tree he guarantees that the different indexes will have identical syntax in the query language. Moreover, if you later decided that "nearTo" was a confusing name, you could change it to "withinDistanceInKm", and know that the new syntax would be respected by all your index implementations.

PS: The inspiration for this example is drawn from the Neo4j spatial code.

Get Absolute Position of element within the window in wpf

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

How to determine a user's IP address in node

If you're using express version 3.x or greater, you can use the trust proxy setting (http://expressjs.com/api.html#trust.proxy.options.table) and it will walk the chain of addresses in the x-forwarded-for header and put the latest ip in the chain that you've not configured as a trusted proxy into the ip property on the req object.

How to create an ArrayList from an Array in PowerShell?

Probably the shortest version:

[System.Collections.ArrayList]$someArray

It is also faster because it does not call relatively expensive New-Object.

how to convert rgb color to int in java

You may declare a value in color.xml, and thus you can get integer value by calling the code below.

context.getColor(int resId);

concat scope variables into string in angular directive expression

<a ngHref="/path/{{obj.val1}}/{{obj.val2}}">{{obj.val1}}, {{obj.val2}}</a>

How can I replace every occurrence of a String in a file with PowerShell?

The one above only runs for "One File" only, but you can also run this for multiple files within your folder:

Get-ChildItem 'C:yourfile*.xml' -Recurse | ForEach {
     (Get-Content $_ | ForEach  { $_ -replace '[MYID]', 'MyValue' }) |
     Set-Content $_
}

"Eliminate render-blocking CSS in above-the-fold content"

I too have struggled with this new pagespeed metric.

Although I have found no practical way to get my score back up to %100 there are a few things I have found helpful.

Combining all css into one file helped a lot. All my sites are back up to %95 - %98.

The only other thing I could think of was to inline all the necessary css (which appears to be most of it - at least for my pages) on the first page to get the sweet high score. Although it may help your speed score this will probably make your page load slower though.

TypeScript: Property does not exist on type '{}'

You can assign the any type to the object:

let bar: any = {};
bar.foo = "foobar"; 

How do I update a Tomcat webapp without restarting the entire service?

There are multiple easy ways.

  1. Just touch web.xml of any webapp.

    touch /usr/share/tomcat/webapps/<WEBAPP-NAME>/WEB-INF/web.xml
    

You can also update a particular jar file in WEB-INF/lib and then touch web.xml, rather than building whole war file and deploying it again.

  1. Delete webapps/YOUR_WEB_APP directory, Tomcat will start deploying war within 5 seconds (assuming your war file still exists in webapps folder).

  2. Generally overwriting war file with new version gets redeployed by tomcat automatically. If not, you can touch web.xml as explained above.

  3. Copy over an already exploded "directory" to your webapps folder

How do I print a datetime in the local timezone?

As of python 3.2, using only standard library functions:

u_tm = datetime.datetime.utcfromtimestamp(0)
l_tm = datetime.datetime.fromtimestamp(0)
l_tz = datetime.timezone(l_tm - u_tm)

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=l_tz)
str(t)
'2009-07-10 18:44:59.193982-07:00'

Just need to use l_tm - u_tm or u_tm - l_tm depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.

And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Serhii's suggestion works and here is some more detail.

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Hope this helps, Glenn

Linux command-line call not returning what it should from os.system?

For your requirement, Popen function of subprocess python module is the answer. For example,

import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Change file permission to 755 for the file:

/var/lib/mongodb/mongod.lock

How to mock void methods with Mockito

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):

import static org.mockito.Mockito.*;

For partial mocking and still keeping original functionality on the rest mockito offers "Spy".

You can use it as follows:

private World world = spy(new World());

To eliminate a method from being executed you could use something like this:

doNothing().when(someObject).someMethod(anyObject());

to give some custom behaviour to a method use "when" with an "thenReturn":

doReturn("something").when(this.world).someMethod(anyObject());

For more examples please find the excellent mockito samples in the doc.

Most efficient way to find smallest of 3 numbers Java?

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

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

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

How do I trap ctrl-c (SIGINT) in a C# console app

The Console.CancelKeyPress event is used for this. This is how it's used:

public static void Main(string[] args)
{
    Console.CancelKeyPress += delegate {
        // call methods to clean up
    };

    while (true) {}
}

When the user presses Ctrl + C the code in the delegate is run and the program exits. This allows you to perform cleanup by calling necessairy methods. Note that no code after the delegate is executed.

There are other situations where this won't cut it. For example, if the program is currently performing important calculations that can't be immediately stopped. In that case, the correct strategy might be to tell the program to exit after the calculation is complete. The following code gives an example of how this can be implemented:

class MainClass
{
    private static bool keepRunning = true;

    public static void Main(string[] args)
    {
        Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
            e.Cancel = true;
            MainClass.keepRunning = false;
        };

        while (MainClass.keepRunning) {
            // Do your work in here, in small chunks.
            // If you literally just want to wait until ctrl-c,
            // not doing anything, see the answer using set-reset events.
        }
        Console.WriteLine("exited gracefully");
    }
}

The difference between this code and the first example is that e.Cancel is set to true, which means the execution continues after the delegate. If run, the program waits for the user to press Ctrl + C. When that happens the keepRunning variable changes value which causes the while loop to exit. This is a way to make the program exit gracefully.

Get type of all variables

R/Rscript doesn't have concrete datatypes.

R interpreter has a duck-typing memory allocation system. There is no builtin method to tell you the datatype of your pointer to memory. Duck typing is done for speed, but turned out to be a bad idea because now statements such as: print(is.integer(5)) returns FALSE and is.integer(as.integer(5)) returns TRUE. Go figure.

The R-manual on basic types: https://cran.r-project.org/doc/manuals/R-lang.html#Basic-types

The best you can hope for is to write your own function to probe your pointer to memory, then use process of elimination to decide if it is suitable for your needs.

If your variable is a global or an object:

Your object() needs to be penetrated with get(...) before you can see inside. Example:

a <- 10
myGlobals <- objects()
for(i in myGlobals){
  typeof(i)         #prints character
  typeof(get(i))    #prints integer
}

typeof(...) probes your variable pointer to memory:

The R function typeof has a bias to give you the type at maximum depth, for example.

library(tibble)

#expression              notes                                  type
#----------------------- -------------------------------------- ----------
typeof(TRUE)             #a single boolean:                     logical
typeof(1L)               #a single numeric with L postfixed:    integer
typeof("foobar")         #A single string in double quotes:     character
typeof(1)                #a single numeric:                     double
typeof(list(5,6,7))      #a list of numeric:                    list
typeof(2i)               #an imaginary number                   complex

typeof(5 + 5L)           #double + integer is coerced:          double
typeof(c())              #an empty vector has no type:          NULL
typeof(!5)               #a bang before a double:               logical
typeof(Inf)              #infinity has a type:                  double
typeof(c(5,6,7))         #a vector containing only doubles:     double
typeof(c(c(TRUE)))       #a vector of vector of logicals:       logical
typeof(matrix(1:10))     #a matrix of doubles has a type:       list

typeof(substr("abc",2,2))#a string at index 2 which is 'b' is:  character
typeof(c(5L,6L,7L))      #a vector containing only integers:    integer
typeof(c(NA,NA,NA))      #a vector containing only NA:          logical
typeof(data.frame())     #a data.frame with nothing in it:      list
typeof(data.frame(c(3))) #a data.frame with a double in it:     list
typeof(c("foobar"))      #a vector containing only strings:     character
typeof(pi)               #builtin expression for pi:            double

typeof(1.66)             #a single numeric with mantissa:       double
typeof(1.66L)            #a double with L postfixed             double
typeof(c("foobar"))      #a vector containing only strings:     character
typeof(c(5L, 6L))        #a vector containing only integers:    integer
typeof(c(1.5, 2.5))      #a vector containing only doubles:     double
typeof(c(1.5, 2.5))      #a vector containing only doubles:     double
typeof(c(TRUE, FALSE))   #a vector containing only logicals:    logical

typeof(factor())         #an empty factor has default type:     integer
typeof(factor(3.14))     #a factor containing doubles:          integer
typeof(factor(T, F))     #a factor containing logicals:         integer
typeof(Sys.Date())       #builtin R dates:                      double
typeof(hms::hms(3600))   #hour minute second timestamp          double
typeof(c(T, F))          #T and F are builtins:                 logical
typeof(1:10)             #a builtin sequence of numerics:       integer
typeof(NA)               #The builtin value not available:      logical

typeof(c(list(T)))       #a vector of lists of logical:         list
typeof(list(c(T)))       #a list of vectors of logical:         list
typeof(c(T, 3.14))       #a vector of logicals and doubles:     double
typeof(c(3.14, "foo"))   #a vector of doubles and characters:   character
typeof(c("foo",list(T))) #a vector of strings and lists:        list
typeof(list("foo",c(T))) #a list of strings and vectors:        list
typeof(TRUE + 5L)        #a logical plus an integer:            integer
typeof(c(TRUE, 5L)[1])   #The true is coerced to 1              integer
typeof(c(c(2i), TRUE)[1])#logical coerced to complex:           complex
typeof(c(NaN, 'batman')) #NaN's in a vector don't dominate:     character
typeof(5 && 4)           #doubles are coerced by order of &&    logical
typeof(8 < 'foobar')     #string and double is coerced          logical
typeof(list(4, T)[[1]])  #a list retains type at every index:   double
typeof(list(4, T)[[2]])  #a list retains type at every index:   logical
typeof(2 ** 5)           #result of exponentiation              double
typeof(0E0)              #exponential lol notation              double
typeof(0x3fade)          #hexidecimal                           double
typeof(paste(3, '3'))    #paste promotes types to string        character
typeof(3 + ?)           #R pukes on unicode                    error
typeof(iconv("a", "latin1", "UTF-8")) #UTF-8 characters         character
typeof(5 == 5)           #result of a comparison:               logical

class(...) probes your variable pointer to memory:

The R function class has a bias to give you the type of container or structure encapsulating your types, for example.

library(tibble)

#expression            notes                                    class
#--------------------- ---------------------------------------- ---------
class(matrix(1:10))     #a matrix of doubles has a class:       matrix
class(factor("hi"))     #factor of items is:                    factor
class(TRUE)             #a single boolean:                      logical
class(1L)               #a single numeric with L postfixed:     integer
class("foobar")         #A single string in double quotes:      character
class(1)                #a single numeric:                      numeric
class(list(5,6,7))      #a list of numeric:                     list
class(2i)               #an imaginary                           complex
class(data.frame())     #a data.frame with nothing in it:       data.frame
class(Sys.Date())       #builtin R dates:                       Date
class(sapply)           #a function is                          function
class(charToRaw("hi"))  #convert string to raw:                 raw
class(array("hi"))      #array of items is:                     array

class(5 + 5L)           #double + integer is coerced:          numeric
class(c())              #an empty vector has no class:         NULL
class(!5)               #a bang before a double:               logical
class(Inf)              #infinity has a class:                 numeric
class(c(5,6,7))         #a vector containing only doubles:     numeric
class(c(c(TRUE)))       #a vector of vector of logicals:       logical

class(substr("abc",2,2))#a string at index 2 which is 'b' is:  character
class(c(5L,6L,7L))      #a vector containing only integers:    integer
class(c(NA,NA,NA))      #a vector containing only NA:          logical
class(data.frame(c(3))) #a data.frame with a double in it:     data.frame
class(c("foobar"))      #a vector containing only strings:     character
class(pi)               #builtin expression for pi:            numeric

class(1.66)             #a single numeric with mantissa:       numeric
class(1.66L)            #a double with L postfixed             numeric
class(c("foobar"))      #a vector containing only strings:     character
class(c(5L, 6L))        #a vector containing only integers:    integer
class(c(1.5, 2.5))      #a vector containing only doubles:     numeric
class(c(TRUE, FALSE))   #a vector containing only logicals:    logical

class(factor())       #an empty factor has default class:      factor
class(factor(3.14))   #a factor containing doubles:            factor
class(factor(T, F))   #a factor containing logicals:           factor
class(hms::hms(3600)) #hour minute second timestamp            hms difftime
class(c(T, F))        #T and F are builtins:                   logical
class(1:10)           #a builtin sequence of numerics:         integer
class(NA)             #The builtin value not available:        logical

class(c(list(T)))       #a vector of lists of logical:         list
class(list(c(T)))       #a list of vectors of logical:         list
class(c(T, 3.14))       #a vector of logicals and doubles:     numeric
class(c(3.14, "foo"))   #a vector of doubles and characters:   character
class(c("foo",list(T))) #a vector of strings and lists:        list
class(list("foo",c(T))) #a list of strings and vectors:        list
class(TRUE + 5L)        #a logical plus an integer:            integer
class(c(TRUE, 5L)[1])   #The true is coerced to 1              integer
class(c(c(2i), TRUE)[1])#logical coerced to complex:           complex
class(c(NaN, 'batman')) #NaN's in a vector don't dominate:     character
class(5 && 4)           #doubles are coerced by order of &&    logical
class(8 < 'foobar')     #string and double is coerced          logical
class(list(4, T)[[1]])  #a list retains class at every index:  numeric
class(list(4, T)[[2]])  #a list retains class at every index:  logical
class(2 ** 5)           #result of exponentiation              numeric
class(0E0)              #exponential lol notation              numeric
class(0x3fade)          #hexidecimal                           numeric
class(paste(3, '3'))     #paste promotes class to string       character
class(3 + ?)           #R pukes on unicode                   error
class(iconv("a", "latin1", "UTF-8")) #UTF-8 characters         character
class(5 == 5)           #result of a comparison:               logical

Get the data storage.mode of your variable:

When an R variable is written to disk, the data layout changes again, and is called the data's storage.mode. The function storage.mode(...) reveals this low level information: see Mode, Class, and Type of R objects. You shouldn't need to worry about R's storage.mode unless you are trying to understand delays caused by round trip casts/coercions that occur when assigning and reading data to and from disk.

Demo: R/Rscript gettype(your_variable):

Run this R code then adapt it for your purposes, it'll make a pretty good guess as to what type it is.

get_type <- function(variable){ 
  sz <- as.integer(length(variable)) #length of your variable 
  tof <- typeof(variable)            #typeof your variable 
  cls <- class(variable)             #class of your variable 
  isc <- is.character(variable)      #what is.character() has to say about it.  
  d <- dim(variable)                 #dimensions of your variable 
  isv <- is.vector(variable) 
  if (is.matrix(variable)){  
    d <- dim(t(variable))             #dimensions of your matrix
  }    
  #observations ----> datatype 
  if (sz>=1 && tof == "logical" && cls == "logical" && isv == TRUE){ return("vector of logical") } 
  if (sz>=1 && tof == "integer" && cls == "integer" ){ return("vector of integer") } 
  if (sz==1 && tof == "double"  && cls == "Date" ){ return("Date") } 
  if (sz>=1 && tof == "raw"     && cls == "raw" ){ return("vector of raw") } 
  if (sz>=1 && tof == "double"  && cls == "numeric" ){ return("vector of double") } 
  if (sz>=1 && tof == "double"  && cls == "array" ){ return("vector of array of double") } 
  if (sz>=1 && tof == "character"  && cls == "array" ){ return("vector of array of character") } 
  if (sz>=0 && tof == "list"       && cls == "data.frame" ){ return("data.frame") } 
  if (sz>=1 && isc == TRUE         && isv == TRUE){ return("vector of character") } 
  if (sz>=1 && tof == "complex"    && cls == "complex" ){ return("vector of complex") } 
  if (sz==0 && tof == "NULL"       && cls == "NULL" ){ return("NULL") } 
  if (sz>=0 && tof == "integer"    && cls == "factor" ){ return("factor") } 
  if (sz>=1 && tof == "double"     && cls == "numeric" && isv == TRUE){ return("vector of double") } 
  if (sz>=1 && tof == "double"     && cls == "matrix"){ return("matrix of double") } 
  if (sz>=1 && tof == "character"  && cls == "matrix"){ return("matrix of character") } 
  if (sz>=1 && tof == "list"       && cls == "list" && isv == TRUE){ return("vector of list") } 
  if (sz>=1 && tof == "closure"    && cls == "function" && isv == FALSE){ return("closure/function") } 
  return("it's pointer to memory, bruh") 
} 
assert <- function(a, b){ 
  if (a == b){ 
    cat("P") 
  } 
  else{ 
    cat("\nFAIL!!!  Sniff test:\n") 
    sz <- as.integer(length(variable))   #length of your variable 
    tof <- typeof(variable)              #typeof your variable 
    cls <- class(variable)               #class of your variable 
    isc <- is.character(variable)        #what is.character() has to say about it. 
    d <- dim(variable)                   #dimensions of your variable 
    isv <- is.vector(variable) 
    if (is.matrix(variable)){  
      d <- dim(t(variable))                   #dimensions of your variable 
    } 
    if (!is.function(variable)){ 
      print(paste("value: '", variable, "'")) 
    } 
    print(paste("get_type said: '", a, "'")) 
    print(paste("supposed to be: '", b, "'")) 
 
    cat("\nYour pointer to memory has properties:\n")  
    print(paste("sz: '", sz, "'")) 
    print(paste("tof: '", tof, "'")) 
    print(paste("cls: '", cls, "'")) 
    print(paste("d: '", d, "'")) 
    print(paste("isc: '", isc, "'")) 
    print(paste("isv: '", isv, "'")) 
    quit() 
  } 
}
#these asserts give a sample for exercising the code. 
assert(get_type(TRUE),      "vector of logical")  #everything is a vector in R by default. 
assert(get_type(c(TRUE)),   "vector of logical")  #c() just casts to vector 
assert(get_type(c(c(TRUE))),"vector of logical")  #casting vector multiple times does nothing 
assert(get_type(!5),        "vector of logical")  #bang inflicts 'not truth-like' 
assert(get_type(1L),              "vector of integer")   #naked integers are still vectors of 1 
assert(get_type(c(1L, 2L)),       "vector of integer")   #Longs are not doubles 
assert(get_type(c(1L, c(2L, 3L))),"vector of integer")   #nested vectors of integers 
assert(get_type(c(1L, c(TRUE))),  "vector of integer")   #logicals coerced to integer 
assert(get_type(c(FALSE, c(1L))), "vector of integer")   #logicals coerced to integer 
assert(get_type("foobar"),        "vector of character")    #character here means 'string' 
assert(get_type(c(1L, "foobar")), "vector of character")    #integers are coerced to string 
assert(get_type(5),           "vector of double") 
assert(get_type(5 + 5L),      "vector of double") 
assert(get_type(Inf),         "vector of double") 
assert(get_type(c(5,6,7)),    "vector of double") 
assert(get_type(NaN),           "vector of double") 
assert(get_type(list(5)),       "vector of list")    #your list is in a vector. 
assert(get_type(list(5,6,7)),   "vector of list") 
assert(get_type(c(list(5,6,7))),"vector of list") 
assert(get_type(list(c(5,6),T)),"vector of list")    #vector of list of vector and logical 
assert(get_type(list(5,6,7)),   "vector of list") 
assert(get_type(2i),            "vector of complex") 
assert(get_type(c(2i, 3i, 4i)), "vector of complex") 
assert(get_type(c()),            "NULL") 
assert(get_type(data.frame()),   "data.frame") 
assert(get_type(data.frame(4,5)),"data.frame") 
assert(get_type(Sys.Date()),     "Date") 
assert(get_type(sapply),         "closure/function") 
assert(get_type(charToRaw("hi")),"vector of raw") 
assert(get_type(c(charToRaw("a"), charToRaw("b"))), "vector of raw") 
assert(get_type(array(4)),       "vector of array of double") 
assert(get_type(array(4,5)),     "vector of array of double") 
assert(get_type(array("hi")),    "vector of array of character") 
assert(get_type(factor()),       "factor") 
assert(get_type(factor(3.14)),   "factor") 
assert(get_type(factor(TRUE)),   "factor") 
assert(get_type(matrix(3,4,5)),  "matrix of double") 
assert(get_type(as.matrix(5)),   "matrix of double") 
assert(get_type(matrix("yatta")),"matrix of character") 

I put in a C++/Java/Python ideology here that gives me the scoop of what the memory most looks like. R triad typing system is like trying to nail spaghetti to the wall, <- and <<- will package your matrix to a list when you least suspect. As the old duck-typing saying goes: If it waddles like a duck and if it quacks like a duck and if it has feathers, then it's a duck.

How to perform string interpolation in TypeScript?

Just use special `

var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;

You can see more examples here.

How to convert webpage into PDF by using Python

WeasyPrint

pip install weasyprint  # No longer supports Python 2.x.

python
>>> import weasyprint
>>> pdf = weasyprint.HTML('http://www.google.com').write_pdf()
>>> len(pdf)
92059
>>> open('google.pdf', 'wb').write(pdf)

How to compile and run C in sublime text 3?

For a sublime build system implementing the Run menu command :

  • Go to Tools->Build System->New Build System...

Or

  • Create a file ~/.config/sublime-text-3/Packages/User/GCC.sublime-build

And insert this:

{
"shell_cmd" : "gcc $file_name -o ${file_base_name}",
"working_dir" : "$file_path",
"variants":
  [
    {
      "name": "Run",
      "shell_cmd": "gcc $file_name -o ${file_base_name} && ${file_path}/${file_base_name}"
    }
  ]
}

*This example uses the GCC compiler. Feel free to replace gcc with the compiler of your choice.

How to check all versions of python installed on osx and centos

compgen -c python | grep -P '^python\d'

This lists some other python things too, But hey, You can identify all python versions among them.

Why is my Spring @Autowired field null?

Your problem is new (object creation in java style)

MileageFeeCalculator calc = new MileageFeeCalculator();

With annotation @Service, @Component, @Configuration beans are created in the
application context of Spring when server is started. But when we create objects using new operator the object is not registered in application context which is already created. For Example Employee.java class i have used.

Check this out:

public class ConfiguredTenantScopedBeanProcessor implements BeanFactoryPostProcessor {

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String name = "tenant";
    System.out.println("Bean factory post processor is initialized"); 
    beanFactory.registerScope("employee", new Employee());

    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
            "BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
        if (name.equals(definition.getScope())) {
            BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, true);
            registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
        }
    }
}

}

How do I put the image on the right side of the text in a UIButton?

I ended up creating a custom button, which allows setting the Image from Inspector. Below is my code:

import UIKit

@IBDesignable
class CustomButton: UIButton {

    @IBInspectable var leftImage: UIImage? = nil
    @IBInspectable var gapPadding: CGFloat = 0

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }

    func setup() {

        if(leftImage != nil) {
            let imageView = UIImageView(image: leftImage)
            imageView.translatesAutoresizingMaskIntoConstraints = false

            addSubview(imageView)

            let length = CGFloat(16)
            titleEdgeInsets.left += length

            NSLayoutConstraint.activate([
                imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: gapPadding),
                imageView.centerYAnchor.constraint(equalTo: self.titleLabel!.centerYAnchor, constant: 0),
                imageView.widthAnchor.constraint(equalToConstant: length),
                imageView.heightAnchor.constraint(equalToConstant: length)
            ])
        }
    }
}

You can adjust the value of Gap Padding from Inspector to adjust the spacing between text and the image.

PS: Used some code portion from @Mark Hennings answer

How can I make git accept a self signed certificate?

You can set GIT_SSL_NO_VERIFY to true:

GIT_SSL_NO_VERIFY=true git clone https://example.com/path/to/git

or alternatively configure Git not to verify the connection on the command line:

git -c http.sslVerify=false clone https://example.com/path/to/git

Note that if you don't verify SSL/TLS certificates, then you are susceptible to MitM attacks.

Can a PDF file's print dialog be opened with Javascript?

Just figured out how to do this within the PDF itself - if you have acrobat pro, go to your pages tab, right click on the thumbnail for the first page, and click page properties. Click on the actions tab at the top of the window and under select trigger choose page open. Under select action choose "run a javascript". Then in the javascript window, type this:

this.print({bUI: false, bSilent: true, bShrinkToFit: true});

This will print your document without a dialogue to the default printer on your machine. If you want the print dialog, just change bUI to true, bSilent to false, and optionally, remove the shrink to fit parameter.

Auto-printing PDF!

TypeScript Objects as Dictionary types as in C#

In addition to using an map-like object, there has been an actual Map object for some time now, which is available in TypeScript when compiling to ES6, or when using a polyfill with the ES6 type-definitions:

let people = new Map<string, Person>();

It supports the same functionality as Object, and more, with a slightly different syntax:

// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });

// Checking for the presence of a key:
people.has("John"); // true

// Retrieving a value by a key:
people.get("John").lastName; // "Doe"

// Deleting an item by a key:
people.delete("John");

This alone has several advantages over using a map-like object, such as:

  • Support for non-string based keys, e.g. numbers or objects, neither of which are supported by Object (no, Object does not support numbers, it converts them to strings)
  • Less room for errors when not using --noImplicitAny, as a Map always has a key type and a value type, whereas an object might not have an index-signature
  • The functionality of adding/removing items (key-value pairs) is optimized for the task, unlike creating properties on an Object

Additionally, a Map object provides a more powerful and elegant API for common tasks, most of which are not available through simple Objects without hacking together helper functions (although some of these require a full ES6 iterator/iterable polyfill for ES5 targets or below):

// Iterate over Map entries:
people.forEach((person, key) => ...);

// Clear the Map:
people.clear();

// Get Map size:
people.size;

// Extract keys into array (in insertion order):
let keys = Array.from(people.keys());

// Extract values into array (in insertion order):
let values = Array.from(people.values());

What does %~d0 mean in a Windows batch file?

%~d0 gives you the drive letter of argument 0 (the script name), %~p0 the path.

Using a list as a data source for DataGridView

Set the DataGridView property

    gridView1.AutoGenerateColumns = true;

And make sure the list of objects your are binding, those object properties should be public.

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

Create MSI or setup project with Visual Studio 2012

I think that Deploying an Office Solution by Using ClickOnce (MSDN) can be useful.

After creating an Outlook plugin for Office 2010 the problem was to install it on the customer's computer, without using ISLE or other complex tools (or expensive).

The solution was to use the publish instrument of the Visual Studio project, as described in the link. Just two things to be done before the setup will work:

Show Current Location and Update Location in MKMapView in Swift

For swift 3 and XCode 8 I find this answer:

  • First, you need set privacy into info.plist. Insert string NSLocationWhenInUseUsageDescription with your description why you want get user location. For example, set string "For map in application".

  • Second, use this code example

    @IBOutlet weak var mapView: MKMapView!
    
    private var locationManager: CLLocationManager!
    private var currentLocation: CLLocation?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        mapView.delegate = self
    
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    
        // Check for Location Services
    
        if CLLocationManager.locationServicesEnabled() {
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        }
    }
    
    // MARK - CLLocationManagerDelegate
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        defer { currentLocation = locations.last }
    
        if currentLocation == nil {
            // Zoom to user location
            if let userLocation = locations.last {
                let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
                mapView.setRegion(viewRegion, animated: false)
            }
        }
    }
    
  • Third, set User Location flag in storyboard for mapView.