Programs & Examples On #Getter

A getter is a public accessor method, used in object-oriented programming, which returns the value associated with a private member of a class.

Why use getters and setters/accessors?

Getters and setters coming from data hiding. Data Hiding means We are hiding data from outsiders or outside person/thing cannot access our data.This is a useful feature in OOP.

As a example:

If you create a public variable, you can access that variable and change value in anywhere(any class). But if you create as private that variable cannot see/access in any class except declared class.

public and private are access modifiers.

So how can we access that variable outside:

This is the place getters and setters coming from. You can declare variable as private then you can implement getter and setter for that variable.

Example(Java):

private String name;

public String getName(){
   return this.name;
}

public void setName(String name){
   this.name= name;
}

Advantage:

When anyone want to access or change/set value to balance variable, he/she must have permision.

//assume we have person1 object
//to give permission to check balance
person1.getName()

//to give permission to set balance
person1.setName()

You can set value in constructor also but when later on when you want to update/change value, you have to implement setter method.

Set and Get Methods in java?

The benefits of get() set() methods are as follows ..

  1. You can serialize you object easily.
  2. You can create a persistent object from the containing class.
  3. You can convert the properties to JSON easily.
  4. In the DAO layer (Frameworks like Hibernate) you can directly save the object to DB.
  5. Easy understanding of object oriented concept.
  6. Needs in all design pattern except possibly in single tone pattern.
  7. Security for properties protecting direct access.
  8. Polymorphism, Encapsulation can be easily understood and implemented by this type of class.

Example:

private String personName;
private int personId;

    public void setPersonName(String name) throws Exception{
    if(!(name.equals("")||name=="")){
      this.personName = name;
    }
  }
  public String getPersonName(){
    return this.personName;
  }
  public void setPersonId(int id) throws Exception{
    this.personId = id;
  }
  public int getPersonId(){
    return this.personId;
  }

View's getWidth() and getHeight() returns 0

I used this solution, which I think is better than onWindowFocusChanged(). If you open a DialogFragment, then rotate the phone, onWindowFocusChanged will be called only when the user closes the dialog):

    yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // Ensure you call it only once :
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            // Here you can get the size :)
        }
    });

Edit : as removeGlobalOnLayoutListener is deprecated, you should now do :

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {

    // Ensure you call it only once :
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
    else {
        yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }

    // Here you can get the size :)
}

How can we generate getters and setters in Visual Studio?

In addition to the 'prop' snippet and auto-properties, there is a refactor option to let you select an existing field and expose it via a property (right click on the field → RefactorEncapsulate Field...).

Also, if you don't like the 'prop' implementation, you can create your own snippets. Additionally, a third-party refactoring tool like ReSharper will give you even more features and make it easier to create more advanced snippets. I'd recommend ReSharper if you can afford it.

How do getters and setters work?

class Clock {  
        String time;  

        void setTime (String t) {  
           time = t;  
        }  

        String getTime() {  
           return time;  
        }  
}  


class ClockTestDrive {  
   public static void main (String [] args) {  
   Clock c = new Clock;  

   c.setTime("12345")  
   String tod = c.getTime();  
   System.out.println(time: " + tod);  
 }
}  

When you run the program, program starts in mains,

  1. object c is created
  2. function setTime() is called by the object c
  3. the variable time is set to the value passed by
  4. function getTime() is called by object c
  5. the time is returned
  6. It will passe to tod and tod get printed out

Getters \ setters for dummies

Sorry to resurrect an old question, but I thought I might contribute a couple of very basic examples and for-dummies explanations. None of the other answers posted thusfar illustrate syntax like the MDN guide's first example, which is about as basic as one can get.

Getter:

var settings = {
    firstname: 'John',
    lastname: 'Smith',
    get fullname() { return this.firstname + ' ' + this.lastname; }
};

console.log(settings.fullname);

... will log John Smith, of course. A getter behaves like a variable object property, but offers the flexibility of a function to calculate its returned value on the fly. It's basically a fancy way to create a function that doesn't require () when calling.

Setter:

var address = {
    set raw(what) {
        var loc = what.split(/\s*;\s*/),
        area = loc[1].split(/,?\s+(\w{2})\s+(?=\d{5})/);

        this.street = loc[0];
        this.city = area[0];
        this.state = area[1];
        this.zip = area[2];
    }
};

address.raw = '123 Lexington Ave; New York NY  10001';
console.log(address.city);

... will log New York to the console. Like getters, setters are called with the same syntax as setting an object property's value, but are yet another fancy way to call a function without ().

See this jsfiddle for a more thorough, perhaps more practical example. Passing values into the object's setter triggers the creation or population of other object items. Specifically, in the jsfiddle example, passing an array of numbers prompts the setter to calculate mean, median, mode, and range; then sets object properties for each result.

What is the best way to give a C# auto-property an initial value?

In Version of C# (6.0) & greater, you can do :

For Readonly properties

public int ReadOnlyProp => 2;

For both Writable & Readable properties

public string PropTest { get; set; } = "test";

In current Version of C# (7.0), you can do : (The snippet rather displays how you can use expression bodied get/set accessors to make is more compact when using with backing fields)

private string label = "Default Value";

// Expression-bodied get / set accessors.
public string Label
{
   get => label;
   set => this.label = value; 
 }

Looking for a short & simple example of getters/setters in C#

In C#, Properties represent your Getters and Setters.

Here's an example:

public class PropertyExample
{
    private int myIntField = 0;

    public int MyInt
    {
        // This is your getter.
        // it uses the accessibility of the property (public)
        get
        {
            return myIntField;
        }
        // this is your setter
        // Note: you can specify different accessibility
        // for your getter and setter.
        protected set
        {
            // You can put logic into your getters and setters
            // since they actually map to functions behind the scenes
            DoSomeValidation(value)
            {
                // The input of the setter is always called "value"
                // and is of the same type as your property definition
                myIntField = value;
            }
        }
    }
}

You would access this property just like a field. For example:

PropertyExample example = new PropertyExample();
example.MyInt = 4; // sets myIntField to 4
Console.WriteLine( example.MyInt ); // prints 4

A few other things to note:

  1. You don't have to specifiy both a getter and a setter, you can omit either one.
  2. Properties are just "syntactic sugar" for your traditional getter and setter. The compiler will actually build get_ and set_ functions behind the scenes (in the compiled IL) and map all references to your property to those functions.

Best way of invoking getter by reflection

You can invoke reflections and also, set order of sequence for getter for values through annotations

public class Student {

    private String grade;

    private String name;

    private String id;

    private String gender;

    private Method[] methods;

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Order {
        int value();
    }

    /**
     * Sort methods as per Order Annotations
     * 
     * @return
     */
    private void sortMethods() {

        methods = Student.class.getMethods();

        Arrays.sort(methods, new Comparator<Method>() {
            public int compare(Method o1, Method o2) {
                Order or1 = o1.getAnnotation(Order.class);
                Order or2 = o2.getAnnotation(Order.class);
                if (or1 != null && or2 != null) {
                    return or1.value() - or2.value();
                }
                else if (or1 != null && or2 == null) {
                    return -1;
                }
                else if (or1 == null && or2 != null) {
                    return 1;
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    /**
     * Read Elements
     * 
     * @return
     */
    public void readElements() {
        int pos = 0;
        /**
         * Sort Methods
         */
        if (methods == null) {
            sortMethods();
        }
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
                pos++;
                String value = "";
                try {
                    value = (String) method.invoke(this);
                }
                catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                System.out.println(name + " Pos: " + pos + " Value: " + value);
            }
        }
    }

    // /////////////////////// Getter and Setter Methods

    /**
     * @param grade
     * @param name
     * @param id
     * @param gender
     */
    public Student(String grade, String name, String id, String gender) {
        super();
        this.grade = grade;
        this.name = name;
        this.id = id;
        this.gender = gender;
    }

    /**
     * @return the grade
     */
    @Order(value = 4)
    public String getGrade() {
        return grade;
    }

    /**
     * @param grade the grade to set
     */
    public void setGrade(String grade) {
        this.grade = grade;
    }

    /**
     * @return the name
     */
    @Order(value = 2)
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the id
     */
    @Order(value = 1)
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the gender
     */
    @Order(value = 3)
    public String getGender() {
        return gender;
    }

    /**
     * @param gender the gender to set
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    /**
     * Main
     * 
     * @param args
     * @throws IOException
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Student student = new Student("A", "Anand", "001", "Male");
        student.readElements();
    }
  }

Output when sorted

getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A

2D array values C++

The proper way to initialize a multidimensional array in C or C++ is

int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};

You can use this same trick to initialize even higher-dimensional arrays if you want.

Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!

Difference between ref and out parameters in .NET

ref and out both allow the called method to modify a parameter. The difference between them is what happens before you make the call.

  • ref means that the parameter has a value on it before going into the function. The called function can read and or change the value any time. The parameter goes in, then comes out

  • out means that the parameter has no official value before going into the function. The called function must initialize it. The parameter only goes out

Here's my favorite way to look at it: ref is to pass variables by reference. out is to declare a secondary return value for the function. It's like if you could write this:

// This is not C#
public (bool, string) GetWebThing(string name, ref Buffer paramBuffer);

// This is C#
public bool GetWebThing(string name, ref Buffer paramBuffer, out string actualUrl);

Here's a more detailed list of the effects of each alternative:

Before calling the method:

ref: The caller must set the value of the parameter before passing it to the called method.

out: The caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded.

During the call:

ref: The called method can read the argument at any time.

out: The called method must initialize the parameter before reading it.

Remoted calls:

ref: The current value is marshalled to the remote call. Extra performance cost.

out: Nothing is passed to the remote call. Faster.

Technically speaking, you could use always ref in place of out, but out allows you to be more precise about the meaning of the argument, and sometimes it can be a lot more efficient.

Rendering React Components from Array of Objects

this.data presumably contains all the data, so you would need to do something like this:

var stations = [];
var stationData = this.data.stations;

for (var i = 0; i < stationData.length; i++) {
    stations.push(
        <div key={stationData[i].call} className="station">
            Call: {stationData[i].call}, Freq: {stationData[i].frequency}
        </div>
    )
}

render() {
  return (
    <div className="stations">{stations}</div>
  )
}

Or you can use map and arrow functions if you're using ES6:

const stations = this.data.stations.map(station =>
    <div key={station.call} className="station">
      Call: {station.call}, Freq: {station.frequency}
    </div>
);

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

$('input').focus(function () {
    var self = $(this);
    setTimeout(function () {
        self.select();
    }, 1);        
});

Edit: Per @DavidG's request, I can't provide details because I'm not sure why this works, but I believe it has something to do with the focus event propagating up or down or whatever it does and the input element getting the notification it's received focus. Setting the timeout gives the element a moment to realize it's done so.

How do I "break" out of an if statement?

I don't know your test conditions, but a good old switch could work

switch(colour)
{
  case red:
  {
    switch(car)
    { 
      case hyundai: 
      {
        break;
      }
      :
    }
    break;
  }
  :
}

How do I trim whitespace from a string?

This can also be done with a regular expression

import re

input  = " Hello "
output = re.sub(r'^\s+|\s+$', '', input)
# output = 'Hello'

Textarea that can do syntax highlighting on the fly?

I would recommend EditArea for live editing of a syntax hightlighted textarea.

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and uncheck the checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

Redirecting a request using servlets and the "setHeader" method not working

Another way of doing this if you want to redirect to any url source after the specified point of time

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

public class MyServlet extends HttpServlet


{

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException

{

response.setContentType("text/html");

PrintWriter pw=response.getWriter();

pw.println("<b><centre>Redirecting to Google<br>");


response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url  after 5 seconds


pw.close();
}

}

Javascript / Chrome - How to copy an object from the webkit inspector as code

  1. Right-click an object in Chrome's console and select Store as Global Variable from the context menu. It will return something like temp1 as the variable name.

  2. Chrome also has a copy() method, so copy(temp1) in the console should copy that object to your clipboard.

Copy Javascript Object in Chrome DevTools

Note on Recursive Objects: If you're trying to copy a recursive object, you will get [object Object]. The way out is to copy(JSON.stringify(temp1)) , the object will be fully copied to your clipboard as a valid JSON, so you'd be able to format it as you wish, using one of many resources.

Deny access to one specific folder in .htaccess

You can also put this IndexIgnore * at your root .htaccess file to disable file listing of all of your website directories including sub-dir

Row numbers in query result using Microsoft Access

MS-Access doesn't support ROW_NUMBER(). Use TOP 1:

SELECT TOP 1 *
FROM [MyTable]
ORDER BY [MyIdentityCOlumn]

If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this:

SELECT TOP 1 *
FROM (
  SELECT TOP 15 *
  FROM [MyTable]
  ORDER BY [MyIdentityColumn] ) t
ORDER BY [MyIdentityColumn] DESC

Is it possible to sort a ES6 map object?

The snippet below sorts given map by its keys and maps the keys to key-value objects again. I used localeCompare function since my map was string->string object map.

var hash = {'x': 'xx', 't': 'tt', 'y': 'yy'};
Object.keys(hash).sort((a, b) => a.localeCompare(b)).map(function (i) {
            var o = {};
            o[i] = hash[i];
            return o;
        });

result: [{t:'tt'}, {x:'xx'}, {y: 'yy'}];

Copying PostgreSQL database to another server

Here is an example using pg_basebackup

I chose to go this route because it backs up the entire database cluster (users, databases, etc.).

I'm posting this as a solution on here because it details every step I had to take, feel free to add recommendations or improvements after reading other answers on here and doing some more research.

For Postgres 12 and Ubuntu 18.04 I had to do these actions:


On the server that is currently running the database:

Update pg_hba.conf, for me located at /etc/postgresql/12/main/pg_hba.conf

Add the following line (substitute 192.168.0.100 with the IP address of the server you want to copy the database to).

host  replication  postgres  192.168.0.100/32  trust

Update postgresql.conf, for me located at /etc/postgresql/12/main/postgresql.conf. Add the following line:

listen_addresses = '*'

Restart postgres:

sudo service postgresql restart


On the host you want to copy the database cluster to:

sudo service postgresql stop

sudo su root

rm -rf /var/lib/postgresql/12/main/*

exit

sudo -u postgres pg_basebackup -h 192.168.0.101 -U postgres -D /var/lib/postgresql/12/main/

sudo service postgresql start

Big picture - stop the service, delete everything in the data directory (mine is in /var/lib/postgreql/12). The permissions on this directory are drwx------ with user and group postgres. I could only do this as root, not even with sudo -u postgres. I'm unsure why. Ensure you are doing this on the new server you want to copy the database to! You are deleting the entire database cluster.

Make sure to change the IP address from 192.168.0.101 to the IP address you are copying the database from. Copy the data from the original server with pg_basebackup. Start the service.

Update pg_hba.conf and postgresql.conf to match the original server configuration - before you made any changes adding the replication line and the listen_addresses line (in my care I had to add the ability to log-in locally via md5 to pg_hba.conf).

Note there are considerations for max_wal_senders and wal_level that can be found in the documentation. I did not have to do anything with this.

Placeholder in IE9

to make it work in IE-9 use below .it works for me

JQuery need to include:

jQuery(function() {
   jQuery.support.placeholder = false;
   webkit_type = document.createElement('input');
   if('placeholder' in webkit_type) jQuery.support.placeholder = true;});
   $(function() {

     if(!$.support.placeholder) {

       var active = document.activeElement;

       $(':text, textarea, :password').focus(function () {

       if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&         ($(this).attr('placeholder') != '') && $(this).val() == $(this).attr('placeholder')) {
          $(this).val('').removeClass('hasPlaceholder');
        }
      }).blur(function () {
if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&  ($(this).attr('placeholder') != '') && ($(this).val() == '' || $(this).val() ==   $(this).attr('placeholder'))) {
     $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});

$(':text, textarea, :password').blur();
$(active).focus();
$('form').submit(function () {
     $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});

CSS Style need to include:

.hasPlaceholder {color: #aaa;}

Prevent typing non-numeric in input type number

I just had the same problem and discovered an alternative solution using the validation API - works without black magic in all major browsers (Chrome, Firefox, Safari) except IE. This solution simply prevents users from entering invalid values. I also included a fallback for IE, which is not nice but works at least.

Context: onInput function is called on input events, setInputValue is used to set the value of the input element, previousInputValue contains the last valid input value (updated in setInputValue calls).

    function onInput (event) {
        const inputValue = event.target.value;

        // badInput supported on validation api (except IE)
        // in IE it will be undefined, so we need strict value check
        const badInput = event.target.validity.badInput;

        // simply prevent modifying the value
        if (badInput === true) {
        // it's still possible to enter invalid values in an empty input, so we'll need this trick to prevent that
            if (previousInputValue === '') {
                setInputValue(' ');
                setTimeout(() => {
                    setInputValue('');
                }, 1);
            }
            return;
        }

        if (badInput === false) {
            setInputValue(inputValue);
            return;
        }

        // fallback case for IE and other abominations

        // remove everything from the string expect numbers, point and comma
        // replace comma with points (parseFloat works only with points)
        let stringVal = String(inputValue)
            .replace(/([^0-9.,])/g, '')
            .replace(/,/g, '.');

        // remove all but first point
        const pointIndex = stringVal.indexOf('.');
        if (pointIndex !== -1) {
            const pointAndBefore = stringVal.substring(0, pointIndex + 1);
            const afterPoint = stringVal.substring(pointIndex + 1);

            // removing all points after the first
            stringVal = `${pointAndBefore}${afterPoint.replace(/\./g, '')}`;
        }

        const float = parseFloat(stringVal);
        if (isNaN(float)) {
            // fallback to emptying the input if anything goes south
            setInputValue('');
            return;
        }
        setInputValue(stringVal);
}

Setting focus to a textbox control

create a textbox:

 <TextBox Name="tb">
 ..hello..
</TextBox>

focus() ---> it is used to set input focus to the textbox control

tb.focus()

deleting folder from java

I wrote a method for this sometime back. It deletes the specified directory and returns true if the directory deletion was successful.

/**
 * Delets a dir recursively deleting anything inside it.
 * @param dir The dir to delete
 * @return true if the dir was successfully deleted
 */
public static boolean deleteDirectory(File dir) {
    if(! dir.exists() || !dir.isDirectory())    {
        return false;
    }

    String[] files = dir.list();
    for(int i = 0, len = files.length; i < len; i++)    {
        File f = new File(dir, files[i]);
        if(f.isDirectory()) {
            deleteDirectory(f);
        }else   {
            f.delete();
        }
    }
    return dir.delete();
}

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.Append(......);

    StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
    sw.Write(sb.ToString());
    sw.Close();

Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.

How to convert Java String to JSON Object

Converting the String to JsonNode using ObjectMapper object :

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);

Grep only the first match and stop

A single liner, using find:

find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit

Convert a video to MP4 (H.264/AAC) with ffmpeg

You're trying to convert a (rather rare) .flv file that (already) contains H.264 video and AAC audio.

Formatting your console's output as FFmpeg brings out these details.

 Input #0, flv, from 'video.flv':
   Duration: 00:05:01.20, start: 0.000000, bitrate: 66 kb/s
    Stream #0.0: Video: h264, yuv420p, 320x240 [PAR 1:1 DAR 4:3], 66 kb/s, 29.92 tbr, 1k tbn, 2k tbc 
    Stream #0.1: Audio: aac, 22050 Hz, stereo, s16

The original flv is converted to an .mp4 file with H.264 video and AAC audio (just like the original .flv):

Output #0, mp4, to 'video.mp4': 
    Stream #0.0: Video: mpeg4, yuv420p, 320x240 [PAR 1:1 DAR 4:3], q=2-31, 200 kb/s, 90k tbn, 29.92 tbc 
    Stream #0.1: Audio: 0x0000, 22050 Hz, stereo, s16, 64 kb/s

Because the audio and video data in the .flv are already in the format/codecs you need for the .mp4, you can just copy everything to the new .mp4 container. This process will be massively faster than decoding and reencoding everything:

ffmpeg -i video.flv -vcodec copy -acodec copy video.mp4

or more simply:

ffmpeg -i video.flv -codec copy video.mp4

The real error you're getting is:

Unsupported codec for output stream #0.1

Which means FFmpeg can't convert audio (stream #0.1) to AAC.

You can skip the error by:

  • copying the audio data since it's already AAC encoded (use the copy command above)

or you can solve the error by:

For more details you should also read Converting FLV to MP4 With FFmpeg The Ultimate Guide

Installing Bootstrap 3 on Rails App

I use https://github.com/yabawock/bootstrap-sass-rails

Which is pretty much straight forward install, fast gem updates and followups and quick fixes in case is needed.

How to include a sub-view in Blade templates?

As of Laravel 5.6, if you have this kind of structure and you want to include another blade file inside a subfolder,

|--- views

|------- parentFolder (Folder)

|---------- name.blade.php (Blade File)

|---------- childFolder (Folder)

|-------------- mypage.blade.php (Blade File)

name.blade.php

  <html>
      @include('parentFolder.childFolder.mypage')
  </html>

Applying function with multiple arguments to create a new pandas column

You can go with @greenAfrican example, if it's possible for you to rewrite your function. But if you don't want to rewrite your function, you can wrap it into anonymous function inside apply, like this:

>>> def fxy(x, y):
...     return x * y

>>> df['newcolumn'] = df.apply(lambda x: fxy(x['A'], x['B']), axis=1)
>>> df
    A   B  newcolumn
0  10  20        200
1  20  30        600
2  30  10        300

Set value of hidden field in a form using jQuery's ".val()" doesn't work

I was having the same issue, and I found out what was wrong. I had the HTML defined as

<form action="url" method="post">
    <input type="hidden" id="email" />
<form>
<script>
    function onsomeevent()
    {
       $("#email").val("[email protected]");
    }
</script>

Reading the form values on server always resulted in email as empty. After scratching my head (and numerous search), I realized the mistake was not defining the form/input correctly. On modifing the input (as shown next), it worked like a charm

<input type="hidden" id="email" name="email" />

Adding to this thread in case others have the same issue.

How to check if variable is array?... or something array-like

PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    }
}

This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

You can also use the function is_array($var) to check if the passed variable is an array:

<?php
    var_dump( is_array(array()) ); // true
    var_dump( is_array(array(1, 2, 3)) ); // true
    var_dump( is_array($_SERVER) ); // true
?>

Read more in How to check if a variable is an array in PHP?

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

Mock functions in Go

I would do something like,

Main

var getPage = get_page
func get_page (...

func downloader() {
    dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
    content := getPage(BASE_URL)
    links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
    matches := links_regexp.FindAllStringSubmatch(content, -1)
    for _, match := range matches{
        go serie_dl(match[1], match[2])
    }
}

Test

func TestDownloader (t *testing.T) {
    origGetPage := getPage
    getPage = mock_get_page
    defer func() {getPage = origGatePage}()
    // The rest to be written
}

// define mock_get_page and rest of the codes
func mock_get_page (....

And I would avoid _ in golang. Better use camelCase

IFrame: This content cannot be displayed in a frame

Use target="_top" attribute in anchor tag that will really work.

Multipart File Upload Using Spring Rest Template + Spring Web MVC

A correct file upload would like this:

HTTP header:

Content-Type: multipart/form-data; boundary=ABCDEFGHIJKLMNOPQ

Http body:

--ABCDEFGHIJKLMNOPQ

Content-Disposition: form-data; name="file"; filename="my.txt"

Content-Type: application/octet-stream

Content-Length: ...

<...file data in base 64...>

--ABCDEFGHIJKLMNOPQ--

and code is like this:

public void uploadFile(File file) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://localhost:8080/file/user/upload";
            HttpMethod requestMethod = HttpMethod.POST;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);


            MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
            ContentDisposition contentDisposition = ContentDisposition
                    .builder("form-data")
                    .name("file")
                    .filename(file.getName())
                    .build();

            fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
            HttpEntity<byte[]> fileEntity = new HttpEntity<>(Files.readAllBytes(file.toPath()), fileMap);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileEntity);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            ResponseEntity<String> response = restTemplate.exchange(url, requestMethod, requestEntity, String.class);

            System.out.println("file upload status code: " + response.getStatusCode());

        } catch (IOException e) {
            e.printStackTrace();
        }

}

HTML form with multiple "actions"

the best way (for me) to make it it's the next infrastructure:

<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>

with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.

Fixing npm path in Windows 8 and 10

This worked for me: 1. npm root -g (to see the current npm is installed) 2. npm config set prefix (to change the path)

ASP.NET Core - Swashbuckle not creating swagger.json file

Make sure you have all the required dependencies, go to the url xxx/swagger/v1/swagger.json you might find that you're missing one or more dependencies.

enter image description here

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

What is the list of valid @SuppressWarnings warning names in Java?

All values are permitted (unrecognized ones are ignored). The list of recognized ones is compiler specific.

In The Java Tutorials unchecked and deprecation are listed as the two warnings required by The Java Language Specification, therefore, they should be valid with all compilers:

Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked.

The specific sections inside The Java Language Specification where they are defined is not consistent across versions. In the Java SE 8 Specification unchecked and deprecation are listed as compiler warnings in sections 9.6.4.5. @SuppressWarnings and 9.6.4.6 @Deprecated, respectively.

For Sun's compiler, running javac -X gives a list of all values recognized by that version. For 1.5.0_17, the list appears to be:

  • all
  • deprecation
  • unchecked
  • fallthrough
  • path
  • serial
  • finally

regex error - nothing to repeat

regular expression normally uses * and + in theory of language. I encounter the same bug while executing the line code

re.split("*",text)

to solve it, it needs to include \ before * and +

re.split("\*",text)

Get the key corresponding to the minimum value within a dictionary

For the case where you have multiple minimal keys and want to keep it simple

def minimums(some_dict):
    positions = [] # output variable
    min_value = float("inf")
    for k, v in some_dict.items():
        if v == min_value:
            positions.append(k)
        if v < min_value:
            min_value = v
            positions = [] # output variable
            positions.append(k)

    return positions

minimums({'a':1, 'b':2, 'c':-1, 'd':0, 'e':-1})

['e', 'c']

How to set the height and the width of a textfield in Java?

xyz.setColumns() method is control the width of TextField.

import java.awt.*;
import javax.swing.*;



class miniproj extends JFrame {

  public static void main(String[] args)
  {
    JFrame frame=new JFrame();
    JPanel panel=new JPanel();
    frame.setSize(400,400);
    frame.setTitle("Registration");


    JLabel lablename=new JLabel("Enter your name");
    TextField tname=new TextField(30);
    tname.setColumns(45);

    JLabel lableemail=new JLabel("Enter your Email");
    TextField email=new TextField(30);
    email.setColumns(45);
    JLabel lableaddress=new JLabel("Enter your address");
    TextField address=new TextField(30);
    address.setColumns(45);
    address.setFont(Font.getFont(Font.SERIF));
    JLabel lablepass=new JLabel("Enter your password");
    TextField pass=new TextField(30);
    pass.setColumns(45);

    JButton login=new JButton();
    JButton create=new JButton();
    login.setPreferredSize(new Dimension(90,30));
    login.setText("Login");
    create.setPreferredSize(new Dimension(90,30));
    create.setText("Create");



    panel.add(lablename);
    panel.add(tname);
    panel.add(lableemail);
    panel.add(email);
    panel.add(lableaddress);
    panel.add(address);
    panel.add(lablepass);
    panel.add(pass);
    panel.add(create);
    panel.add(login);



    frame.add(panel);
    frame.setVisible(true);
  }
}

enter image description here

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

After build. Refresh project and if still persist just right click Problems tab in eclipse and choose delete all.

It often happens if you do maven install and eclipse properties files do not get updated properly. Even though your project does not have any errors. Hopefully!

How do I convert an interval into a number of hours with postgres?

         select date 'now()' - date '1955-12-15';

Here is the simple query which calculates total no of days.

How can I mock requests and the response?

this is how you mock requests.post, change it to your http method

@patch.object(requests, 'post')
def your_test_method(self, mockpost):
    mockresponse = Mock()
    mockpost.return_value = mockresponse
    mockresponse.text = 'mock return'

    #call your target method now

Running Bash commands in Python

You can use subprocess, but I always felt that it was not a 'Pythonic' way of doing it. So I created Sultan (shameless plug) that makes it easy to run command line functions.

https://github.com/aeroxis/sultan

Get file content from URL?

Depending on your PHP configuration, this may be a easy as using:

$jsonData = json_decode(file_get_contents('https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json'));

However, if allow_url_fopen isn't enabled on your system, you could read the data via CURL as follows:

<?php
    $curlSession = curl_init();
    curl_setopt($curlSession, CURLOPT_URL, 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json');
    curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);

    $jsonData = json_decode(curl_exec($curlSession));
    curl_close($curlSession);
?>

Incidentally, if you just want the raw JSON data, then simply remove the json_decode.

<DIV> inside link (<a href="">) tag

This is a classic case of divitis - you don't need a div to be clickable, just give the <a> tag a class. Then edit the CSS of the class to display:block, and define a height and width like a lot of other answers have mentioned.

The <a> tag works perfectly well on its own, so you don't need an extra level of mark-up on the page.

"Strict Standards: Only variables should be passed by reference" error

array_shift the only parameter is an array passed by reference. The return value of explode(".", $value) does not have any reference. Hence the error.

You should store the return value to a variable first.

    $arr = explode(".", $value);
    $extension = strtolower(array_pop($arr));   
    $fileName = array_shift($arr);

From PHP.net

The following things can be passed by reference:

- Variables, i.e. foo($a)
- New statements, i.e. foo(new foobar())
- [References returned from functions][2]

No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

Maven: best way of linking custom external JAR to my project?

update We have since just installed our own Nexus server, much easier and cleaner.

At our company we had some jars that we some jars that were common but were not hosted in any maven repositories, nor did we want to have them in local storage. We created a very simple mvn (public) repo on Github (but you can host it on any server or locally):
note that this is only ideal for managing a few rarely chaning jar files

  1. Create repo on GitHub:
    https://github.com/<user_name>/mvn-repo/

  2. Add Repository in pom.xml
    (Make note that the full path raw file will be a bit different than the repo name)

    <repository>
        <id>project-common</id>
        <name>Project Common</name>
        <url>https://github.com/<user_name>/mvn-repo/raw/master/</url>
    </repository>
    
  3. Add dependency to host (Github or private server)
    a. All you need to know is that files are stored in the pattern mentioned by @glitch
    /groupId/artifactId/version/artifactId-version.jar
    b. On your host create the folders to match this pattern.
    i.e if you have a jar file named service-sdk-0.0.1.jar, create the folder service-sdk/service-sdk/0.0.1/ and place the jar file service-sdk-0.0.1.jar into it.
    c. Test it by trying to download the jar from a browser (in our case: https://github.com/<user_name>/mvn-repo/raw/master/service-sdk/service-sdk/0.0.1/service-sdk-0.0.1.jar

  4. Add dependency to your pom.xml file:

    <dependency>
        <groupId>service-sdk</groupId>
        <artifactId>service-sdk</artifactId>
        <version>0.0.1</version>
    </dependency>
    
  5. Enjoy

How can I create a marquee effect?

With a small change of the markup, here's my approach (I've just inserted a span inside the paragraph):

_x000D_
_x000D_
.marquee {
  width: 450px;
  margin: 0 auto;
  overflow: hidden;
  box-sizing: border-box;
}

.marquee span {
  display: inline-block;
  width: max-content;

  padding-left: 100%;
  /* show the marquee just outside the paragraph */
  will-change: transform;
  animation: marquee 15s linear infinite;
}

.marquee span:hover {
  animation-play-state: paused
}


@keyframes marquee {
  0% { transform: translate(0, 0); }
  100% { transform: translate(-100%, 0); }
}


/* Respect user preferences about animations */

@media (prefers-reduced-motion: reduce) {
  .marquee span {
    animation-iteration-count: 1;
    animation-duration: 0.01; 
    /* instead of animation: none, so an animationend event is 
     * still available, if previously attached.
     */
    width: auto;
    padding-left: 0;
  }
}
_x000D_
<p class="marquee">
   <span>
       When I had journeyed half of our life's way, I found myself
       within a shadowed forest, for I had lost the path that 
       does not stray. – (Dante Alighieri, <i>Divine Comedy</i>. 
       1265-1321)
   </span>
   </p>
_x000D_
_x000D_
_x000D_


No hardcoded values — dependent on paragraph width — have been inserted.

The animation applies the CSS3 transform property (use prefixes where needed) so it performs well.

If you need to insert a delay just once at the beginning then also set an animation-delay. If you need instead to insert a small delay at every loop then try to play with an higher padding-left (e.g. 150%)

JavaScript listener, "keypress" doesn't detect backspace?

Something I wrote up incase anyone comes across an issue with people hitting backspace while thinking they are in a form field

window.addEventListener("keydown", function(e){
    /*
     * keyCode: 8
     * keyIdentifier: "U+0008"
    */
    if(e.keyCode === 8 && document.activeElement !== 'text') {
        e.preventDefault();
        alert('Prevent page from going back');
    }
});

"Object doesn't support this property or method" error in IE11

We have set compatibility mode for IE11 to resolve an issue: Settings>Compatibility View Settings>Add your site name or Check "Display intranet sites in Compatibility View" if your portal is in the intranet.

IE version 11.0.9600.16521

Worked for us, hope this helps someone.

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

how to increase MaxReceivedMessageSize when calling a WCF from C#

Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.

Check this : Using Large Message Requests in Silverlight with WCF

<system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="TestLargeWCF.Web.MyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <customBinding>
       <binding name="customBinding0">
         <binaryMessageEncoding />
         <!-- Start change -->
         <httpTransport maxReceivedMessageSize="2097152"
                        maxBufferSize="2097152"
                        maxBufferPoolSize="2097152"/>
         <!-- Stop change -->
       </binding>
     </customBinding>
   </bindings>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   <services>
     <service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
       <endpoint address=""
                binding="customBinding"
                bindingConfiguration="customBinding0"
                contract="TestLargeWCF.Web.MyService"/>
       <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
     </service>
   </services>
 </system.serviceModel> 

Using OpenSSL what does "unable to write 'random state'" mean?

I know this question is on Linux, but on windows I had the same issue. Turns out you have to start the command prompt in "Run As Administrator" mode for it to work. Otherwise you get the same: unable to write 'random state' error.

What's the syntax to import a class in a default package in Java?

The only way to access classes in the default package is from another class in the default package. In that case, don't bother to import it, just refer to it directly.

How to show matplotlib plots in python

Save the plot as png

plt.savefig("temp.png")

How to select a CRAN mirror in R

Repository selection screen cannot be shown on your system (OS X), since OS X no longer includes X11. R tries to show you the prompt through X11. Install X11 from http://xquartz.macosforge.org/landing/. Then run the install command. The repo selection prompt will be shown.

Named placeholders in string formatting

Apache Commons Lang's replaceEach method may come in handy dependeding on your specific needs. You can easily use it to replace placeholders by name with this single method call:

StringUtils.replaceEach("There's an incorrect value '%(value)' in column # %(column)",
            new String[] { "%(value)", "%(column)" }, new String[] { x, y });

Given some input text, this will replace all occurrences of the placeholders in the first string array with the corresponding values in the second one.

Using (Ana)conda within PyCharm

this might be repetitive. I was trying to use pycharm to run flask - had anaconda 3, pycharm 2019.1.1 and windows 10. Created a new conda environment - it threw errors. Followed these steps -

  1. Used the cmd to install python and flask after creating environment as suggested above.

  2. Followed this answer.

  3. As suggested above, went to Run -> Edit Configurations and changed the environment there as well as in (2).

Obviously kept the correct python interpreter (the one in the environment) everywhere.

Getting the base url of the website and globally passing it to twig in Symfony 2

For current Symfony version (as of writing this answer it's Symfony 4.1) do not directly access the service container as done in some of the other answers.

Instead (unless you don't use the standard services configuration), inject the request object by type-hinting.

<?php

namespace App\Service;

use Symfony\Component\HttpFoundation\RequestStack;

/**
 * The YourService class provides a method for retrieving the base URL.
 *
 * @package App\Service
 */
class YourService
{

    /**
     * @var string
     */
    protected $baseUrl;

    /**
     * YourService constructor.
     *
     * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
     */
    public function __construct(RequestStack $requestStack)
    {
        $this->baseUrl = $requestStack->getCurrentRequest()->getSchemeAndHttpHost();
    }

    /**
     * Returns the current base URL.
     *
     * @return string
     */
    public function getBaseUrl(): string
    {
        return $this->baseUrl;
    }
}

See also official Symfony docs about how to retrieve the current request object.

Resolve build errors due to circular dependency amongst classes

In some cases it is possible to define a method or a constructor of class B in the header file of class A to resolve circular dependencies involving definitions. In this way you can avoid having to put definitions in .cc files, for example if you want to implement a header only library.

// file: a.h
#include "b.h"
struct A {
  A(const B& b) : _b(b) { }
  B get() { return _b; }
  B _b;
};

// note that the get method of class B is defined in a.h
A B::get() {
  return A(*this);
}

// file: b.h
class A;
struct B {
  // here the get method is only declared
  A get();
};

// file: main.cc
#include "a.h"
int main(...) {
  B b;
  A a = b.get();
}

how to remove key+value from hash in javascript

Another option may be this John Resig remove method. can better fit what you need. if you know the index in the array.

SQL Server CASE .. WHEN .. IN statement

CASE AlarmEventTransactions.DeviceID should just be CASE.

You are mixing the 2 forms of the CASE expression.

How do I call a SQL Server stored procedure from PowerShell?

This answer was pulled from http://www.databasejournal.com/features/mssql/article.php/3683181

This same example can be used for any adhoc queries. Let us execute the stored procedure “sp_helpdb” as shown below.

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

Hash table runtime complexity (insert, search and delete)

Hash tables are O(1) average and amortized case complexity, however it suffers from O(n) worst case time complexity. [And I think this is where your confusion is]

Hash tables suffer from O(n) worst time complexity due to two reasons:

  1. If too many elements were hashed into the same key: looking inside this key may take O(n) time.
  2. Once a hash table has passed its load balance - it has to rehash [create a new bigger table, and re-insert each element to the table].

However, it is said to be O(1) average and amortized case because:

  1. It is very rare that many items will be hashed to the same key [if you chose a good hash function and you don't have too big load balance.
  2. The rehash operation, which is O(n), can at most happen after n/2 ops, which are all assumed O(1): Thus when you sum the average time per op, you get : (n*O(1) + O(n)) / n) = O(1)

Note because of the rehashing issue - a realtime applications and applications that need low latency - should not use a hash table as their data structure.

EDIT: Annother issue with hash tables: cache
Another issue where you might see a performance loss in large hash tables is due to cache performance. Hash Tables suffer from bad cache performance, and thus for large collection - the access time might take longer, since you need to reload the relevant part of the table from the memory back into the cache.

How do I get the current username in Windows PowerShell?

I thought it would be valuable to summarize and compare the given answers.

If you want to access the environment variable:

(easier/shorter/memorable option)

  • [Environment]::UserName -- @ThomasBratt
  • $env:username -- @Eoin
  • whoami -- @galaktor

If you want to access the Windows access token:

(more dependable option)

  • [System.Security.Principal.WindowsIdentity]::GetCurrent().Name -- @MarkSeemann

If you want the name of the logged in user

(rather than the name of the user running the PowerShell instance)

  • $(Get-WMIObject -class Win32_ComputerSystem | select username).username -- @TwonOfAn on this other forum

Comparison

@Kevin Panko's comment on @Mark Seemann's answer deals with choosing one of the categories over the other:

[The Windows access token approach] is the most secure answer, because $env:USERNAME can be altered by the user, but this will not be fooled by doing that.

In short, the environment variable option is more succinct, and the Windows access token option is more dependable.

I've had to use @Mark Seemann's Windows access token approach in a PowerShell script that I was running from a C# application with impersonation.

The C# application is run with my user account, and it runs the PowerShell script as a service account. Because of a limitation of the way I'm running the PowerShell script from C#, the PowerShell instance uses my user account's environment variables, even though it is run as the service account user.

In this setup, the environment variable options return my account name, and the Windows access token option returns the service account name (which is what I wanted), and the logged in user option returns my account name.


Testing

Also, if you want to compare the options yourself, here is a script you can use to run a script as another user. You need to use the Get-Credential cmdlet to get a credential object, and then run this script with the script to run as another user as argument 1, and the credential object as argument 2.

Usage:

$cred = Get-Credential UserTo.RunAs
Run-AsUser.ps1 "whoami; pause" $cred
Run-AsUser.ps1 "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; pause" $cred

Contents of Run-AsUser.ps1 script:

param(
  [Parameter(Mandatory=$true)]
  [string]$script,
  [Parameter(Mandatory=$true)]
  [System.Management.Automation.PsCredential]$cred
)

Start-Process -Credential $cred -FilePath 'powershell.exe' -ArgumentList 'noprofile','-Command',"$script"

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

Dilemma: when to use Fragments vs Activities:

Well, according to Google's lectures (maybe here, I don't remember) , you should consider using Fragments whenever it's possible, as it makes your code easier to maintain and control.

However, I think that on some cases it can get too complex, as the activity that hosts the fragments need to navigate/communicate between them.

I think you should decide by yourself what's best for you. It's usually not that hard to convert an activity to a fragment and vice versa.

I've created a post about this dillema here, if you wish to read some further.

SQL to search objects, including stored procedures, in Oracle

I'm not sure I quite understand the question but if you want to search objects on the database for a particular search string try:

SELECT owner, name, type, line, text 
FROM dba_source
WHERE instr(UPPER(text), UPPER(:srch_str)) > 0;

From there if you need any more info you can just look up the object / line number.

Format ints into string of hex

With python 2.X, you can do the following:

numbers = [0, 1, 2, 3, 127, 200, 255]
print "".join(chr(i).encode('hex') for i in numbers)

print

'000102037fc8ff'

Print very long string completely in pandas dataframe

Use pd.set_option('display.max_colwidth', None) for automatic linebreaks and multi-line cells.

This is a great resource on how to use jupyters display with pandas to the fullest.


Edited: Used to be pd.set_option('display.max_colwidth', -1).

"Unable to launch the IIS Express Web server" error

Deleting the unnecessary site entries from applicationhost.config file solved the issue for me.

Upgrade python in a virtualenv

For everyone with the problem

Error: Command '['/Users/me/Sites/site/venv3/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1.

You have to install python3.6-venv

 sudo apt-get install python3.6-venv

AngularJS Uploading An Image With ng-upload

In my case above mentioned methods work fine with php but when i try to upload files with these methods in node.js then i have some problem. So instead of using $http({..,..,...}) use the normal jquery ajax.

For select file use this

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)"/>

And in controller

$scope.uploadFile = function(element) {   
var data = new FormData();
data.append('file', $(element)[0].files[0]);
jQuery.ajax({
      url: 'brand/upload',
      type:'post',
      data: data,
      contentType: false,
      processData: false,
      success: function(response) {
      console.log(response);
      },
      error: function(jqXHR, textStatus, errorMessage) {
      alert('Error uploading: ' + errorMessage);
      }
 });   
};

What's the best strategy for unit-testing database-driven applications?

I'm always running tests against an in-memory DB (HSQLDB or Derby) for these reasons:

  • It makes you think which data to keep in your test DB and why. Just hauling your production DB into a test system translates to "I have no idea what I'm doing or why and if something breaks, it wasn't me!!" ;)
  • It makes sure the database can be recreated with little effort in a new place (for example when we need to replicate a bug from production)
  • It helps enormously with the quality of the DDL files.

The in-memory DB is loaded with fresh data once the tests start and after most tests, I invoke ROLLBACK to keep it stable. ALWAYS keep the data in the test DB stable! If the data changes all the time, you can't test.

The data is loaded from SQL, a template DB or a dump/backup. I prefer dumps if they are in a readable format because I can put them in VCS. If that doesn't work, I use a CSV file or XML. If I have to load enormous amounts of data ... I don't. You never have to load enormous amounts of data :) Not for unit tests. Performance tests are another issue and different rules apply.

Android: Share plain text using intent (to all messaging apps)

Use below method, just pass the subject and body as arguments of the method

public static void shareText(String subject,String body) {
    Intent txtIntent = new Intent(android.content.Intent.ACTION_SEND);
    txtIntent .setType("text/plain");
    txtIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    txtIntent .putExtra(android.content.Intent.EXTRA_TEXT, body);
    startActivity(Intent.createChooser(txtIntent ,"Share"));
}

Linux bash: Multiple variable assignment

Sometimes you have to do something funky. Let's say you want to read from a command (the date example by SDGuero for example) but you want to avoid multiple forks.

read month day year << DATE_COMMAND
 $(date "+%m %d %Y")
DATE_COMMAND
echo $month $day $year

You could also pipe into the read command, but then you'd have to use the variables within a subshell:

day=n/a; month=n/a; year=n/a
date "+%d %m %Y" | { read day month year ; echo $day $month $year; }
echo $day $month $year

results in...

13 08 2013
n/a n/a n/a

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

Open a local HTML file using window.open in Chrome

This worked for me fine:

File 1:

    <html>
    <head></head>
    <body>
        <a href="#" onclick="window.open('file:///D:/Examples/file2.html'); return false">CLICK ME</a>
    </body>
    <footer></footer>
    </html>

File 2:

    <html>
        ...
    </html>

This method works regardless of whether or not the 2 files are in the same directory, BUT both files must be local.

For obvious security reasons, if File 1 is located on a remote server you absolutely cannot open a file on some client's host computer and trying to do so will open a blank target.

Check if a Class Object is subclass of another Class Object in Java

instanceof works on instances, i.e. on Objects. Sometimes you want to work directly with classes. In this case you can use the asSubClass method of the Class class. Some examples:

1)

    Class o=Object.class;
    Class c=Class.forName("javax.swing.JFrame").asSubclass(o);

this will go through smoothly because JFrame is subclass of Object. c will contain a Class object representing the JFrame class.

2)

    Class o=JButton.class;
    Class c=Class.forName("javax.swing.JFrame").asSubclass(o);

this will launch a java.lang.ClassCastException because JFrame is NOT subclass of JButton. c will not be initialized.

3)

    Class o=Serializable.class;
    Class c=Class.forName("javax.swing.JFrame").asSubclass(o);

this will go through smoothly because JFrame implements the java.io.Serializable interface. c will contain a Class object representing the JFrame class.

Of course the needed imports have to be included.

Show Current Location and Update Location in MKMapView in Swift

You just need to set the userTrackingMode of the MKMapView. If you only want to display and track the user location and implement the same behaviour as the Apple Maps app uses, there is no reason for writing additional code.

mapView.userTrackingMode = .follow

See more at https://developer.apple.com/documentation/mapkit/mkmapview/1616208-usertrackingmode .

How to create a Jar file in Netbeans

I also tried to make an executable jar file that I could run with the following command:

java -jar <jarfile>

After some searching I found the following link:

Packaging and Deploying Desktop Java Applications

I set the project's main class:

  1. Right-click the project's node and choose Properties
  2. Select the Run panel and enter the main class in the Main Class field
  3. Click OK to close the Project Properties dialog box
  4. Clean and build project

Then in the fodler dist the newly created jar should be executable with the command I mentioned above.

How can I let a user download multiple files when a button is clicked?

This is the easiest way I have found to download multiple files.

$('body').on('click','.download_btn',function(){
    downloadFiles([
        ['File1.pdf', 'File1-link-here'],
        ['File2.pdf', 'File2-link-here'],
        ['File3.pdf', 'File3-link-here'],
        ['File4.pdf', 'File4-link-here']
    ]);
})
function downloadFiles(files){
    if(files.length == 0){
        return;
    }
    file = files.pop();
    var Link = $('body').append('<a href="'+file[1]+'" download="file[0]"></a>');
    Link[0].click(); 
    Link.remove();
    downloadFiles(files);
}

This should be work for you. Thank You.

C# List<> Sort by x then y

The trick is to implement a stable sort. I've created a Widget class that can contain your test data:

public class Widget : IComparable
{
    int x;
    int y;
    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public Widget(int argx, int argy)
    {
        x = argx;
        y = argy;
    }

    public int CompareTo(object obj)
    {
        int result = 1;
        if (obj != null && obj is Widget)
        {
            Widget w = obj as Widget;
            result = this.X.CompareTo(w.X);
        }
        return result;
    }

    static public int Compare(Widget x, Widget y)
    {
        int result = 1;
        if (x != null && y != null)                
        {                
            result = x.CompareTo(y);
        }
        return result;
    }
}

I implemented IComparable, so it can be unstably sorted by List.Sort().

However, I also implemented the static method Compare, which can be passed as a delegate to a search method.

I borrowed this insertion sort method from C# 411:

 public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)
        {           
            int count = list.Count;
            for (int j = 1; j < count; j++)
            {
                T key = list[j];

                int i = j - 1;
                for (; i >= 0 && comparison(list[i], key) > 0; i--)
                {
                    list[i + 1] = list[i];
                }
                list[i + 1] = key;
            }
    }

You would put this in the sort helpers class that you mentioned in your question.

Now, to use it:

    static void Main(string[] args)
    {
        List<Widget> widgets = new List<Widget>();

        widgets.Add(new Widget(0, 1));
        widgets.Add(new Widget(1, 1));
        widgets.Add(new Widget(0, 2));
        widgets.Add(new Widget(1, 2));

        InsertionSort<Widget>(widgets, Widget.Compare);

        foreach (Widget w in widgets)
        {
            Console.WriteLine(w.X + ":" + w.Y);
        }
    }

And it outputs:

0:1
0:2
1:1
1:2
Press any key to continue . . .

This could probably be cleaned up with some anonymous delegates, but I'll leave that up to you.

EDIT: And NoBugz demonstrates the power of anonymous methods...so, consider mine more oldschool :P

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

Try:

SELECT convert(datetime, '23/07/2009', 103)

this is British/French standard.

Removing character in list of strings

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]

msg = filter(lambda x : x != "8", lst)

print msg

EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.

Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.

To make this (kinda work?) with how the intent of the question was we could perform something similar to this

msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
  • I am not in an interpreter at the moment so of course mileage may vary, we may have to index so we do list(y[0]) would be the only modification to the above for this explanation purposes.

What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].

This would result in a data type that looks like this

msg = [["a", "a", "a", "a"], ["b", "b"]...]

So finally to wrap that up we would have to map it to bring them all back into the same type roughly

msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))

I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.

How do I capture the output of a script if it is being ran by the task scheduler?

You can have a debug.cmd that calls yourscript.cmd

yourscript.cmd > logall.txt

you schedule debug.cmd instead of yourscript.cmd

Get the first item from an iterable that matches a condition

By using

(index for index, value in enumerate(the_iterable) if condition(value))

one can check the condition of the value of the first item in the_iterable, and obtain its index without the need to evaluate all of the items in the_iterable.

The complete expression to use is

first_index = next(index for index, value in enumerate(the_iterable) if condition(value))

Here first_index assumes the value of the first value identified in the expression discussed above.

Using momentjs to convert date to epoch then back to date

http://momentjs.com/docs/#/displaying/unix-timestamp/

You get the number of unix seconds, not milliseconds!

You you need to multiply it with 1000 or using valueOf() and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.

moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()

Undoing a git rebase

The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the reflog...

git reflog

and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the --hard option).

Suppose the old commit was HEAD@{5} in the ref log:

git reset --hard HEAD@{5}

In Windows, you may need to quote the reference:

git reset --hard "HEAD@{5}"

You can check the history of the candidate old head by just doing a git log HEAD@{5} (Windows: git log "HEAD@{5}").

If you've not disabled per branch reflogs you should be able to simply do git reflog branchname@{1} as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently.

Per default, all reflogs are activated for non-bare repositories:

[core]
    logAllRefUpdates = true

how to download file in react js

You can define a component and use it wherever.

import React from 'react';
import PropTypes from 'prop-types';


export const DownloadLink = ({ to, children, ...rest }) => {

  return (
    <a
      {...rest}
      href={to}
      download
    >
      {children}
    </a>
  );
};


DownloadLink.propTypes = {
  to: PropTypes.string,
  children: PropTypes.any,
};

export default DownloadLink;

.Net picking wrong referenced assembly version

Maybe this helps or maybe not. I cleaned my debug and release versions then I renamed the OBJ folder. This finally got me thorugh. Previous steps were basically project removing references and them adding them back in at the project properties.

How do I instantiate a JAXBElement<String> object?

When you imported the WSDL, you should have an ObjectFactory class which should have bunch of methods for creating various input parameters.

ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

If you tried all the other answers in this question and you:

  • Have multiple projects in your solution
  • Have a project (Project A) that references another project (Project B), whose project references a NuGet package.
  • In Project A, you used Intellisense/ReSharper to bring in the reference to the NuGet package referenced in Project B (this can happen when a method in Project B returns a type provided by the NuGet package and that method is used in Project A)
  • updated the NuGet package via NuGet Package Manager (or CLI).

...you may have separate versions of the NuGet packages DLL in your projects' References, as the reference created by Intellisense/ReSharper will be a "normal" reference, and not a NuGet reference as expected, so the NuGet update process won't find or update it!

To fix this, remove the reference in Project A, then use NuGet to install it, and make sure the NuGet packages in all projects are the same version. (as explain in this answer)


Life Pro Tip:

This issue can come up whenever ReSharper/Intellisense suggests to add a reference to your project. It can be much more deeply convoluted than the example above, with multiple interweaving projects and dependencies making it hard to track down. If the reference being suggested by ReSharper/Intellisense is actually from a NuGet package, use NuGet to install it.

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I ran into this problem, and when I checked out the database directory, there were a number of exp files (the ibd and frm files had been removed). Listing the files to look at their attributes (since the owner already had rw privileges on the files)

lsattr *.exp
-------------e-- foo.exp
-------------e-- bar.exp

Man page says

       The  'e'  attribute  indicates that the file is using extents for mapping the blocks on disk.
       It may not be removed using chattr(1).

You actually can chattr -e these files, but mysql still won't let you drop the database. Removing the files with rm, however, allows the database to be dropped cleanly.

Short circuit Array.forEach like calling break

I know it not right way. It is not break the loop. It is a Jugad

_x000D_
_x000D_
let result = true;_x000D_
[1, 2, 3].forEach(function(el) {_x000D_
    if(result){_x000D_
      console.log(el);_x000D_
      if (el === 2){_x000D_
        result = false;_x000D_
      }_x000D_
    }_x000D_
});
_x000D_
_x000D_
_x000D_

How to access Anaconda command prompt in Windows 10 (64-bit)

After installing Anaconda3 on your system you need to add Anaconda to the PATH environment variable. This will allow you to access Anaconda with the 'conda' command from cmd.exe or PowerShell.

The link I provided below go through the three major issues with not recognized error. Which are:

  1. Environment PATH for Conda is not set
  2. Environment PATH is incorrectly added
  3. Anaconda version is older than the version of the Anaconda Navigator

LINK: https://appuals.com/fix-conda-is-not-recognized-as-an-internal-or-external-command-operable-program-or-batch-file/

My issue was resolved following the steps for issue #2 Environment PATH is incorrectly added. I did not have all three file paths in my variable environment.

How to check if running as root in a bash script

The $EUID environment variable holds the current user's UID. Root's UID is 0. Use something like this in your script:

if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit
fi

Note: If you get 2: [: Illegal number: check if you have #!/bin/sh at the top and change it to #!/bin/bash.

How to use OKHTTP to make a post request?

Here is my method to do post request first pass in method map and data like

HashMap<String, String> param = new HashMap<String, String>();

param.put("Name", name);
param.put("Email", email);
param.put("Password", password);
param.put("Img_Name", "");

final JSONObject result = doPostRequest(map,Url);

public static JSONObject doPostRequest(HashMap<String, String> data, String url) {

    try {
        RequestBody requestBody;
        MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

        if (data != null) {


            for (String key : data.keySet()) {
                String value = data.get(key);
                Utility.printLog("Key Values", key + "-----------------" + value);

                mBuilder.addFormDataPart(key, value);

            }
        } else {
            mBuilder.addFormDataPart("temp", "temp");
        }
        requestBody = mBuilder.build();


        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        Utility.printLog("URL", url);
        Utility.printLog("Response", responseBody);
        return new JSONObject(responseBody);

    } catch (UnknownHostException | UnsupportedEncodingException e) {

        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Error: " + e.getLocalizedMessage());
    } catch (Exception e) {
        e.printStackTrace();
        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
    }
    return null;
}

Using :: in C++

One use for the 'Unary Scope Resolution Operator' or 'Colon Colon Operator' is for local and global variable selection of identical names:

    #include <iostream>
    using namespace std;
    
    int variable = 20;
    
    int main()
    {
    float variable = 30;
    
    cout << "This is local to the main function: " << variable << endl;
    cout << "This is global to the main function: " << ::variable << endl;
    
    return 0;
    }

The resulting output would be:

This is local to the main function: 30

This is global to the main function: 20

Other uses could be: Defining a function from outside of a class, to access a static variable within a class or to use multiple inheritance.

ng if with angular for string contains

Do checks like that in a controller function. Your HTML should be easy-to-read markup without logic.

Controller:

angular.module("myApp")
.controller("myController",function(){
    var self = this;

    self.select = { /* ... */ };

    self.showFoo = function() {
        //Checks if self.select.name contains the character '?'
        return self.select.name.indexOf('?') != -1;
    }
});

Page example:

<div ng-app="myApp" ng-controller="myController as vm">
    <p ng-show="vm.showFoo()">Bar</p>
</div>

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

The easiest way to do this is to format a cell the way you want it, then use the "cell format ..." contextual menu to get to the fill and format colours, use the "more colors ..." button to get to the hexagon colour selector, select the custom tab.

The RGB colours are as in the table at the bottom of the pane. If you prefer HSL values change the color model from RGB to HSL. I have used this to change the saturation on my bad cells. A higher luminosity gives a worse results and the shade of all the cells is the same just the deepness of the colour is modified.

Jquery-How to grey out the background while showing the loading icon over it

I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/

Step 1 :

I renamed your container div to overlay, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.

The resulting html is :

<div class="overlay">
    <div id="loading-img"></div>
</div>


<div class="content">
    <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
    <button id="button">Submit</button>
</div>

The css of the overlay is the following

.overlay {
    background: #e9e9e9;  <- I left your 'gray' background
    display: none;        <- Not displayed by default
    position: absolute;   <- This and the following properties will
    top: 0;                  make the overlay, the element will expand
    right: 0;                so as to cover the whole body of the page
    bottom: 0;
    left: 0;
    opacity: 0.5;
}

Step 2 :

I added some dummy text so as to have something to overlay.

Step 3 :

Then, in the click handler we just need to show the overlay :

$("#button").click(function () {
    $(".overlay").show();
});

How to format a number 0..9 to display with 2 digits (it's NOT a date)

If you need to print the number you can use printf

System.out.printf("%02d", num);

You can use

String.format("%02d", num);

or

(num < 10 ? "0" : "") + num;

or

(""+(100+num)).substring(1);

How to get list of all installed packages along with version in composer?

To list the globally installed composer packages:

composer global show -i

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

How to preview git-pull without doing fetch?

After doing a git fetch, do a git log HEAD..origin/master to show the log entries between your last common commit and the origin's master branch. To show the diffs, use either git log -p HEAD..origin/master to show each patch, or git diff HEAD...origin/master (three dots not two) to show a single diff.

There normally isn't any need to undo a fetch, because doing a fetch only updates the remote branches and none of your branches. If you're not prepared to do a pull and merge in all the remote commits, you can use git cherry-pick to accept only the specific remote commits you want. Later, when you're ready to get everything, a git pull will merge in the rest of the commits.

Update: I'm not entirely sure why you want to avoid the use of git fetch. All git fetch does is update your local copy of the remote branches. This local copy doesn't have anything to do with any of your branches, and it doesn't have anything to do with uncommitted local changes. I have heard of people who run git fetch in a cron job because it's so safe. (I wouldn't normally recommend doing that, though.)

What are the rules for calling the superclass constructor?

In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:


class A : public B
{
public:
  A(int a, int b, int c);
private:
  int b_, c_;
};

Then, assuming B has a constructor which takes an int, A's constructor may look like this:


A::A(int a, int b, int c) 
  : B(a), b_(b), c_(c) // initialization list
{
  // do something
}

As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.

Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.

What properties can I use with event.target?

An easy way to see all the properties on a particular DOM node in Chrome (I'm on v.69) is to right click on the element, select inspect, and then instead of viewing the "Style" tab click on "Properties".

Inside of the Properties tab you will see all the properties for your particular element.

How do I download a package from apt-get without installing it?

Try

apt-get -d install <packages>

It is documented in man apt-get.

Just for clarification; the downloaded packages are located in the apt package cache at

/var/cache/apt/archives

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

The first row:

$result = mysql_query($query);  

return php db resource.

The second row

while ($row = mysql_fetch_array($result))  

Loops all the records returned by the query.

Use mysql_fetch_assoc instead
In that case the row has key=>value pairs.
In the while just put this:
print_r($row) and you will understand
If you use mysql_fetch_assoc the format of the row will be:

$row["column1_name"] = column1_value;  
$row["column2_name"] = column2_value;  

For this one:

$row = mysql_fetch_assoc($result)  
foreach ($row as $columnName => $columnValue) {  
    ...  
}  

You will get the firs row from the query and you will iterate all columns in the first result of the query.

Return values from the row above to the current row

This formula does not require a column letter reference ("A", "B", etc.). It returns the value of the cell one row above in the same column.

=INDIRECT(ADDRESS(ROW()-1,COLUMN()))

Serializing/deserializing with memory stream

BinaryFormatter may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.

If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer or XmlSerializer.

I want to get the type of a variable at runtime

I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:

If you wish to print as you have specified then:

scala>  def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> println(manOf(x))
scala.collection.immutable.List[Int]

If you are in repl mode then

scala> :type List(1,2,3)
List[Int]

Or if you just wish to know what the class type then as @monkjack explains "string".getClass might solve the purpose

Google access token expiration time

Since there is no accepted answer I will try to answer this one:

[s] - seconds

position fixed header in html

body{
  margin:0;
  padding:0 0 0 0;
}
div#header{
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:25;
}
@media screen{
 body>div#header{
   position: fixed;
 }
}
* html body{
  overflow:hidden;
} 
* html div#content{
  height:100%;
  overflow:auto;
}

How to execute raw queries with Laravel 5.1?

I found the solution in this topic and I code this:

$cards = DB::select("SELECT
        cards.id_card,
        cards.hash_card,
        cards.`table`,
        users.name,
        0 as total,
        cards.card_status,
        cards.created_at as last_update
    FROM cards
    LEFT JOIN users
    ON users.id_user = cards.id_user
    WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
    UNION
    SELECT
        cards.id_card,
        orders.hash_card,
        cards.`table`,
        users.name,
        sum(orders.quantity*orders.product_price) as total, 
        cards.card_status, 
        max(orders.created_at) last_update 
    FROM menu.orders
    LEFT JOIN cards
    ON cards.hash_card = orders.hash_card
    LEFT JOIN users
    ON users.id_user = cards.id_user
    GROUP BY hash_card
    ORDER BY id_card ASC");

DataGridView AutoFit and Fill

Try this :

  DGV.AutoResizeColumns();
  DGV.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;

Displaying tooltip on mouse hover of a text

Well, take a look, this works, If you have problems please tell me:

using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1() { InitializeComponent(); }

        ToolTip tip = new ToolTip();
        void richTextBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (!timer1.Enabled)
            {
                string link = GetWord(richTextBox1.Text, richTextBox1.GetCharIndexFromPosition(e.Location));
                //Checks whether the current word i a URL, change the regex to whatever you want, I found it on www.regexlib.com.
//you could also check if current word is bold, underlined etc. but I didn't dig into it.
                if (System.Text.RegularExpressions.Regex.IsMatch(link, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$"))
                {
                    tip.ToolTipTitle = link;
                    Point p = richTextBox1.Location;
                    tip.Show(link, this, p.X + e.X,
                        p.Y + e.Y + 32, //You can change it (the 35) to the tooltip's height - controls the tooltips position.
                        1000);
                    timer1.Enabled = true;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e) //The timer is to control the tooltip, it shouldn't redraw on each mouse move.
        {
            timer1.Enabled = false;
        }

        public static string GetWord(string input, int position) //Extracts the whole word the mouse is currently focused on.
        {
            char s = input[position];
            int sp1 = 0, sp2 = input.Length;
            for (int i = position; i > 0; i--)
            {
                char ch = input[i];
                if (ch == ' ' || ch == '\n')
                {
                    sp1 = i;
                    break;
                }
            }

            for (int i = position; i < input.Length; i++)
            {
                char ch = input[i];
                if (ch == ' ' || ch == '\n')
                {
                    sp2 = i;
                    break;
                }
            }

            return input.Substring(sp1, sp2 - sp1).Replace("\n", "");
        }
    }
}

mysql: see all open connections to a given database?

The command is

SHOW PROCESSLIST

Unfortunately, it has no narrowing parameters. If you need them you can do it from the command line:

mysqladmin processlist | grep database-name

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

I know this post is a little old, but a have a suggestion that may help some.

I used an Enum to determine what to set in the attribute constructor.

Property declaration :

[DbProperty(initialValue: EInitialValue.DateTime_Now)]
public DateTime CreationDate { get; set; }

Property constructor :

Public Class DbProperty Inherits System.Attribute

    Public Property InitialValue As Object

    Public Sub New(ByVal initialValue As EInitialValue)
       Select Case initialValue
          Case EInitialValue.DateTime_Now
             Me.InitialValue = System.DateTime.Now

          Case EInitialValue.DateTime_Min
             Me.InitialValue = System.DateTime.MinValue

          Case EInitialValue.DateTime_Max
             Me.InitialValue = System.DateTime.MaxValue

       End Select

    End Sub
End Class

Enum :

Public Enum EInitialValue
   DateTime_Now
   DateTime_Min
   DateTime_Max
End Enum

Find MongoDB records where array field is not empty

You can use any of the following to achieve this.
Both also take care of not returning a result for objects that don't have the requested key in them:

db.video.find({pictures: {$exists: true, $gt: {$size: 0}}})
db.video.find({comments: {$exists: true, $not: {$size: 0}}})

Maven: How do I activate a profile from command line?

Activation by system properties can be done as follows

<activation>
    <property>
        <name>foo</name>
        <value>bar</value>
    </property>
</activation>

And run the mvn build with -D to set system property

mvn clean install -Dfoo=bar

This method also helps select profiles in transitive dependency of project artifacts.

How to npm install to a specified directory?

In the documentation it's stated: Use the prefix option together with the global option:

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary. On Unix systems, it's one level up, since node is typically installed at {prefix}/bin/node rather than {prefix}/node.exe.

When the global flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.

(Emphasis by them)

So in your root directory you could install with

npm install --prefix <path/to/prefix_folder> -g

and it will install the node_modules folder into the folder

<path/to/prefix_folder>/lib/node_modules

Replace Both Double and Single Quotes in Javascript String

You don't need to escape it inside. You can use the | character to delimit searches.

"\"foo\"\'bar\'".replace(/("|')/g, "")

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);

Pro JavaScript programmer interview questions (with answers)

intermediate programmers should have technical mastery of their tools.

if he's passed the technical phone screen-esque questions above, make him sketch out something stupid on the spot, like an ajax url shortner. then grill him on his portfolio. no amazing portfolio = intermediate developer in this domain and not the guy you want in charge of your shiny new project.

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

use

select convert(varchar(10),GETDATE(), 103) + 
       ' '+
       right(convert(varchar(32),GETDATE(),108),8) AS Date_Time

It will Produce:

Date_Time 30/03/2015 11:51:40

How would you implement an LRU cache in Java?

Following the @sanjanab concept (but after fixes) I made my version of the LRUCache providing also the Consumer that allows to do something with the removed items if needed.

public class LRUCache<K, V> {

    private ConcurrentHashMap<K, V> map;
    private final Consumer<V> onRemove;
    private ConcurrentLinkedQueue<K> queue;
    private final int size;

    public LRUCache(int size, Consumer<V> onRemove) {
        this.size = size;
        this.onRemove = onRemove;
        this.map = new ConcurrentHashMap<>(size);
        this.queue = new ConcurrentLinkedQueue<>();
    }

    public V get(K key) {
        //Recently accessed, hence move it to the tail
        if (queue.remove(key)) {
            queue.add(key);
            return map.get(key);
        }
        return null;
    }

    public void put(K key, V value) {
        //ConcurrentHashMap doesn't allow null key or values
        if (key == null || value == null) throw new IllegalArgumentException("key and value cannot be null!");

        V existing = map.get(key);
        if (existing != null) {
            queue.remove(key);
            onRemove.accept(existing);
        }

        if (map.size() >= size) {
            K lruKey = queue.poll();
            if (lruKey != null) {
                V removed = map.remove(lruKey);
                onRemove.accept(removed);
            }
        }
        queue.add(key);
        map.put(key, value);
    }
}

convert float into varchar in SQL server without scientific notation

You can use this code:

STR(<Your Field>, Length, Scale)

Your Field = Float field for convert

Length = Total length of your float number with Decimal point

Scale = Number of length after decimal point

For Example:

SELECT STR(1234.5678912,8,3)

Result is: 1234.568

Note that the last digit is also round up.

Good luck.

set serveroutput on in oracle procedure

Actually, you need to call SET SERVEROUTPUT ON; before the BEGIN call.

Everyone suggested this but offers no advice where to actually place the line:

SET SERVEROUTPUT ON;

BEGIN
    FOR rec in (SELECT * FROM EMPLOYEES) LOOP
        DBMS_OUTPUT.PUT_LINE(rec.EmployeeName);
    ENDLOOP;
END;

Otherwise, you won't see any output.

What is the meaning of "$" sign in JavaScript

From another answer:

A little history

Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:

var $ = document.getElementById; //freedom from document.getElementById!

When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.

jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)

How to get raw text from pdf file using java

Extracting all keywords from PDF(from a web page) file on your local machine or Base64 encoded string:

import org.apache.commons.codec.binary.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WebPagePdfExtractor {

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();

        System.out.println("From file:   " + webPagePdfExtractor.processRecord(createByteArray()).get("text"));

        System.out.println("From string: " + webPagePdfExtractor.processRecord(getArrayFromBase64EncodedString()).get("text"));
    }

    public Map<String, Object> processRecord(byte[] byteArray) {
        Map<String, Object> map = new HashMap<>();
        try {
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(false);
            stripper.setShouldSeparateByBeads(true);

            PDDocument document = PDDocument.load(byteArray);
            String text = stripper.getText(document);
            map.put("text", text.replaceAll("\n|\r|\t", " "));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    private static byte[] getArrayFromBase64EncodedString() {
        String encodedContent = "data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmlsdGVyIC9GbGF0ZURlY29kZSA+PgpzdHJlYW0KeAGF0E0OgjAQBeA9p3hL3UCHlha2Gg9A0sS1AepPxIDl/rFFErVESDddvPlm8nqU6EFpzARjBCVkLHNkipBzPBsc8UCyt4TKgmCr/9HI+GDqg2x8Luzk8UtfYwX5DVWLnQaLmd+qHTsF3V5QEekWidZuDNpgc7L1FvqGg35fOzPlqslFYJrzZdnkq6YI77TXtrs3GBo7oKvNss9mfhT0IAV+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E3OT4KPGRiNzgzY2E0MzYzODhjMjlkNzkwNDY3Njc2NTE2MTc5PiBdID4+CnN0YXJ0eHJlZgo5MTA0CiUlRU9GCg==";
        String content = encodedContent.substring("data:application/pdf;base64," .length());
        return Base64.decodeBase64(content);
    }

    public static byte[] createByteArray() {
        String pathToBinaryData = "/bla-bla/src/main/resources/small.pdf";

        File file = new File(pathToBinaryData);
        if (!file.exists()) {
            System.out.println(" could not be found in folder " + pathToBinaryData);
            return null;
        }

        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        byte fileContent[] = new byte[(int) file.length()];

        try {
            fin.read(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileContent;
    }
}

How to get the number of days of difference between two dates on mysql?

SELECT md.*, DATEDIFF(md.end_date, md.start_date) AS days FROM  membership_dates md

output::

id  entity_id    start_date            end_date             days

1   1236      2018-01-16 00:00:00     2018-08-31 00:00:00    227
2   2876      2015-06-26 00:00:00     2019-06-30 00:00:00   1465
3   3880      1990-06-05 00:00:00     2018-07-04 00:00:00   10256
4   3882      1993-07-05 00:00:00     2018-07-04 00:00:00   9130

hope it helps someone in future

Difference between numpy.array shape (R, 1) and (R,)

The difference between (R,) and (1,R) is literally the number of indices that you need to use. ones((1,R)) is a 2-D array that happens to have only one row. ones(R) is a vector. Generally if it doesn't make sense for the variable to have more than one row/column, you should be using a vector, not a matrix with a singleton dimension.

For your specific case, there are a couple of options:

1) Just make the second argument a vector. The following works fine:

    np.dot(M[:,0], np.ones(R))

2) If you want matlab like matrix operations, use the class matrix instead of ndarray. All matricies are forced into being 2-D arrays, and operator * does matrix multiplication instead of element-wise (so you don't need dot). In my experience, this is more trouble that it is worth, but it may be nice if you are used to matlab.

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

How to set selectedIndex of select element using display text?

If you want this without loops or jquery you could use the following This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.

_x000D_
_x000D_
// Please note that querySelectorAll will return a match for _x000D_
// for the term...if there is more than one then you will _x000D_
// have to loop through the returned object_x000D_
var selectAnimal = function() {_x000D_
  var animals = document.getElementById('animal');_x000D_
  if (animals) {_x000D_
    var x = animals.querySelectorAll('option[value="frog"]');_x000D_
    if (x.length === 1) {_x000D_
      console.log(x[0].index);_x000D_
      animals.selectedIndex = x[0].index;_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Test without loop or jquery</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <label>Animal to select_x000D_
  <select id='animal'>_x000D_
    <option value='nothing'></option>_x000D_
    <option value='dog'>dog</option>_x000D_
    <option value='cat'>cat</option>_x000D_
    <option value='mouse'>mouse</option>_x000D_
    <option value='rat'>rat</option>_x000D_
    <option value='frog'>frog</option>_x000D_
    <option value='horse'>horse</option>_x000D_
  </select>_x000D_
  </label>_x000D_
  <button onclick="selectAnimal()">Click to select animal</button>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

document.getElementById('Animal').querySelectorAll('option[value="searchterm"]'); in the index object you can now do the following: x[0].index

Returning an array using C

You can use code like this:

char *MyFunction(some arguments...)
{
    char *pointer = malloc(size for the new array);
    if (!pointer)
        An error occurred, abort or do something about the error.
    return pointer; // Return address of memory to the caller.
}

When you do this, the memory should later be freed, by passing the address to free.

There are other options. A routine might return a pointer to an array (or portion of an array) that is part of some existing structure. The caller might pass an array, and the routine merely writes into the array, rather than allocating space for a new array.

Hidden features of Windows batch files

Search and replace when setting environment variables:

> @set fname=%date:/=%

...removes the "/" from a date for use in timestamped file names.

and substrings too...

> @set dayofweek=%fname:~0,3%

Single controller with multiple GET methods in ASP.NET Web API

Modify the WebApiConfig and add at the end another Routes.MapHttpRoute like this:

config.Routes.MapHttpRoute(
                name: "ServiceApi",
                routeTemplate: "api/Service/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Then create a controller like this:

public class ServiceController : ApiController
{
        [HttpGet]
        public string Get(int id)
        {
            return "object of id id";
        }
        [HttpGet]
        public IQueryable<DropDownModel> DropDowEmpresa()
        {
            return db.Empresa.Where(x => x.Activo == true).Select(y =>
                  new DropDownModel
                  {
                      Id = y.Id,
                      Value = y.Nombre,
                  });
        }

        [HttpGet]
        public IQueryable<DropDownModel> DropDowTipoContacto()
        {
            return db.TipoContacto.Select(y =>
                  new DropDownModel
                  {
                      Id = y.Id,
                      Value = y.Nombre,
                  });
        }

        [HttpGet]
        public string FindProductsByName()
        {
            return "FindProductsByName";
        }
}

This is how I solved it. I hope it will help someone.

First Or Create

An update:

As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate method now accepts an optional second array as an argument.

The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:

See documentation

Creating multiple objects with different names in a loop to store in an array list

You can use this code...

public class Main {

    public static void main(String args[]) {
        String[] names = {"First", "Second", "Third"};//You Can Add More Names
        double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
        List<Customer> customers = new ArrayList<Customer>();
        int i = 0;
        while (i < names.length) {
            customers.add(new Customer(names[i], amount[i]));
            i++;
        }
    }
}

Python: maximum recursion depth exceeded while calling a Python object

You can increase the capacity of the stack by the following :

import sys
sys.setrecursionlimit(10000)

What are the minimum margins most printers can handle?

The margins vary depending on the printer. In Windows GDI, you call the following functions to get the built-in margins, the "no-print zone":

GetDeviceCaps(hdc, PHYSICALWIDTH);
GetDeviceCaps(hdc, PHYSICALHEIGHT);
GetDeviceCaps(hdc, PHYSICALOFFSETX);
GetDeviceCaps(hdc, PHYSICALOFFSETY);

Printing right to the edge is called a "bleed" in the printing industry. The only laser printer I ever knew to print right to the edge was the Xerox 9700: 120 ppm, $500K in 1980.

Remove URL parameters without refreshing page

I wanted to remove only one param success. Here's how you can do this:

let params = new URLSearchParams(location.search)
params.delete('success')
history.replaceState(null, '', '?' + params + location.hash)

This also retains #hash.


URLSearchParams won't work on IE, but being worked on for Edge. You can use a polyfill or a could use a naïve helper function for IE-support:

function take_param(key) {
    var params = new Map(location.search.slice(1).split('&')
        .map(function(p) { return p.split(/=(.*)/) }))   
    var value = params.get(key)
    params.delete(key)
    var search = Array.from(params.entries()).map(
        function(v){ return v[0]+'='+v[1] }).join('&')
    return {search: search ? '?' + search : '', value: value}
}

This can be used like:

history.replaceState(
    null, '', take_param('success').search + location.hash)

What is an HttpHandler in ASP.NET

Any Class that implements System.Web.IHttpHandler Interface becomes HttpHandler. And this class run as processes in response to a request made to the ASP.NET Site.

The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler(The Class that implements System.Web.IHttpHandler Interface).

You can create your own custom HTTP handlers that render custom output to the browser.

Some ASP.NET default handlers are:

  1. Page Handler (.aspx) – Handles Web pages
  2. User Control Handler (.ascx) – Handles Web user control pages
  3. Web Service Handler (.asmx) – Handles Web service pages
  4. Trace Handler (trace.axd) – Handles trace functionality

Facebook Open Graph Error - Inferred Property

Are those tags on 'http://www.mywebaddress.com'?

Bear in mind the linter will follow the og:url tag as this tag should point to the canonical URL of the piece of content - so if you have a page, e.g. 'http://mywebaddress.com/article1' with an og:url tag pointing to 'http://mywebaddress.com', Facebook will go there and read the tags there also.

Failing that, the most common reason i've seen for seemingly correct tags not being detected by the linter is user-agent detection returning different content to Facebook's crawler than the content you're seeing when you manually check

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

What are these new categories of expressions?

The FCD (n3092) has an excellent description:

— An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object. [ Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue. —end example ]

— An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references (8.3.2). [ Example: The result of calling a function whose return type is an rvalue reference is an xvalue. —end example ]

— A glvalue (“generalized” lvalue) is an lvalue or an xvalue.

— An rvalue (so called, historically, because rvalues could appear on the right-hand side of an assignment expressions) is an xvalue, a temporary object (12.2) or subobject thereof, or a value that is not associated with an object.

— A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [ Example: The result of calling a function whose return type is not a reference is a prvalue. The value of a literal such as 12, 7.3e5, or true is also a prvalue. —end example ]

Every expression belongs to exactly one of the fundamental classifications in this taxonomy: lvalue, xvalue, or prvalue. This property of an expression is called its value category. [ Note: The discussion of each built-in operator in Clause 5 indicates the category of the value it yields and the value categories of the operands it expects. For example, the built-in assignment operators expect that the left operand is an lvalue and that the right operand is a prvalue and yield an lvalue as the result. User-defined operators are functions, and the categories of values they expect and yield are determined by their parameter and return types. —end note

I suggest you read the entire section 3.10 Lvalues and rvalues though.

How do these new categories relate to the existing rvalue and lvalue categories?

Again:

Taxonomy

Are the rvalue and lvalue categories in C++0x the same as they are in C++03?

The semantics of rvalues has evolved particularly with the introduction of move semantics.

Why are these new categories needed?

So that move construction/assignment could be defined and supported.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

Hello World in Python

print("Hello, World!")

You are probably using Python 3.0, where print is now a function (hence the parenthesis) instead of a statement.

How to add plus one (+1) to a SQL Server column in a SQL Query

"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"

Number of occurrences of a character in a string

Here is the most inefficient way to get the count in all answers. But you'll get a Dictionary that contains key-value pairs as a bonus.

string test = "key1=value1&key2=value2&key3=value3";

var keyValues = Regex.Matches(test, @"([\w\d]+)=([\w\d]+)[&$]*")
                     .Cast<Match>()
                     .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

var count = keyValues.Count - 1;

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Brew doctor says: "Warning: /usr/local/include isn't writable."

First you need to create the directory:

sudo mkdir /usr/local/include

Second:

sudo chown -R $(whoami) $(brew --prefix)/*

Preferred way of getting the selected item of a JComboBox

If you have only put (non-null) String references in the JComboBox, then either way is fine.

However, the first solution would also allow for future modifications in which you insert Integers, Doubless, LinkedLists etc. as items in the combo box.

To be robust against null values (still without casting) you may consider a third option:

String x = String.valueOf(JComboBox.getSelectedItem());

Windows batch script to unhide files hidden by virus

echo "Enter Drive letter" 
set /p driveletter=

attrib -s -h -a /s /d  %driveletter%:\*.*

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

From this post:

To get the entire PC CPU and Memory usage:

using System.Diagnostics;

Then declare globally:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

Then to get the CPU time, simply call the NextValue() method:

this.theCPUCounter.NextValue();

This will get you the CPU usage

As for memory usage, same thing applies I believe:

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Memory", "Available MBytes");

Then to get the memory usage, simply call the NextValue() method:

this.theMemCounter.NextValue();

For a specific process CPU and Memory usage:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Process", "% Processor Time",              
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Process", "Working Set",
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?

To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters

The difference between Processor\% Processor Time and Process\% Processor Time is Processor is from the PC itself and Process is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters

An alternative to using the Performance Counter

Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.

Call a url from javascript

Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.

In jQuery:

$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })

In plain vanilla javaScript (from w3c):

var xmlhttp;
function loadXMLDoc(url)
{
    xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for all new browsers
      xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.send(null);
  }
else
  {
      alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
    if (xmlhttp.readyState==4)
      {// 4 = "loaded"
          if (xmlhttp.status==200)
            {// 200 = OK
             //xmlhttp.data and shtuff
            // ...our code here...
        }
  else
        {
            alert("Problem retrieving data");
        }
  }
}

Why do we use volatile keyword?

In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia

http://en.wikipedia.org/wiki/Volatile_variable

Setting Column width in Apache POI

You can use also util methods mentioned in this blog: Getting cell witdth and height from excel with Apache POI. It can solve your problem.

Copy & paste from that blog:

static public class PixelUtil {

    public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
    public static final short EXCEL_ROW_HEIGHT_FACTOR = 20;
    public static final int UNIT_OFFSET_LENGTH = 7;
    public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 };

    public static short pixel2WidthUnits(int pxs) {
        short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH));
        widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];
        return widthUnits;
    }

    public static int widthUnits2Pixel(short widthUnits) {
        int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH;
        int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;
        pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));
        return pixels;
    }

    public static int heightUnits2Pixel(short heightUnits) {
        int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR);
        int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
        pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH));
        return pixels;
    }
}

So when you want to get cell width and height you can use this to get value in pixel, values are approximately.

PixelUtil.heightUnits2Pixel((short) row.getHeight())
PixelUtil.widthUnits2Pixel((short) sh.getColumnWidth(columnIndex));

Matching strings with wildcard

Often, wild cards operate with two type of jokers:

  ? - any character  (one and only one)
  * - any characters (zero or more)

so you can easily convert these rules into appropriate regular expression:

  // If you want to implement both "*" and "?"
  private static String WildCardToRegular(String value) {
    return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$"; 
  }

  // If you want to implement "*" only
  private static String WildCardToRegular(String value) {
    return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$"; 
  }

And then you can use Regex as usual:

  String test = "Some Data X";

  Boolean endsWithEx = Regex.IsMatch(test, WildCardToRegular("*X"));
  Boolean startsWithS = Regex.IsMatch(test, WildCardToRegular("S*"));
  Boolean containsD = Regex.IsMatch(test, WildCardToRegular("*D*"));

  // Starts with S, ends with X, contains "me" and "a" (in that order) 
  Boolean complex = Regex.IsMatch(test, WildCardToRegular("S*me*a*X"));

How to see the changes in a Git commit?

First get the commit ID using,

git log #to list all

Or

git log -p -1 #last one commit id

Copy commit id.

Now we use two methods to list changes from a specific commit,

Method 1:

git diff commit_id^! #commit id something like this 1c6a6000asad012

Method 2:

git show commit_id
For example: git show 1c6a600a

Apply a function to every row of a matrix or a data frame

Another approach if you want to use a varying portion of the dataset instead of a single value is to use rollapply(data, width, FUN, ...). Using a vector of widths allows you to apply a function on a varying window of the dataset. I've used this to build an adaptive filtering routine, though it isn't very efficient.

How do ports work with IPv6?

They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.

What is deserialize and serialize in JSON?

Explanation of Serialize and Deserialize using Python

In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.

Serialization using pickle

import pickle

#the object to serialize
example_dic={1:"6",2:"2",3:"f"}

#where the bytes after serializing end up at, wb stands for write byte
pickle_out=open("dict.pickle","wb")
#Time to dump
pickle.dump(example_dic,pickle_out)
#whatever you open, you must close
pickle_out.close()

The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):

€}q (KX 6qKX 2qKX fqu.

Deserialization using pickle

import pickle

pickle_in=open("dict.pickle","rb")
get_deserialized_data_back=pickle.load(pickle_in)

print(get_deserialized_data_back)

Output:

{1: '6', 2: '2', 3: 'f'}

PHP Error: Function name must be a string

Try square braces with your $_COOKIE, not parenthesis. Like this:

<?php
if ($_COOKIE['CaptchaResponseValue'] == "false")
{
    header('Location: index.php');
    return;
}
?>

I also corrected your location header call a little too.

What is the difference between an abstract function and a virtual function?

An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.

A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.

So for example:

public abstract class myBase
{
    //If you derive from this class you must implement this method. notice we have no method body here either
    public abstract void YouMustImplement();

    //If you derive from this class you can change the behavior but are not required to
    public virtual void YouCanOverride()
    { 
    }
}

public class MyBase
{
   //This will not compile because you cannot have an abstract method in a non-abstract class
    public abstract void YouMustImplement();
}

Regex to match string containing two names in any order

Try:

james.*jack

If you want both at the same time, then or them:

james.*jack|jack.*james

How do the post increment (i++) and pre increment (++i) operators work in Java?

when a is 5, then a++ gives a 5 to the expression and increments a afterwards, while ++a increments a before passing the number to the expression (which gives a 6 to the expression in this case).

So you calculate

i = 6 + 7 + 7
i = 5 + 7 + 8

Killing a process created with Python's subprocess.Popen()

process.terminate() doesn't work when using shell=True. This answer will help you.

How to create a self-signed certificate for a domain name for development?

To Create the new certificate for your specific domain:

Open Powershell ISE as admin, run the command:

New-SelfSignedCertificate -DnsName *.mydomain.com, localhost -CertStoreLocation cert:\LocalMachine\My

To trust the new certificate:

  • Open mmc.exe
  • Go to Console Root -> Certificates (Local Computer) -> Personal
  • Select the certificate you have created, do right click -> All Tasks -> Export and follow the export wizard to create a .pfx file
  • Go to Console Root -> Certificates -> Trusted Root Certification Authorities and import the new .pfx file

To bind the certificate to your site:

  • Open IIS Manager
  • Select your site and choose Edit Site -> Bindings in the right pane
  • Add new https binding with the correct hostname and the new certificate

ASP.NET GridView RowIndex As CommandArgument

MSDN says that:

The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled.

So you shouldn't need to set it manually. A row command with GridViewCommandEventArgs would then make it accessible; e.g.

protected void Whatever_RowCommand( object sender, GridViewCommandEventArgs e )
{
    int rowIndex = Convert.ToInt32( e.CommandArgument );
    ...
}

submit a form in a new tab

This will also work great, u can do something else while a new tab handler the submit .

<form target="_blank">
    <a href="#">Submit</a>
</form>

<script>
    $('a').click(function () {
        // do something you want ...

        $('form').submit();
    });
</script>

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

I had the same issue and I tried most of the solution provided by other folks but it worked for me with below steps. I have VS 2017.

Steps:

Install-Package EntityFramework -IncludePrerelease

then create a class as

public class MyDBContext : DbContext { public MyDBContext() { } }

and at the last execute

Enable-Migrations -EnableAutomaticMigrations

What didn't work for me:

: Restarting VS.

: only "Enable-Migrations" command, which is without -EnableAutomaticMigrations.

: restoring or updating Nuget Package Manager.

My original error in the beginning was

/* The term 'enable-migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.At line:1 char:1 + enable-migration + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (enable-migration:String) [], CommandNotFoundException */

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

center a row using Bootstrap 3

What you are doing is not working, because you apply the margin: auto to the full-width column.

Wrap it in a div and center that one. E.g:

<div class="i-am-centered">
  <div class="row">...</div>
</div>

.

.i-am-centered { margin: auto; max-width: 300px;}

http://www.bootply.com/93751

Its a cleaner solution anyway, as it is more expressive and as you usually don't want to mess with the grid.

Where in an Eclipse workspace is the list of projects stored?

In Linux after deleting

<workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\

Does not worked.

After that i have done File->Refresh

Then it cleared all old project listed from eclipse.

Address already in use: JVM_Bind java

It can be also caused by double definition of port 8080 in ..\tomcat\conf\server.xml :

<Connector port="8080"
           enableLookups="false" redirectPort="8443" debug="0"/>
<Connector port="8080"
           enableLookups="false" address="127.0.0.1" maxParameterCount="30000"/>

How to create an Observable from static data similar to http one in Angular?

Things seem to have changed since Angular 2.0.0

import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
// ...
public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}

The .next() function will be called on your subscriber.

Java SimpleDateFormat for time zone with a colon separator?

Since an example of Apache FastDateFormat(click for the documentations of versions:2.6and3.5) is missing here, I am adding one for those who may need it. The key here is the pattern ZZ(2 capital Zs).

import java.text.ParseException
import java.util.Date;
import org.apache.commons.lang3.time.FastDateFormat;
public class DateFormatTest throws ParseException {
    public static void main(String[] args) {
        String stringDateFormat = "yyyy-MM-dd'T'HH:mm:ssZZ";
        FastDateFormat fastDateFormat = FastDateFormat.getInstance(stringDateFormat);
        System.out.println("Date formatted into String:");
        System.out.println(fastDateFormat.format(new Date()));
        String stringFormattedDate = "2016-11-22T14:30:14+05:30";
        System.out.println("String parsed into Date:");
        System.out.println(fastDateFormat.parse(stringFormattedDate));
    }
}

Here is the output of the code:

Date formatted into String:
2016-11-22T14:52:17+05:30
String parsed into Date:
Tue Nov 22 14:30:14 IST 2016

Note: The above code is of Apache Commons' lang3. The class org.apache.commons.lang.time.FastDateFormat does not support parsing, and it supports only formatting. For example, the output of the following code:

import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang.time.FastDateFormat;
public class DateFormatTest {
    public static void main(String[] args) throws ParseException {
        String stringDateFormat = "yyyy-MM-dd'T'HH:mm:ssZZ";
        FastDateFormat fastDateFormat = FastDateFormat.getInstance(stringDateFormat);
        System.out.println("Date formatted into String:");
        System.out.println(fastDateFormat.format(new Date()));
        String stringFormattedDate = "2016-11-22T14:30:14+05:30";
        System.out.println("String parsed into Date:");
        System.out.println(fastDateFormat.parseObject(stringFormattedDate));
    }
}

will be this:

Date formatted into String:
2016-11-22T14:55:56+05:30
String parsed into Date:
Exception in thread "main" java.text.ParseException: Format.parseObject(String) failed
    at java.text.Format.parseObject(Format.java:228)
    at DateFormatTest.main(DateFormatTest.java:12)

Programmatically get own phone number in iOS

As you probably all ready know if you use the following line of code, your app will be rejected by Apple

NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];

here is a reference

http://ayeapi.blogspot.com/2009/12/sbformatphonenumber-is-lie.html

you can use the following information instead

NSString *phoneName = [[UIDevice currentDevice] name];

NSString *phoneUniqueIdentifier = [[UIDevice currentDevice] uniqueIdentifier];

and so on

@property(nonatomic,readonly,retain) NSString    *name;              // e.g. "My iPhone"
@property(nonatomic,readonly,retain) NSString    *model;             // e.g. @"iPhone", @"iPod Touch"
@property(nonatomic,readonly,retain) NSString    *localizedModel;    // localized version of model
@property(nonatomic,readonly,retain) NSString    *systemName;        // e.g. @"iPhone OS"
@property(nonatomic,readonly,retain) NSString    *systemVersion;     // e.g. @"2.0"
@property(nonatomic,readonly) UIDeviceOrientation orientation;       // return current device orientation
@property(nonatomic,readonly,retain) NSString    *uniqueIdentifier;  // a string unique to each device based on various hardware info.

Hope this helps!

Javascript/jQuery detect if input is focused

If you can use JQuery, then using the JQuery :focus selector will do the needful

$(this).is(':focus');

Pretty git branch graphs

Update: This answer has gotten far more attention than it deserves.  It was originally posted because I think the graphs look nice and they could be drawn-over in Illustrator for a publication– and there was no better solution.  But there now exists much more applicable answers to this Q, such as fracz's, Jubobs', or Harry Lee's!  Please go upvote those!!

Update 2: I've posted an improved version of this answer to the Visualizing branch topology in git question, since it's far more appropriate there.  That version includes lg3, which shows both the author and committer info, so you really should check it out.  Leaving this answer for historical (& rep, I'll admit) reasons, though I'm really tempted to just delete it.

My 2¢: I have two aliases I normally throw in my ~/.gitconfig file:

[alias]
lg1 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
lg = !"git lg1"

git lg/git lg1 looks like this:
git lg1

and git lg2 looks like this:
git lg2

Merge Cell values with PHPExcel - PHP

There is a specific method to do this:

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');

You can also use:

$objPHPExcel->setActiveSheetIndex(0)->mergeCells('A1:C1');

That should do the trick.

Communicating between a fragment and an activity - best practices

The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.

Once it has implemented that interface, you could do anything you want in the method it overrides.

The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.

There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.

I hope this was helpful to you!

anaconda - path environment variable in windows

Instead of giving the path following way:

C:\Users\User_name\AppData\Local\Continuum\anaconda3\python.exe

Do this:

C:\Users\User_name\AppData\Local\Continuum\anaconda3\

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

Convert Iterator to ArrayList

You can also use IteratorUtils from Apache commons-collections, although it doesn't support generics:

List list = IteratorUtils.toList(iterator);

How does the bitwise complement operator (~ tilde) work?

First we have to split the given digit into its binary digits and then reverse it by adding at the last binary digit.After this execution we have to give opposite sign to the previous digit that which we are finding the complent ~2=-3 Explanation: 2s binary form is 00000010 changes to 11111101 this is ones complement ,then complented 00000010+1=00000011 which is the binary form of three and with -sign I.e,-3

How to auto-format code in Eclipse?

The secret is simple: Ctrl+Shift+F

What does "while True" mean in Python?

while loops continue to loop until the condition is false. For instance (pseudocode):

i = 0
while i < 10
  i++

With each iteration of the loop, i will be incremented by 1, until it is 10. At that point, the condition i < 10 is no longer true, and the loop will complete.

Since the condition in while True is explicitly and always true, the loop will never end (until it is broken out of some other way, usually by a construct like break within the loop body).

Value of type 'T' cannot be converted to

I know similar code that the OP posted in this question from generic parsers. From a performance perspective, you should use Unsafe.As<TFrom, TResult>(ref TFrom source), which can be found in the System.Runtime.CompilerServices.Unsafe NuGet package. It avoids boxing for value types in these scenarios. I also think that Unsafe.As results in less machine code produced by the JIT than casting twice (using (TResult) (object) actualString), but I haven't checked that out.

public TResult ParseSomething<TResult>(ParseContext context)
{
    if (typeof(TResult) == typeof(string))
    {
        var token = context.ParseNextToken();
        string parsedString = token.ParseToDotnetString();
        return Unsafe.As<string, TResult>(ref parsedString);
    }
    else if (typeof(TResult) == typeof(int))
    {
        var token = context.ParseNextToken();
        int parsedInt32 = token.ParseToDotnetInt32();
        // This will not box which might be critical to performance
        return Unsafe.As<int, TResult>(ref parsedInt32); 
    }
    // other cases omitted for brevity's sake
}

Unsafe.As will be replaced by the JIT with efficient machine code instructions, as you can see in the official CoreFX repo:

Source Code of Unsafe.As

How to check if a String contains another String in a case insensitive manner in Java?

Yes, this is achievable:

String s1 = "abBaCca";
String s2 = "bac";

String s1Lower = s1;

//s1Lower is exact same string, now convert it to lowercase, I left the s1 intact for print purposes if needed

s1Lower = s1Lower.toLowerCase();

String trueStatement = "FALSE!";
if (s1Lower.contains(s2)) {

    //THIS statement will be TRUE
    trueStatement = "TRUE!"
}

return trueStatement;

This code will return the String "TRUE!" as it found that your characters were contained.

Removing items from a list

You can't and shouldn't modify a list while iterating over it. You can solve this by temporarely saving the objects to remove:

List<Object> toRemove = new ArrayList<Object>();
for(Object a: list){
    if(a.getXXX().equalsIgnoreCase("AAA")){
        toRemove.add(a);
    }
}
list.removeAll(toRemove);

How can I return two values from a function in Python?

You can return more than one value using list also. Check the code below

def newFn():    #your function
  result = []    #defining blank list which is to be return
  r1 = 'return1'    #first value
  r2 = 'return2'    #second value
  result.append(r1)    #adding first value in list
  result.append(r2)    #adding second value in list
  return result    #returning your list

ret_val1 = newFn()[1]    #you can get any desired result from it
print ret_val1    #print/manipulate your your result

Does Java support structs?

The equivalent in Java to a struct would be

class Member
{
    public String FirstName; 
    public String LastName;  
    public int    BirthYear; 
 };

and there's nothing wrong with that in the right circumstances. Much the same as in C++ really in terms of when do you use struct verses when do you use a class with encapsulated data.

MySQL error 2006: mysql server has gone away

This error happens basically for two reasons.

  1. You have a too low RAM.
  2. The database connection is closed when you try to connect.

You can try this code below.

# Simplification to execute an SQL string of getting a data from the database
def get(self, sql_string, sql_vars=(), debug_sql=0):
    try:            
        self.cursor.execute(sql_string, sql_vars)
        return self.cursor.fetchall()
    except (AttributeError, MySQLdb.OperationalError):
        self.__init__()
        self.cursor.execute(sql_string, sql_vars)
        return self.cursor.fetchall()

It mitigates the error whatever the reason behind it, especially for the second reason.

If it's caused by low RAM, you either have to raise database connection efficiency from the code, from the database configuration, or simply raise the RAM.

Cannot simply use PostgreSQL table name ("relation does not exist")

You have to add the schema first e.g.

SELECT * FROM place.user_place;

If you don't want to add that in all queries then try this:

SET search_path TO place;

Now it will works:

SELECT * FROM user_place;

tmux status bar configuration

I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.

Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.