Programs & Examples On #Bitmask

Bitmask is a technique used to isolate specific bits in a byte in order to work only on the desired ones. They are used in IP addresses to separate the network prefix and the host number for example.

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

Using a bitmask in C#

if ( ( param & karen ) == karen )
{
  // Do stuff
}

The bitwise 'and' will mask out everything except the bit that "represents" Karen. As long as each person is represented by a single bit position, you could check multiple people with a simple:

if ( ( param & karen ) == karen )
{
  // Do Karen's stuff
}
if ( ( param & bob ) == bob )
  // Do Bob's stuff
}

How to use bitmask?

Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45

unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));

The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.

How to query data out of the box using Spring data JPA by both Sort and Pageable?

 public List<Model> getAllData(Pageable pageable){
       List<Model> models= new ArrayList<>();
       modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
       return models;
   }

How can I compare two dates in PHP?

This works because of PHP's string comparison logic. Simply you can check...

if ($startdate < $date) {// do something} 
if ($startdate > $date) {// do something}

Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

How to present UIAlertController when not in a view controller?

create helper class AlertWindow and than use as

let alertWindow = AlertWindow();
let alert = UIAlertController(title: "Hello", message: "message", preferredStyle: .alert);
let cancel = UIAlertAction(title: "Ok", style: .cancel){(action) in

    //....  action code here

    // reference to alertWindow retain it. Every action must have this at end

    alertWindow.isHidden = true;

   //  here AlertWindow.deinit{  }

}
alert.addAction(cancel);
alertWindow.present(alert, animated: true, completion: nil)


class AlertWindow:UIWindow{

    convenience init(){
        self.init(frame:UIScreen.main.bounds);
    }

    override init(frame: CGRect) {
        super.init(frame: frame);
        if let color = UIApplication.shared.delegate?.window??.tintColor {
            tintColor = color;
        }
        rootViewController = UIViewController()
        windowLevel = UIWindowLevelAlert + 1;
        makeKeyAndVisible()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    deinit{
        //  semaphor.signal();
    }

    func present(_ ctrl:UIViewController, animated:Bool, completion: (()->Void)?){
        rootViewController!.present(ctrl, animated: animated, completion: completion);
    }
}

What is Func, how and when is it used

Maybe it is not too late to add some info.

Sum:

The Func is a custom delegate defined in System namespace that allows you to point to a method with the same signature (as delegates do), using 0 to 16 input parameters and that must return something.

Nomenclature & how2use:

Func<input_1, input_2, ..., input1_6, output> funcDelegate = someMethod;

Definition:

public delegate TResult Func<in T, out TResult>(T arg);

Where it is used:

It is used in lambda expressions and anonymous methods.

How to create cron job using PHP?

First open your SSH server with username and password and change to the default root user(User with all permissions) then follow the steps below,

  1. enter the command crontab -l now you will see the list of all cronjobs.
  2. enter crontab -e a file with all cron jobs will be opened.
  3. Edit the file with your cronjob schedule as min hr dayofmonth month dayofweek pathtocronjobfile and save the file.
  4. Now you will see a response crontab: installing new crontab now again check the list of cronjobs your cron job will be listed there.

For loop example in MySQL

Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below

CREATE TABLE `table1` (
    `col1` VARCHAR(50) NULL DEFAULT NULL
)

Now if you want to insert number from 1 to 50 in that table then use following stored procedure

DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      DECLARE a INT Default 1 ;
      simple_loop: LOOP         
         insert into table1 values(a);
         SET a=a+1;
         IF a=51 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

To call that stored procedure use

CALL `ABC`()

How to check a string starts with numeric number?

See the isDigit(char ch) method:

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html

and pass it to the first character of the String using the String.charAt() method.

Character.isDigit(myString.charAt(0));

Less aggressive compilation with CSS3 calc

A very common usecase of calc is take 100% width and adding some margin around the element.

One can do so with:

@someMarginVariable = 15px;

margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

Make sure your AndroidManifest file contains a package name in the manifest node. Setting a package name fixed this problem for me.

How do I perform an IF...THEN in an SQL SELECT?

SELECT 1 AS Saleable, *
  FROM @Product
 WHERE ( Obsolete = 'N' OR InStock = 'Y' )
UNION
SELECT 0 AS Saleable, *
  FROM @Product
 WHERE NOT ( Obsolete = 'N' OR InStock = 'Y' )

Sum across multiple columns with dplyr

dplyr >= 1.0.0 using across

sum up each row using rowSums (rowwise works for any aggreation, but is slower)

df %>%
   replace(is.na(.), 0) %>%
   mutate(sum = rowSums(across(where(is.numeric))))

sum down each column

df %>%
   summarise(across(everything(), ~ sum(., is.na(.), 0)))

dplyr < 1.0.0

sum up each row

df %>%
   replace(is.na(.), 0) %>%
   mutate(sum = rowSums(.[1:5]))

sum down each column using superseeded summarise_all:

df %>%
   replace(is.na(.), 0) %>%
   summarise_all(funs(sum))

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I had this problem and it was because the panel was outside of the [data-role="page"] element.

Excel Formula: Count cells where value is date

Total number of cells in a range minus the blank cells of the same range.

=(115 - (COUNTBLANK(C2:C116)))

This counts everything in the range so, maybe not what you're looking for.

What does "if (rs.next())" mean?

I'm presuming you're using Java 6 and that the ResultSet that you're using is a java.sql.ResultSet.

The JavaDoc for the ResultSet.next() method states:

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

So, if(rs.next(){ //do something } means "If the result set still has results, move to the next result and do something".

As BalusC pointed out, you need to replace

ResultSet rs = stmt.executeQuery(sql);

with

ResultSet rs = stmt.executeQuery();

Because you've already set the SQL to use in the statement with your previous line

PreparedStatement stmt = conn.prepareStatement(sql);

If you weren't using the PreparedStatement, then ResultSet rs = stmt.executeQuery(sql); would work.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

XAMPP Control Panel under Windows does not always reflect what is actually going on, unless you start it by "Run as administrator".

What does "exec sp_reset_connection" mean in Sql Server Profiler?

It's an indication that connection pooling is being used (which is a good thing).

current/duration time of html5 video?

I am assuming you want to display this as part of the player.

This site breaks down how to get both the current and total time regardless of how you want to display it though using jQuery:

http://dev.opera.com/articles/view/custom-html5-video-player-with-css3-and-jquery/

This will also cover how to set it to a specific div. As philip has already mentioned, .currentTime will give you where you are in the video.

Loop through an array php

Ok, I know there is an accepted answer but… for more special cases you also could use this one:

array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);

Or in a more un-complex way:

function printItem($n){
    echo $n['filename'];
    echo $n['filepath'];
}

array_map('printItem', $array);

This will allow you to manipulate the data in an easier way.

Validating URL in Java

Using only standard API, pass the string to a URL object then convert it to a URI object. This will accurately determine the validity of the URL according to the RFC2396 standard.

Example:

public boolean isValidURL(String url) {

    try {
        new URL(url).toURI();
    } catch (MalformedURLException | URISyntaxException e) {
        return false;
    }

    return true;
}

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

What to do if :foo in its natural form contains slashes? You wouldn't want it to Isn't that the distinction the recommendation is attempting to preserve? It specifically notes,

The similarity to unix and other disk operating system filename conventions should be taken as purely coincidental, and should not be taken to indicate that URIs should be interpreted as file names.

If one was building an online interface to a backup program, and wished to express the path as a part of the URL path, it would make sense to encode the slashes in the file path, as that is not really part of the hierarchy of the resource - and more importantly, the route. /backups/2016-07-28content//home/dan/ loses the root of the filesystem in the double slash. Escaping the slashes is the appropriate way to distinguish, as I read it.

CSS 100% height with padding/margin

The better way is with the calc() property. So your case would look like:

#myDiv {
    width: calc(100% - 5px);
    height: calc(100% - 5px);
    padding: 5px;
}

Simple, clean, no workarounds. Just make sure you don't forget the space between the values and the operator (eg (100%-5px) that will break the syntax. Enjoy!

How to run mysql command on bash?

Use double quotes while using BASH variables.

mysql --user="$user" --password="$password" --database="$database" --execute="DROP DATABASE $user; CREATE DATABASE $database;"

BASH doesn't expand variables in single quotes.

How do I show a running clock in Excel?

See the below code (taken from this post)

Put this code in a Module in VBA (Developer Tab -> Visual Basic)

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub
Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
    TimerActive = False
End Sub
Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
    End If
End Sub

You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.

Private Sub Workbook_Open()
    Module1.StartTimer
End Sub

Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.

Convert a dataframe to a vector (by rows)

c(df$x, df$y)
# returns: 26 21 20 34 29 28

if the particular order is important then:

M = as.matrix(df)
c(m[1,], c[2,], c[3,])
# returns 26 34 21 29 20 28 

Or more generally:

m = as.matrix(df)
q = c()
for (i in seq(1:nrow(m))){
  q = c(q, m[i,])
}

# returns 26 34 21 29 20 28

Setting a WebRequest's body data

Update

See my other SO answer.


Original

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

R numbers from 1 to 100

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100))

gives

 -5 100

Instead, look at the : operator to give sequences (with a step size of one):

1:100

or you can use the seq function to have a bit more control. For example,

##Step size of 2
seq(1, 100, by=2)

or

##length.out: desired length of the sequence
seq(1, 100, length.out=5)

@Cacheable key on multiple method arguments

You can use a Spring-EL expression, for eg on JDK 1.7:

@Cacheable(value="bookCache", key="T(java.util.Objects).hash(#p0,#p1, #p2)")

jQuery get selected option value (not the text, but the attribute 'value')

 $(document ).ready(function() {
    $('select[name=selectorname]').change(function() { 
     alert($(this).val());});
 });

Why is access to the path denied?

I have found that this error can occur in DESIGN MODE as opposed to ? execution mode... If you are doing something such as creating a class member which requires access to an .INI or .HTM file (configuration file, help file) you might want to NOT initialize the item in the declaration, but initialize it later in FORM_Load() etc... When you DO initialize... Use a guard IF statement:

    /// <summary>FORM: BasicApp - Load</summary>
    private void BasicApp_Load(object sender, EventArgs e)
    {
        // Setup Main Form Caption with App Name and Config Control Info
        if (!DesignMode)
        {
            m_Globals = new Globals();
            Text = TGG.GetApplicationConfigInfo();
        }
    }

This will keep the MSVS Designer from trying to create an INI or HTM file when you are in design mode.

Column name or number of supplied values does not match table definition

for inserts it is always better to specify the column names see the following

DECLARE @Table TABLE(
        Val1 VARCHAR(MAX)
)

INSERT INTO @Table SELECT '1'

works fine, changing the table def to causes the error

DECLARE @Table TABLE(
        Val1 VARCHAR(MAX),
        Val2 VARCHAR(MAX)
)

INSERT INTO @Table SELECT '1'

Msg 213, Level 16, State 1, Line 6 Insert Error: Column name or number of supplied values does not match table definition.

But changing the above to

DECLARE @Table TABLE(
        Val1 VARCHAR(MAX),
        Val2 VARCHAR(MAX)
)

INSERT INTO @Table (Val1)  SELECT '1'

works. You need to be more specific with the columns specified

supply the structures and we can have a look

Jenkins Slave port number for firewall

A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.

You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.

If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

How do I format date and time on ssrs report?

If the date and time is in its own cell (aka textbox), then you should look at applying the format to the entire textbox. This will create cleaner exports to other formats; in particular, the value will export as a datetime value to Excel instead of a string.

Use the properties pane or dialog to set the format for the textbox to "MM/dd/yyyy hh:mm tt"

I would only use Ian's answer if the datetime is being concatenated with another string.

pip installing in global site-packages instead of virtualenv

Go to bin directory in your virtual environment and write like this:

./pip3 install <package-name>

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data,response,error in
        if error != nil{
            print(error!.localizedDescription)
            return
        }
        if let responseJSON = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String:AnyObject]{
            if let response_token:String = responseJSON["token"] as? String {
                print("Singleton Firebase Token : \(response_token)")
                completion(response_token)
            }
        }
    })
    task.resume()

Chrome Fullscreen API

I made a simple wrapper for the Fullscreen API, called screenfull.js, to smooth out the prefix mess and fix some inconsistencies in the different implementations. Check out the demo to see how the Fullscreen API works.

Recommended reading:

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

I'd add that in case of really odd behavior - where you spend a couple of hours saying WTF - try manually deleting the /webapps/yourwebapp/WEB-INF/classes directory. A java source file that was moved to another package will not have its compiled class file deleted - at least in the case of an exploded web-application on TC. This can seriously drive you crazy with unpredictable behavior, especially with an annotated servlet.

How to return a result (startActivityForResult) from a TabHost Activity?

http://tylenoly.wordpress.com/2010/10/27/how-to-finish-activity-with-results/

With a slight modification for "param_result"

/* Start Activity */
public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setClassName("com.thinoo.ActivityTest", "com.thinoo.ActivityTest.NewActivity");
    startActivityForResult(intent,90);
}
/* Called when the second activity's finished */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
    case 90:
        if (resultCode == RESULT_OK) {
            Bundle res = data.getExtras();
            String result = res.getString("param_result");
            Log.d("FIRST", "result:"+result);
        }
        break;
    }
}

private void finishWithResult()
{
    Bundle conData = new Bundle();
    conData.putString("param_result", "Thanks Thanks");
    Intent intent = new Intent();
    intent.putExtras(conData);
    setResult(RESULT_OK, intent);
    finish();
}

Python code to remove HTML tags from a string

global temp

temp =''

s = ' '

def remove_strings(text):

    global temp 

    if text == '':

        return temp

    start = text.find('<')

    end = text.find('>')

    if start == -1 and end == -1 :

        temp = temp + text

    return temp

newstring = text[end+1:]

fresh_start = newstring.find('<')

if newstring[:fresh_start] != '':

    temp += s+newstring[:fresh_start]

remove_strings(newstring[fresh_start:])

return temp

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

these are the commands:

git fetch origin
git merge origin/somebranch somebranch

if you do this on the second line:

git merge origin somebranch

it will try to merge the local master into your current branch.

The question, as I've understood it, was you fetched already locally and want to now merge your branch to the latest of the same branch.

Node.js: what is ENOSPC error and how to solve?

Run the below command to avoid ENOSPC:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

For Arch Linux add this line to /etc/sysctl.d/99-sysctl.conf:

fs.inotify.max_user_watches=524288

Then execute:

sysctl --system

This will also persist across reboots. Technical Details Source

How to debug in Django, the good way?

I just found wdb (http://www.rkblog.rk.edu.pl/w/p/debugging-python-code-browser-wdb-debugger/?goback=%2Egde_25827_member_255996401). It has a pretty nice user interface / GUI with all the bells and whistles. Author says this about wdb -

"There are IDEs like PyCharm that have their own debuggers. They offer similar or equal set of features ... However to use them you have to use those specific IDEs (and some of then are non-free or may not be available for all platforms). Pick the right tool for your needs."

Thought i'd just pass it on.

Also a very helpful article about python debuggers: https://zapier.com/engineering/debugging-python-boss/

Finally, if you'd like to see a nice graphical printout of your call stack in Django, checkout: https://github.com/joerick/pyinstrument. Just add pyinstrument.middleware.ProfilerMiddleware to MIDDLEWARE_CLASSES, then add ?profile to the end of the request URL to activate the profiler.

Can also run pyinstrument from command line or by importing as a module.

What is the difference between Forking and Cloning on GitHub?

In a nutshell, Forking is perhaps the same as "cloning under your GitHub ID/profile". A fork is anytime better than a clone, with a few exceptions, obviously. The forked repository is always being monitored/compared with the original repository unlike a cloned repository. That enables you to track the changes, initiate pull requests and also manually sync the changes made in the original repository with your forked one.

How to test if a string is JSON or not?

var parsedData;

try {
    parsedData = JSON.parse(data)
} catch (e) {
    // is not a valid JSON string
}

However, I will suggest to you that your http call / service should return always a data in the same format. So if you have an error, than you should have a JSON object that wrap this error:

{"error" : { "code" : 123, "message" : "Foo not supported" } } 

And maybe use as well as HTTP status a 5xx code.

ApiNotActivatedMapError for simple html page using google-places-api

To enable Api do this

  1. Go to API Manager
  2. Click on Overview
  3. Search for Google Maps JavaScript API(Under Google Maps APIs). Click on that
  4. You will find Enable button there. Click to enable API.

OR You can try this url: Maps JavaScript API

Hope this will solve the problem of enabling API.

Invalid column name sql error

You problem is that your string are unquoted. Which mean that they are interpreted by your database engine as a column name.

You need to create parameters in order to pass your value to the query.

 cmd.CommandText = "INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address);";
 cmd.Parameters.AddWithValue("@Name", txtName.Text);
 cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
 cmd.Parameters.AddWithValue("@Address", txtAddress.Text);

How to use default Android drawables

To use the default android drawable resource, no need copy anything.. you can just import it first with..

import android.R;

but i will make your own resources will have an error if you want to use it. The error will be something like:

R. cannot be resolved

So, I prefer not to import android.R but import *my.own.package*.R;

then when I can normally use my own resource with R.drawable.*something* without error, and put android.R.*something_default* to use the default android resources.

Simple way to sort strings in the (case sensitive) alphabetical order

Simply use

java.util.Collections.sort(list)

without String.CASE_INSENSITIVE_ORDER comparator parameter.

Why is the Android emulator so slow? How can we speed up the Android emulator?

To add further information to this.

I have recently upgraded my Ubuntu installation to Ubuntu 10.04 LTS (Lucid Lynx) which in turn updated my Java version to:

Java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

And now the emulator (although takes a while to start) seems to be running faster than previously.

It might be worth people upgrading their JVM.

Reading a key from the Web.Config using ConfigurationManager

with assuming below setting in .config file:

<configuration>
   <appSettings>
     <add key="PFUserName" value="myusername"/>
     <add key="PFPassWord" value="mypassword"/>
   </appSettings> 
</configuration>

try this:

public class myController : Controller
{
    NameValueCollection myKeys = ConfigurationManager.AppSettings;

    public void MyMethod()
    {
        var myUsername = myKeys["PFUserName"];
        var myPassword = myKeys["PFPassWord"];
    }
}

How to convert an ASCII character into an int in C

Use the ASCII to Integer atoi() function which accepts a string and converts it into an integer:

#include <stdlib.h>

int num = atoi("23"); // 23

If the string contains a decimal, the number will be truncated:

int num = atoi("23.21"); // 23

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

Not really, but you can emulate them to some extend, for example:

int * array = new int[10000000];
try {
  // Some code that can throw exceptions
  // ...
  throw std::exception();
  // ...
} catch (...) {
  // The finally-block (if an exception is thrown)
  delete[] array;
  // re-throw the exception.
  throw; 
}
// The finally-block (if no exception was thrown)
delete[] array;

Note that the finally-block might itself throw an exception before the original exception is re-thrown, thereby discarding the original exception. This is the exact same behavior as in a Java finally-block. Also, you cannot use return inside the try&catch blocks.

How do I Merge two Arrays in VBA?

Here's a version that uses a collection object to combine two 1-d arrays and pass them to a 3rd array. Doesn't work for multi-dimensional arrays.

Function joinArrays(arr1 As Variant, arr2 As Variant) As Variant
 Dim arrToReturn() As Variant, myCollection As New Collection
 For Each x In arr1: myCollection.Add x: Next
 For Each y In arr2: myCollection.Add y: Next

 ReDim arrToReturn(1 To myCollection.Count)
 For i = 1 To myCollection.Count: arrToReturn(i) = myCollection.Item(i): Next
 joinArrays = arrToReturn
End Function

The project cannot be built until the build path errors are resolved.

just check if any unnecessary Jars are added in your library or not. if yes, then simply remove that jars from your library and clean your project once. Its worked for me.

Where is database .bak file saved from SQL Server Management Studio?

If the backup wasn't created in the default location, you can use this T-SQL (run this in SSMS) to find the file path for the most recent backup for all DBs on your SQL Server instance:

SELECT  DatabaseName = x.database_name,
        LastBackupFileName = x.physical_device_name,
        LastBackupDatetime = x.backup_start_date
FROM (  SELECT  bs.database_name,
                bs.backup_start_date,
                bmf.physical_device_name,
                  Ordinal = ROW_NUMBER() OVER( PARTITION BY bs.database_name ORDER BY bs.backup_start_date DESC )
          FROM  msdb.dbo.backupmediafamily bmf
                  JOIN msdb.dbo.backupmediaset bms ON bmf.media_set_id = bms.media_set_id
                  JOIN msdb.dbo.backupset bs ON bms.media_set_id = bs.media_set_id
          WHERE   bs.[type] = 'D'
                  AND bs.is_copy_only = 0 ) x
WHERE x.Ordinal = 1
ORDER BY DatabaseName;

Matplotlib legends in subplot

This does what you want and overcomes some of the problems in other answers:

import matplotlib.pyplot as plt

labels = ["HHZ 1", "HHN", "HHE"]
colors = ["r","g","b"]

f,axs = plt.subplots(3, sharex=True, sharey=True)

# ---- loop over axes ----
for i,ax in enumerate(axs):
  axs[i].plot([0,1],[1,0],color=colors[i],label=labels[i])
  axs[i].legend(loc="upper right")

plt.show()

... produces ... subplots

How can I lock a file using java (if possible)

Use this for unix if you are transferring using winscp or ftp:

public static void isFileReady(File entry) throws Exception {
        long realFileSize = entry.length();
        long currentFileSize = 0;
        do {
            try (FileInputStream fis = new FileInputStream(entry);) {
                currentFileSize = 0;
                while (fis.available() > 0) {
                    byte[] b = new byte[1024];
                    int nResult = fis.read(b);
                    currentFileSize += nResult;
                    if (nResult == -1)
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("currentFileSize=" + currentFileSize + ", realFileSize=" + realFileSize);
        } while (currentFileSize != realFileSize);
    }

How to store a dataframe using Pandas

Numpy file formats are pretty fast for numerical data

I prefer to use numpy files since they're fast and easy to work with. Here's a simple benchmark for saving and loading a dataframe with 1 column of 1million points.

import numpy as np
import pandas as pd

num_dict = {'voltage': np.random.rand(1000000)}
num_df = pd.DataFrame(num_dict)

using ipython's %%timeit magic function

%%timeit
with open('num.npy', 'wb') as np_file:
    np.save(np_file, num_df)

the output is

100 loops, best of 3: 5.97 ms per loop

to load the data back into a dataframe

%%timeit
with open('num.npy', 'rb') as np_file:
    data = np.load(np_file)

data_df = pd.DataFrame(data)

the output is

100 loops, best of 3: 5.12 ms per loop

NOT BAD!

CONS

There's a problem if you save the numpy file using python 2 and then try opening using python 3 (or vice versa).

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

I'm using Mac OS X Yosemite and Netbeans 8.02, I got the same error and the simple solution I have found is like above, this is useful when you need to include native library in the project. So do the next for Netbeans:

1.- Right click on the Project
2.- Properties
3.- Click on RUN
4.- VM Options: java -Djava.library.path="your_path"
5.- for example in my case: java -Djava.library.path=</Users/Lexynux/NetBeansProjects/NAO/libs>
6.- Ok

I hope it could be useful for someone. The link where I found the solution is here: java.library.path – What is it and how to use

Why are there two ways to unstage a file in Git?

I'm surprised noone mentioned the git reflog (http://git-scm.com/docs/git-reflog):

# git reflog
<find the place before your staged anything>
# git reset HEAD@{1}

The reflog is a git history that not only tracks the changes to the repo, but also tracks the user actions (Eg. pull, checkout to different branch, etc) and allows to undo those actions. So instead of unstaging the file that was mistakingly staged, where you can revert to the point where you didn't stage the files.

This is similar to git reset HEAD <file> but in certain cases may be more granular.

Sorry - not really answering your question, but just pointing yet another way to unstage files that I use quite often (I for one like answers by Ryan Stewart and waldyrious very much.) ;) I hope it helps.

How to call Android contacts list?

The complete code is given below

    package com.testingContect;

    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.ContactsContract;
    import android.provider.Contacts.People;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class testingContect extends Activity implements OnClickListener{
    /** Called when the activity is first created. */

    EditText ed;
    Button bt;
    int PICK_CONTACT;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bt=(Button)findViewById(R.id.button1);
        ed =(EditText)findViewById(R.id.editText1);
        ed.setOnClickListener(this);
        bt.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {

        switch(v.getId())
        {
        case R.id.button1:

            break;
        case R.id.editText1:
             Intent intent = new Intent(Intent.ACTION_PICK);
              intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
              startActivityForResult(intent, PICK_CONTACT);


            break;

        }

    }
    public void onActivityResult(int requestCode, int resultCode, Intent intent) 
    {

      if (requestCode == PICK_CONTACT)
      {         
          Cursor cursor =  managedQuery(intent.getData(), null, null, null, null);
          cursor.moveToNext();
          String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
           String  name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

          Toast.makeText(this, "Contect LIST  =  "+name, Toast.LENGTH_LONG).show(); 
      }
    }//onActivityResult
}//class ends

Customize Bootstrap checkboxes

You have to use Bootstrap version 4 with the custom-* classes to get this style:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- example code of the bootstrap website -->_x000D_
<label class="custom-control custom-checkbox">_x000D_
  <input type="checkbox" class="custom-control-input">_x000D_
  <span class="custom-control-indicator"></span>_x000D_
  <span class="custom-control-description">Check this custom checkbox</span>_x000D_
</label>_x000D_
_x000D_
<!-- your code with the custom classes of version 4 -->_x000D_
<div class="checkbox">_x000D_
  <label class="custom-control custom-checkbox">_x000D_
    <input type="checkbox" [(ngModel)]="rememberMe" name="rememberme" class="custom-control-input">_x000D_
    <span class="custom-control-indicator"></span>_x000D_
    <span class="custom-control-description">Remember me</span>_x000D_
  </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Documentation: https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios-1


Custom checkbox style on Bootstrap version 3?
Bootstrap version 3 doesn't have custom checkbox styles, but you can use your own. In this case: How to style a checkbox using CSS?

These custom styles are only available since version 4.

Can an ASP.NET MVC controller return an Image?

To expland on Dyland's response slightly:

Three classes implement the FileResult class:

System.Web.Mvc.FileResult
      System.Web.Mvc.FileContentResult
      System.Web.Mvc.FilePathResult
      System.Web.Mvc.FileStreamResult

They're all fairly self explanatory:

  • For file path downloads where the file exists on disk, use FilePathResult - this is the easiest way and avoids you having to use Streams.
  • For byte[] arrays (akin to Response.BinaryWrite), use FileContentResult.
  • For byte[] arrays where you want the file to download (content-disposition: attachment), use FileStreamResult in a similar way to below, but with a MemoryStream and using GetBuffer().
  • For Streams use FileStreamResult. It's called a FileStreamResult but it takes a Stream so I'd guess it works with a MemoryStream.

Below is an example of using the content-disposition technique (not tested):

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult GetFile()
    {
        // No need to dispose the stream, MVC does it for you
        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "myimage.png");
        FileStream stream = new FileStream(path, FileMode.Open);
        FileStreamResult result = new FileStreamResult(stream, "image/png");
        result.FileDownloadName = "image.png";
        return result;
    }

How can I hide select options with JavaScript? (Cross browser)

As has been said, you can't display:none individual <option>s, because they're not the right kind of DOM elements.

You can set .prop('disabled', true), but this only grays out the elements and makes them unselectable -- they still take up space.

One solution I use is to .detach() the <select> into a global variable on page load, then add back only the <option>s you want on demand. Something like this (http://jsfiddle.net/mblase75/Afe2E/):

var $sel = $('#sel option').detach(); // global variable

$('a').on('click', function (e) {
    e.preventDefault();
    var c = 'name-of-class-to-show';
    $('#sel').empty().append( $sel.filter('.'+c) );
});

At first I thought you'd have to .clone() the <option>s before appending them, but apparently not. The original global $sel is unaltered after the click code is run.


If you have an aversion to global variables, you could store the jQuery object containing the options as a .data() variable on the <select> element itself (http://jsfiddle.net/mblase75/nh5eW/):

$('#sel').data('options', $('#sel option').detach()); // data variable

$('a').on('click', function (e) {
    e.preventDefault();
    var $sel = $('#sel').data('options'), // jQuery object
        c = 'name-of-class-to-show';
    $('#sel').empty().append( $sel.filter('.'+c) );
});

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

"python" not recognized as a command

emphasis: Remember to always RESTART the CMD WINDOW after setting the PATH environmental variable for it to take effect!

Check an integer value is Null in c#

As stated above, ?? is the null coalescing operator. So the equivalent to

(Age ?? 0) == 0

without using the ?? operator is

(!Age.HasValue) || Age == 0

However, there is no version of .Net that has Nullable< T > but not ??, so your statement,

Now i have to check in a older application where the declaration part is not in ternary.

is doubly invalid.

How to resolve the C:\fakepath?

Hy there , in my case i am using asp.net development environment, so i was want to upload those data in asynchronus ajax request , in [webMethod] you can not catch the file uploader since it is not static element , so i had to make a turnover for such solution by fixing the path , than convert the wanted image into bytes to save it in DB .

Here is my javascript function , hope it helps you:

function FixPath(Path)
         {
             var HiddenPath = Path.toString();
             alert(HiddenPath.indexOf("FakePath"));

             if (HiddenPath.indexOf("FakePath") > 1)
             {
                 var UnwantedLength = HiddenPath.indexOf("FakePath") + 7;
                 MainStringLength = HiddenPath.length - UnwantedLength;
                 var thisArray =[];
                 var i = 0;
                 var FinalString= "";
                 while (i < MainStringLength)
                 {
                     thisArray[i] = HiddenPath[UnwantedLength + i + 1];
                     i++;
                 }
                 var j = 0;
                 while (j < MainStringLength-1)
                 {
                     if (thisArray[j] != ",")
                     {
                         FinalString += thisArray[j];
                     }
                     j++;
                 }
                 FinalString = "~" + FinalString;
                 alert(FinalString);
                 return FinalString;
             }
             else
             {
                 return HiddenPath;
             }
         }

here only for testing :

 $(document).ready(function () {
             FixPath("hakounaMatata:/7ekmaTa3mahaLaziz/FakePath/EnsaLmadiLiYghiz");
         });
// this will give you : ~/EnsaLmadiLiYghiz

How to create correct JSONArray in Java using JSONObject

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }

How can I simulate a print statement in MySQL?

This is an old post, but thanks to this post I have found this:

\! echo 'some text';

Tested with MySQL 8 and working correctly. Cool right? :)

How to test if a file is a directory in a batch script?

If your objective is to only process directories then this will be useful.

This is taken from the https://ss64.com/nt/for_d.html

Example... List every subfolder, below the folder C:\Work\ that has a name starting with "User":

CD \Work
FOR /D /r %%G in ("User*") DO Echo We found

FOR /D or FOR /D /R

@echo off
cd /d "C:\your directory here"
for /d /r %%A in ("*") do echo We found a folder: %%~nxA
pause

Remove /r to only go one folder deep. The /r switch is recursive and undocumented in the command below.

The for /d help taken from command for /?

FOR /D %variable IN (set) DO command [command-parameters]

If set contains wildcards, then specifies to match against directory names instead of file names.

Appending a line to a file only if it does not already exist

Just keep it simple :)

grep + echo should suffice:

grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar

Edit: incorporated @cerin and @thijs-wouters suggestions.

How to send HTML-formatted email?

Setting isBodyHtml to true allows you to use HTML tags in the message body:

msg = new MailMessage("[email protected]",
                "[email protected]", "Message from PSSP System",
                "This email sent by the PSSP system<br />" +
                "<b>this is bold text!</b>");

msg.IsBodyHtml = true;

Foreach loop, determine which is the last iteration of the loop

We can check last item in loop.

foreach (Item result in Model.Results)
{
    if (result==Model.Results.Last())
    {
        // do something different with the last item
    }
}

Naming threads and thread-pools of ExecutorService

You can also change the name of your thread afterwards, while the thread is executed:

Thread.currentThread().setName("FooName");

That could be of interest if for instance you're using the same ThreadFactory for different type of tasks.

Create a temporary table in MySQL with an index from a select

Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...

CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY    
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;

CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid), 
INDEX(tmpid))  
SELECT * FROM tmpLivecheck;

... solved my problem.

Greetings...

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

If you want to uninstall when connected to single device/emulator then use below command

adb uninstall <package name>

else with multiple devices then use below command

adb -s <device ID> uninstall <package name>

How to make child process die after parent exits?

This solution worked for me:

  • Pass stdin pipe to child - you don't have to write any data into the stream.
  • Child reads indefinitely from stdin until EOF. An EOF signals that the parent has gone.
  • This is foolproof and portable way to detect when the parent has gone. Even if parent crashes, OS will close the pipe.

This was for a worker-type process whose existence only made sense when the parent was alive.

Resource interpreted as Document but transferred with MIME type application/zip

The problem

I had similar problem. Got message in js

Resource interpreted as Document but transferred with MIME type text/csv

But I also got message in chrome console

Mixed Content: The site at 'https://my-site/' was loaded over a secure connection, but the file at 'https://my-site/Download?id=99a50c7b' was redirected through an insecure connection. This file should be served over HTTPS. This download has been blocked

It says here that you need to use an secure connection (but scheme is https in message already, strangely...).

The problem is that href for file downloading builded on server side. And this href used http in my case.

The solution

So I changed scheme to https when build href for file downloading.

Why use $_SERVER['PHP_SELF'] instead of ""

The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".

There is no reason to use $_SERVER['PHP_SELF'], and # doesn't submit the form at all (unless there is a submit event handler attached that handles the submission).

Reload nginx configuration

If your system has systemctl

sudo systemctl reload nginx

If your system supports service (using debian/ubuntu) try this

sudo service nginx reload

If not (using centos/fedora/etc) you can try the init script

sudo /etc/init.d/nginx reload

Number of days between two dates in Joda-Time

Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:

Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.

// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
                               end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
                               end.toLocalDate()).getDays());
// prints 1

Going via a LocalDate sidesteps the whole issue.

Count with IF condition in MySQL query

Better still (or shorter anyway):

SUM(ccc_news_comments.id = 'approved')

This works since the Boolean type in MySQL is represented as INT 0 and 1, just like in C. (May not be portable across DB systems though.)

As for COALESCE() as mentioned in other answers, many language APIs automatically convert NULL to '' when fetching the value. For example with PHP's mysqli interface it would be safe to run your query without COALESCE().

How to convert Seconds to HH:MM:SS using T-SQL

This is what I use (typically for html table email reports)

declare @time int, @hms varchar(20)
set @time = 12345
set @hms = cast(cast((@Time)/3600 as int) as varchar(3)) 
  +':'+ right('0'+ cast(cast(((@Time)%3600)/60 as int) as varchar(2)),2) 
  +':'+ right('0'+ cast(((@Time)%3600)%60 as varchar(2)),2) +' (hh:mm:ss)'
select @hms

How to use the unsigned Integer in Java 8 and Java 9?

    // Java 8
    int vInt = Integer.parseUnsignedInt("4294967295");
    System.out.println(vInt); // -1
    String sInt = Integer.toUnsignedString(vInt);
    System.out.println(sInt); // 4294967295

    long vLong = Long.parseUnsignedLong("18446744073709551615");
    System.out.println(vLong); // -1
    String sLong = Long.toUnsignedString(vLong);
    System.out.println(sLong); // 18446744073709551615

    // Guava 18.0
    int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
    System.out.println(vIntGu); // -1
    String sIntGu = UnsignedInts.toString(vIntGu);
    System.out.println(sIntGu); // 4294967295

    long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
    System.out.println(vLongGu); // -1
    String sLongGu = UnsignedLongs.toString(vLongGu);
    System.out.println(sLongGu); // 18446744073709551615

    /**
     Integer - Max range
     Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
     Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1

     Long - Max range
     Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
     Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
     */

PHPMailer character encoding issues

To avoid problems of character encoding in sending emails using the class PHPMailer we can configure it to send it with UTF-8 character encoding using the "CharSet" parameter, as we can see in the following Php code:

$mail = new PHPMailer();
$mail->From = '[email protected]';
$mail->FromName = 'Mi nombre';
$mail->AddAddress('[email protected]');
$mail->Subject = 'Prueba';
$mail->Body = '';
$mail->IsHTML(true);


// Active condition utf-8
$mail->CharSet = 'UTF-8';


// Send mail
$mail->Send();

How do I ignore all files in a folder with a Git repository in Sourcetree?

  • Ignore all files in folder with Git in Sourcetree:

Ignore all files in folder with Git in Sourcetree

SHA-256 or MD5 for file integrity

It is technically approved that MD5 is faster than SHA256 so in just verifying file integrity it will be sufficient and better for performance.

You are able to checkout the following resources:

Can I style an image's ALT text with CSS?

Sure you can!

http://jsfiddle.net/VfTGW/

I do this as a fallback for header logo images, I think some versions of IE will not abide. Edit: Or Chrome apparently - I don't even see alt text in the demo(?). Firefox works well however.

_x000D_
_x000D_
img {_x000D_
  color: green;_x000D_
  font: 40px Impact;_x000D_
}
_x000D_
<img src="404" alt="Alt Text">
_x000D_
_x000D_
_x000D_

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

Downgrade your java version.Whatever system or ide.

Make sure java version is not higher than 8

In my case.I change the ide java verion.This solves my issue. enter image description here

Error 'tunneling socket' while executing npm install

If in case you are using ubuntu trusty 14.0 then search for Network and select Network Proxy and make it none. Now proxy may still be set in system environment variables. check

env|grep -i proxy

you may get output as

http_proxy=http://192.168.X.X:8080/
ftp_proxy=ftp://192.168.X.X:8080/
socks_proxy=socks://192.168.X.X:8080/
https_proxy=https://192.168.X.X:8080/

unset these environment variable as:

unset(http_proxy)

and in this way unset all. Now run npm install ensuring user must have permission to make node_modules folder where you are installing module.

How to change webservice url endpoint?

I wouldn't go so far as @Femi to change the existing address property. You can add new services to the definitions section easily.

<wsdl:service name="serviceMethodName_2">
  <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
    <soap:address location="http://new_end_point_adress"/>
  </wsdl:port>
</wsdl:service>

This doesn't require a recompile of the WSDL to Java and making updates isn't any more difficult than if you used the BindingProvider option (which didn't work for me btw).

Where does MySQL store database files on Windows and what are the names of the files?

C:\Program Files\MySQL\MySQL Workbench 6.3 CE\sys

paste URLin to window file, and get Tables, Procedures, Functions from this directory

How to plot two histograms together in R?

Plotly's R API might be useful for you. The graph below is here.

library(plotly)
#add username and key
p <- plotly(username="Username", key="API_KEY")
#generate data
x0 = rnorm(500)
x1 = rnorm(500)+1
#arrange your graph
data0 = list(x=x0,
         name = "Carrots",
         type='histogramx',
         opacity = 0.8)

data1 = list(x=x1,
         name = "Cukes",
         type='histogramx',
         opacity = 0.8)
#specify type as 'overlay'
layout <- list(barmode='overlay',
               plot_bgcolor = 'rgba(249,249,251,.85)')  
#format response, and use 'browseURL' to open graph tab in your browser.
response = p$plotly(data0, data1, kwargs=list(layout=layout))

url = response$url
filename = response$filename

browseURL(response$url)

Full disclosure: I'm on the team.

Graph

pod install -bash: pod: command not found

The best solution for Big Sur is posted on Redit by _fgmx

Go into Xcode 12 preferences Click locations Select Xcode 12 for Developer tools/command line tools Install cocoapods for Xcode 12: sudo gem install cocoapods

Equivalent VB keyword for 'break'

In both Visual Basic 6.0 and VB.NET you would use:

  • Exit For to break from For loop
  • Wend to break from While loop
  • Exit Do to break from Do loop

depending on the loop type. See Exit Statements for more details.

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

How do I rewrite URLs in a proxy response in NGINX

You can use the following nginx configuration example:

upstream adminhost {
  server adminhostname:8080;
}

server {
  listen 80;

  location ~ ^/admin/(.*)$ {
    proxy_pass http://adminhost/$1$is_args$args;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }
}

How to print something to the console in Xcode?

In some environments, NSLog() will be unresponsive. But there are other ways to get output...

NSString* url = @"someurlstring";
printf("%s", [url UTF8String]);

By using printf with the appropriate parameters, we can display things this way. This is the only way I have found to work on online Objective-C sandbox environments.

Execute the setInterval function without delay the first time

It's simplest to just call the function yourself directly the first time:

foo();
setInterval(foo, delay);

However there are good reasons to avoid setInterval - in particular in some circumstances a whole load of setInterval events can arrive immediately after each other without any delay. Another reason is that if you want to stop the loop you have to explicitly call clearInterval which means you have to remember the handle returned from the original setInterval call.

So an alternative method is to have foo trigger itself for subsequent calls using setTimeout instead:

function foo() {
   // do stuff
   // ...

   // and schedule a repeat
   setTimeout(foo, delay);
}

// start the cycle
foo();

This guarantees that there is at least an interval of delay between calls. It also makes it easier to cancel the loop if required - you just don't call setTimeout when your loop termination condition is reached.

Better yet, you can wrap that all up in an immediately invoked function expression which creates the function, which then calls itself again as above, and automatically starts the loop:

(function foo() {
    ...
    setTimeout(foo, delay);
})();

which defines the function and starts the cycle all in one go.

Programmatically extract contents of InstallShield setup.exe

The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:

% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
  extracting ikernel.dll
  extracting IsProBENT.tlb
  ....
  extracting IScript.dll
  extracting iKernel.rgs

All done, no errors.

How to convert string to date to string in Swift iOS?

//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  

What is the difference between static func and class func in Swift?

To be clearer, I make an example here,

class ClassA {
  class func func1() -> String {
    return "func1"
  }

  static func func2() -> String {
    return "func2"
  }

  /* same as above
  final class func func2() -> String {
    return "func2"
  }
  */
}

static func is same as final class func

Because it is final, we can not override it in subclass as below:

class ClassB : ClassA {
  override class func func1() -> String {
    return "func1 in ClassB"
  }

  // ERROR: Class method overrides a 'final` class method
  override static func func2() -> String {
    return "func2 in ClassB"
  }
}

Definition of a Balanced Tree

There's no difference between these two things. Think about it.

Let's take a simpler definition, "A positive number is even if it is zero or that number minus two is even." Does this say 8 is even if 6 is even? Or does this say 8 is even if 6, 4, 2, and 0 are even?

There's no difference. If it says 8 is even if 6 is even, it also says 6 is even if 4 is even. And thus it also says 4 is even if 2 is even. And thus it says 2 is even if 0 is even. So if it says 8 is even if 6 is even, it (indirectly) says 8 is even if 6, 4, 2, and 0 are even.

It's the same thing here. Any indirect sub-tree can be found by a chain of direct sub-trees. So even if it only applies directly to direct sub-trees, it still applies indirectly to all sub-trees (and thus all nodes).

Links not going back a directory?

There are two type of paths: absolute and relative. This is basically the same for files in your hard disc and directories in a URL.

Absolute paths start with a leading slash. They always point to the same location, no matter where you use them:

  • /pages/en/faqs/faq-page1.html

Relative paths are the rest (all that do not start with slash). The location they point to depends on where you are using them

  • index.html is:
    • /pages/en/faqs/index.html if called from /pages/en/faqs/faq-page1.html
    • /pages/index.html if called from /pages/example.html
    • etc.

There are also two special directory names: . and ..:

  • . means "current directory"
  • .. means "parent directory"

You can use them to build relative paths:

  • ../index.html is /pages/en/index.html if called from /pages/en/faqs/faq-page1.html
  • ../../index.html is /pages/index.html if called from /pages/en/faqs/faq-page1.html

Once you're familiar with the terms, it's easy to understand what it's failing and how to fix it. You have two options:

  • Use absolute paths
  • Fix your relative paths

Concatenating multiple text files into a single file in Bash

The most upvoted answers will fail if the file list is too long.

A more portable solution would be using fd

fd -e txt -d 1 -X awk 1 > combined.txt

-d 1 limits the search to the current directory. If you omit this option then it will recursively find all .txt files from the current directory.
-X (otherwise known as --exec-batch) executes a command (awk 1 in this case) for all the search results at once.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

I've used ng-change:

_x000D_
_x000D_
Date.prototype.addDays = function(days) {_x000D_
  var dat = new Date(this.valueOf());_x000D_
  dat.setDate(dat.getDate() + days);_x000D_
  return dat;_x000D_
}_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.controller('DateController', ['$rootScope', '$scope',_x000D_
  function($rootScope, $scope) {_x000D_
    function init() {_x000D_
      $scope.startDate = new Date();_x000D_
      $scope.endDate = $scope.startDate.addDays(14);_x000D_
    }_x000D_
_x000D_
_x000D_
    function load() {_x000D_
      alert($scope.startDate);_x000D_
      alert($scope.endDate);_x000D_
    }_x000D_
_x000D_
    init();_x000D_
    // public methods_x000D_
    $scope.load = load;_x000D_
    $scope.setStart = function(date) {_x000D_
      $scope.startDate = date;_x000D_
    };_x000D_
    $scope.setEnd = function(date) {_x000D_
      $scope.endDate = date;_x000D_
    };_x000D_
_x000D_
  }_x000D_
]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div data-ng-controller="DateController">_x000D_
  <label class="item-input"> <span class="input-label">Start</span>_x000D_
    <input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
  </label>_x000D_
  <label class="item-input"> <span class="input-label">End</span>_x000D_
    <input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
  </label>_x000D_
  <button button="button" ng-disabled="planningForm.$invalid" ng-click="load()" class="button button-positive">_x000D_
    Run_x000D_
  </button>_x000D_
</div <label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
  <input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>
_x000D_
_x000D_
_x000D_

The transaction log for the database is full

This is an old school approach, but if you're performing an iterative update or insert operation in SQL, something that runs for a long time, it's a good idea to periodically (programmatically) call "checkpoint". Calling "checkpoint" causes SQL to write to disk all of those memory-only changes (dirty pages, they're called) and items stored in the transaction log. This has the effect of cleaning out your transaction log periodically, thus preventing problems like the one described.

CSS-Only Scrollable Table with fixed headers

Ive achieved this easily using this code :

So you have a structure like this :

<table>
<thead><tr></tr></thead>
<tbody><tr></tr></tbody>
</table>

just style the thead with :

<style>
thead{ 
    position: -webkit-sticky;
    position: -moz-sticky;
    position: -ms-sticky;
    position: -o-sticky;
    position: sticky;
    top: 0px;
}
</style>

Three things to consider :

First, this property is new. It’s not supported at all, apart from the beta builds of Webkit-based browsers. So caveat formator. Again, if you really want for your users to benefit from sticky headers, go with a javascript implementation.

Second, if you do use it, you’ll need to incorporate vendor prefixes. Perhaps position: sticky will work one day. For now, though, you need to use position:-webkit-sticky (and the others; check the block of css further up in this post).

Third, there aren’t any positioning defaults at the moment, so you need to at least include top: 0; in the same css declaration as the position:-webkit-sticky. Otherwise, it’ll just scroll off-screen.

How can you check for a #hash in a URL using JavaScript?

Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.

What most people seem to miss is that those same URL properties are also available to anchor elements:

// To process anchors on click    
jQuery('a').click(function () {
   if (this.hash) {
      // Clicked anchor has a hash
   } else {
      // Clicked anchor does not have a hash
   }
});

// To process anchors without waiting for an event
jQuery('a').each(function () {
   if (this.hash) {
      // Current anchor has a hash
   } else {
      // Current anchor does not have a hash
   }
});

How to "test" NoneType in python?

I hope this example will be helpful for you)

print(type(None))  # NoneType

So, you can check type of the variable name

# Example
name = 12  # name = None

if type(name) is type(None):
    print("Can't find name")
else:
    print(name)

How do I use HTML as the view engine in Express?

Answer is very Simple. You Must use app.engine('html') to render *.html Pages. try this.It must Solve the Problem.

app.set('views', path.join(__dirname, 'views'));
**// Set EJS View Engine**
app.set('view engine','ejs');
**// Set HTML engine**
app.engine('html', require('ejs').renderFile);

the .html file Will work

How to set min-height for bootstrap container

Have you tried height: auto; on your .container div?

Here is a fiddle, if you change img height, container height will adjust to it.

EDIT

So if you "can't" change the inline min-height, you can overwrite the inline style with an !important parameter. It's not the cleanest way, but it solves your problem.

add to your .containerclass this line

min-height:0px !important;

I've updated my fiddle to give you an example.

mysqldump data only

This should work:

# To export to file (data only)
mysqldump -u [user] -p[pass] --no-create-info mydb > mydb.sql

# To export to file (structure only)
mysqldump -u [user] -p[pass] --no-data mydb > mydb.sql

# To import to database
mysql -u [user] -p[pass] mydb < mydb.sql

NOTE: there's no space between -p & [pass]

Clearing my form inputs after submission

The easiest way would be to set the value of the form element. If you're using jQuery (which I would highly recommend) you can do this easily with

$('#element-id').val('')

For all input elements in the form this may work (i've never tried it)

$('#form-id').children('input').val('')

Note that .children will only find input elements one level down. If you need to find grandchildren or such .find() should work.

There may be a better way however this should work for you.

Import functions from another js file. Javascript

From a quick glance on MDN I think you may need to include the .js at the end of your file name so the import would read import './course.js' instead of import './course'

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Image is not showing in browser?

I don't know where you're running the site from on your computer, but you have an absolute file path to your C drive: C:\Users\VIRK\Desktop\66.jpg

Try this instead:

<img  src="[PATH_RELATIVE_TO_ROOT]/66.jpg" width="400" height="400" />

UPDATE:

I don't know what your $PROJECTHOME is set to. But say for example your site files are located at C:\Users\VIRK\MyWebsite. And let's say your images are in an 'images' folder within your main site, like so: C:\Users\VIRK\MyWebsite\images.

Then in your HTML you can simply reference the image within the images folder relative to the site, like so:

<img  src="images/66.jpg" width="400" height="400" />

Or, assuming you're hosting at the root of localhost and not within another virtual directory, you can do this (note the slash in the beginning):

<img  src="/images/66.jpg" width="400" height="400" />

How to fix the error "Windows SDK version 8.1" was not found?

I faced this problem too. Re-ran the Visual Studio 2017 Installer, go to 'Individual Components' and select Windows 8.1 SDK. Go back to to the project > Right click and Re-target to match the SDK required as shown below:enter image description here

The difference between fork(), vfork(), exec() and clone()

  • vfork() is an obsolete optimization. Before good memory management, fork() made a full copy of the parent's memory, so it was pretty expensive. since in many cases a fork() was followed by exec(), which discards the current memory map and creates a new one, it was a needless expense. Nowadays, fork() doesn't copy the memory; it's simply set as "copy on write", so fork()+exec() is just as efficient as vfork()+exec().

  • clone() is the syscall used by fork(). with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.

Google Maps JavaScript API RefererNotAllowedMapError

This worked for me. There are 2 major categories of restrictions under api key settings:

  • Application restrictions
  • API restrictions

Application restrictions:

At the bottom in the Referrer section add your website url " http://www.grupocamaleon.com/boceto/aerial-simple.html " .There are example rules on the right hand side of the section based on various requirements.

Application restrictions

API restrictions:

Under API restrictions you have to explicitly select 'Maps Javascript API' from the dropdown list since our unique key will only be used for calling the Google maps API(probably) and save it as you can see in the below snap. I hope this works for you.....worked for me

enter image description here

Check your Script:

Also the issue may arise due to improper key feeding inside the script tag. It should be something like:

  <script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap"
  type="text/javascript"></script>

How to disable RecyclerView scrolling?

At activity's onCreate method, you can simply do:

recyclerView.stopScroll()

and it stops scrolling.

Windows batch script launch program and exit console

Try to start path\to\cygwin\bin\bash.exe

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Remove object from a list of objects in python

If you want to remove multiple object from a list. There are various ways to delete an object from a list

Try this code. a is list with all object, b is list object you want to remove.

example :

a = [1,2,3,4,5,6]
b = [2,3]

for i in b:
   if i in a:
      a.remove(i)

print(a)

the output is [1,4,5,6] I hope, it will work for you

Make cross-domain ajax JSONP request with jQuery

Your JSON-data contains the property Data, but you're accessing data. It's case sensitive

function jsonparser1() {
    $.ajax({
        type: "GET",
        url: "http://10.211.2.219:8080/SampleWebService/sample.do",
        dataType: "json",
        success: function (xml) {
            alert(xml.Data[0].City);
            result = xml.Code;
            document.myform.result1.value = result;
        },
    });
}        

EDIT Also City and Code is in the wrong case. (Thanks @Christopher Kenney)

EDIT2 It should also be json, and not jsonp (at least in this case)

UPDATE According to your latest comment, you should read this answer: https://stackoverflow.com/a/11736771/325836 by Abdul Munim

How to read the content of a file to a string in C?

If you're using glib, then you can use g_file_get_contents;

gchar *contents;
GError *err = NULL;

g_file_get_contents ("foo.txt", &contents, NULL, &err);
g_assert ((contents == NULL && err != NULL) || (contents != NULL && err == NULL));
if (err != NULL)
  {
    // Report error to user, and free error
    g_assert (contents == NULL);
    fprintf (stderr, "Unable to read file: %s\n", err->message);
    g_error_free (err);
  }
else
  {
    // Use file contents
    g_assert (contents != NULL);
  }
}

How to make rectangular image appear circular with CSS

you can only make circle from square using border-radius.

border-radius doesn't increase or reduce heights nor widths.

Your request is to use only image tag , it is basicly not possible if tag is not a square.

If you want to use a blank image and set another in bg, it is going to be painfull , one background for each image to set.

Cropping can only be done if a wrapper is there to do so. inthat case , you have many ways to do it

How to programmatically set the SSLContext of a JAX-WS client?

This is how I solved it based on this post with some minor tweaks. This solution does not require creation of any additional classes.

SSLContext sc = SSLContext.getInstance("SSLv3");

KeyManagerFactory kmf =
    KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );

KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load(new FileInputStream( certPath ), certPasswd.toCharArray() );

kmf.init( ks, certPasswd.toCharArray() );

sc.init( kmf.getKeyManagers(), null, null );

((BindingProvider) webservicePort).getRequestContext()
    .put(
        "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
        sc.getSocketFactory() );

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

gitignore all files of extension in directory

UPDATE: Take a look at @Joey's answer: Git now supports the ** syntax in patterns. Both approaches should work fine.


The gitignore(5) man page states:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory, with patterns in the higher level files (up to the toplevel of the work tree) being overridden by those in lower level files down to the directory containing the file.

What this means is that the patterns in a .gitignore file in any given directory of your repo will affect that directory and all subdirectories.

The pattern you provided

/public/static/**/*.js

isn't quite right, firstly because (as you correctly noted) the ** syntax is not used by Git. Also, the leading / anchors that pattern to the start of the pathname. (So, /public/static/*.js will match /public/static/foo.js but not /public/static/foo/bar.js.) Removing the leading / won't work either, matching paths like public/static/foo.js and foo/public/static/bar.js. EDIT: Just removing the leading slash won't work either — because the pattern still contains a slash, it is treated by Git as a plain, non-recursive shell glob (thanks @Joey Hoer for pointing this out).

As @ptyx suggested, what you need to do is create the file <repo>/public/static/.gitignore and include just this pattern:

*.js

There is no leading /, so it will match at any part of the path, and that pattern will only ever be applied to files in the /public/static directory and its subdirectories.

How can I upload files asynchronously?

This is my solution.

<form enctype="multipart/form-data">    

    <div class="form-group">
        <label class="control-label col-md-2" for="apta_Description">Description</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
        </div>
    </div>

    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>

and the js

<script>

    $(':button').click(function () {
        var formData = new FormData($('form')[0]);
        $.ajax({
            url: '@Url.Action("Save", "Home")',  
            type: 'POST',                
            success: completeHandler,
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
    });    

    function completeHandler() {
        alert(":)");
    }    
</script>

Controller

[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
    [...]
}

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

React-Router open Link in new tab

For external link simply use an achor in place of Link:

<a rel="noopener noreferrer" href="http://url.com" target="_blank">Link Here</a>

How to export MySQL database with triggers and procedures?

I've created the following script and it worked for me just fine.

#! /bin/sh
cd $(dirname $0)
DB=$1
DBUSER=$2
DBPASSWD=$3
FILE=$DB-$(date +%F).sql
mysqldump --routines "--user=${DBUSER}"  --password=$DBPASSWD $DB > $PWD/$FILE
gzip $FILE
echo Created $PWD/$FILE*

and you call the script using command line arguments.

backupdb.sh my_db dev_user dev_password

How to get the difference between two dictionaries in Python?

def flatten_it(d):
    if isinstance(d, list) or isinstance(d, tuple):
        return tuple([flatten_it(item) for item in d])
    elif isinstance(d, dict):
        return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
    else:
        return d

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}

print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or 
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])

ASP.net page without a code behind

File: logdate.aspx

<%@ Page Language="c#" %>
<%@ Import namespace="System.IO"%>
<%

StreamWriter tsw = File.AppendText(@Server.MapPath("./test.txt"));
tsw.WriteLine("--------------------------------");
tsw.WriteLine(DateTime.Now.ToString());

tsw.Close();
%>

Done

Git on Windows: How do you set up a mergetool?

git mergetool is fully configurable so you can pretty much chose your favourite tool.

The full documentation is here: http://www.kernel.org/pub/software/scm/git/docs/git-mergetool.html

In brief, you can set a default mergetool by setting the user config variable merge.tool.

If the merge tool is one of the ones supported natively by it you just have to set mergetool.<tool>.path to the full path to the tool (replace <tool> by what you have configured merge.tool to be.

Otherwise, you can set mergetool.<tool>.cmd to a bit of shell to be eval'ed at runtime with the shell variables $BASE, $LOCAL, $REMOTE, $MERGED set to the appropriate files. You have to be a bit careful with the escaping whether you directly edit a config file or set the variable with the git config command.

Something like this should give the flavour of what you can do ('mymerge' is a fictional tool).

git config merge.tool mymerge
git config merge.mymerge.cmd 'mymerge.exe --base "$BASE" "$LOCAL" "$REMOTE" -o "$MERGED"'

Once you've setup your favourite merge tool, it's simply a matter of running git mergetool whenever you have conflicts to resolve.

The p4merge tool from Perforce is a pretty good standalone merge tool.

How to change color in circular progress bar?

You can change your progressbar colour using the code below:

progressBar.getProgressDrawable().setColorFilter(
    getResources().getColor(R.color.your_color), PorterDuff.Mode.SRC_IN);

Recyclerview and handling different type of row inflation

You can just return ItemViewType and use it. See below code:

@Override
public int getItemViewType(int position) {

    Message item = messageList.get(position);
    // return my message layout
    if(item.getUsername() == Message.userEnum.I)
        return R.layout.item_message_me;
    else
        return R.layout.item_message; // return other message layout
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(viewType, viewGroup, false);
    return new ViewHolder(view);
}

Include an SVG (hosted on GitHub) in MarkDown

Use this site: https://rawgit.com , it works for me as I don't have permission issue with the svg file.
Please pay attention that RawGit is not a service of github, as mentioned in Rawgit FAQ :

RawGit is not associated with GitHub in any way. Please don't contact GitHub asking for help with RawGit

Enter the url of svg you need, such as :

https://github.com/sel-fish/redis-experiments/blob/master/dat/memDistrib-jemalloc-4.0.3.svg

Then, you can get the url bellow which can be used to display:

https://cdn.rawgit.com/sel-fish/redis-experiments/master/dat/memDistrib-jemalloc-4.0.3.svg

How to add hours to current time in python

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you're only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments - strftime

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

As of Oct 2019, SQL Server Management Studio, they did not upgraded the SSMS to add create ER Diagram feature.

I would suggest try using DBWeaver from here :

https://dbeaver.io/download/

I am using Mac and Windows both and I was able to download the community edition and logged into my SQL server database and was able to create the ER diagram using the DB Weaver.

ER Diagram using the Community Version Db Viewer

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

Event when window.location.href changes

I use this script in my extension "Grab Any Media" and work fine ( like youtube case )

var oldHref = document.location.href;

window.onload = function() {

    var
         bodyList = document.querySelector("body")

        ,observer = new MutationObserver(function(mutations) {

            mutations.forEach(function(mutation) {

                if (oldHref != document.location.href) {

                    oldHref = document.location.href;

                    /* Changed ! your code here */

                }

            });

        });

    var config = {
        childList: true,
        subtree: true
    };

    observer.observe(bodyList, config);

};

versionCode vs versionName in Android Manifest

It is indeed based on versionCode and not on versionName. However, I noticed that changing the versionCode in AndroidManifest.xml wasn't enough with Android Studio - Gradle build system. I needed to change it in the build.gradle.

gdb: how to print the current line or find the current line number?

Command where or frame can be used. where command will give more info with the function name

Instagram API - How can I retrieve the list of people a user is following on Instagram

I've been working on some Instagram extension for chrome last few days and I got this to workout:

First, you need to know that this can work if the user profile is public or you are logged in and you are following that user.

I am not sure why does it work like this, but probably some cookies are set when you log in that are checked on the backend while fetching private profiles.

Now I will share with you an ajax example but you can find other ones that suit you better if you are not using jquery.

Also, you can notice that we have two query_hash values for followers and followings and for other queries different ones.

let config = {
  followers: {
    hash: 'c76146de99bb02f6415203be841dd25a',
    path: 'edge_followed_by'
  },
  followings: {
    hash: 'd04b0a864b4b54837c0d870b0e77e076',
    path: 'edge_follow'
  }
};

The user ID you can get from https://www.instagram.com/user_name/?__a=1 as response.graphql.user.id

After is just response from first part of users that u are getting since the limit is 50 users per request:

let after = response.data.user[list].page_info.end_cursor

let data = {followers: [], followings: []};

function getFollows (user, list = 'followers', after = null) {
  $.get(`https://www.instagram.com/graphql/query/?query_hash=${config[list].hash}&variables=${encodeURIComponent(JSON.stringify({
    "id": user.id,
    "include_reel": true,
    "fetch_mutual": true,
    "first": 50,
    "after": after
  }))}`, function (response) {
    data[list].push(...response.data.user[config[list].path].edges);
    if (response.data.user[config[list].path].page_info.has_next_page) {
      setTimeout(function () {
        getFollows(user, list, response.data.user[config[list].path].page_info.end_cursor);
      }, 1000);
    } else if (list === 'followers') {
      getFollows(user, 'followings');
    } else {
      alert('DONE!');
      console.log(followers);
      console.log(followings);
    }
  });
}

You could probably use this off instagram website but I did not try, you would probably need some headers to match those from instagram page.

And if you need for those headers some additional data you could maybe find that within window._sharedData JSON that comes from backend with csrf token etc.

You can catch this by using:

let $script = JSON.parse(document.body.innerHTML.match(/<script type="text\/javascript">window\._sharedData = (.*)<\/script>/)[1].slice(0, -1));

Thats all from me!

Hope it helps you out!

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

Try something like this:

foreach (ListItem listItem in YrChkBox.Items)
{
    if (listItem.Selected)
    { 
       //do some work 
    }
    else 
    { 
      //do something else 
    }
}

MySQL - SELECT * INTO OUTFILE LOCAL ?

You can achieve what you want with the mysql console with the -s (--silent) option passed in.

It's probably a good idea to also pass in the -r (--raw) option so that special characters don't get escaped. You can use this to pipe queries like you're wanting.

mysql -u username -h hostname -p -s -r -e "select concat('this',' ','works')"

EDIT: Also, if you want to remove the column name from your output, just add another -s (mysql -ss -r etc.)

Counting inversions in an array

I recently had to do this in R:

inversionNumber <- function(x){
    mergeSort <- function(x){
        if(length(x) == 1){
            inv <- 0
        } else {
            n <- length(x)
            n1 <- ceiling(n/2)
            n2 <- n-n1
            y1 <- mergeSort(x[1:n1])
            y2 <- mergeSort(x[n1+1:n2])
            inv <- y1$inversions + y2$inversions
            x1 <- y1$sortedVector
            x2 <- y2$sortedVector
            i1 <- 1
            i2 <- 1
            while(i1+i2 <= n1+n2+1){
                if(i2 > n2 || i1 <= n1 && x1[i1] <= x2[i2]){
                    x[i1+i2-1] <- x1[i1]
                    i1 <- i1 + 1
                } else {
                    inv <- inv + n1 + 1 - i1
                    x[i1+i2-1] <- x2[i2]
                    i2 <- i2 + 1
                }
            }
        }
        return (list(inversions=inv,sortedVector=x))
    }
    r <- mergeSort(x)
    return (r$inversions)
}

python pip - install from local dir

You were looking for help on installations with pip. You can find it with the following command:

pip install --help

Running pip install -e /path/to/package installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.

How to add RSA key to authorized_keys file?

There is already a command in the ssh suite to do this automatically for you. I.e log into a remote host and add the public key to that computers authorized_keys file.

ssh-copy-id -i /path/to/key/file [email protected]

If the key you are installing is ~/.ssh/id_rsa then you can even drop the -i flag completely.

Much better than manually doing it!

How to make a char string from a C macro's value?

@Jonathan Leffler: Thank you. Your solution works.

A complete working example:

/** compile-time dispatch 

   $ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
*/
#include <stdio.h>

#define QUOTE(name) #name
#define STR(macro) QUOTE(macro)

#ifndef TEST_FUN
#  define TEST_FUN some_func
#endif

#define TEST_FUN_NAME STR(TEST_FUN)

void some_func(void)
{
  printf("some_func() called\n");
}

void another_func(void)
{
  printf("do something else\n");
}

int main(void)
{
  TEST_FUN();
  printf("TEST_FUN_NAME=%s\n", TEST_FUN_NAME);
  return 0;
}

Example:

$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
do something else
TEST_FUN_NAME=another_func

Detect all Firefox versions in JS

For a long time I have used the alternative:

('netscape' in window) && / rv:/.test(navigator.userAgent)

because I don't trust user agent strings. Some bugs are not detectable using feature detection, so detecting the browser is required for some workarounds.

Also if you are working around a bug in Gecko, then the bug is probably also in derivatives of Firefox, and this code should work with derivatives too (Do Waterfox and Pale Moon have 'Firefox' in the user agent string?).

What do >> and << mean in Python?

I think it is important question and it is not answered yet (the OP seems to already know about shift operators). Let me try to answer, the >> operator in your example is used for two different purposes. In c++ terms this operator is overloaded. In the first example it is used as bitwise operator (left shift), while in the second scenario it is merely used as output redirection. i.e.

2 << 5 # shift to left by 5 bits
2 >> 5 # shift to right by 5 bits
print >> obj, "Hello world" # redirect the output to obj, 

example

with open('foo.txt', 'w') as obj:
    print >> obj, "Hello world" # hello world now saved in foo.txt

update:

In python 3 it is possible to give the file argument directly as follows:

print("Hello world", file=open("foo.txt", "a")) # hello world now saved in foo.txt

How to sort alphabetically while ignoring case sensitive?

It is very unclear what you are trying to do, but you can sort a list like this:

List<String> fruits = new ArrayList<String>(7);

fruits.add("Pineapple");
fruits.add("apple");
fruits.add("apricot");
fruits.add("Banana");
fruits.add("mango");
fruits.add("melon");        
fruits.add("peach");

System.out.println("Unsorted: " + fruits);

Collections.sort(fruits, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {              
        return o1.compareToIgnoreCase(o2);
    }
});

System.out.println("Sorted: " + fruits);

PHP foreach loop key value

foreach($shipmentarr as $index=>$val){    
    $additionalService = array();

    foreach($additionalService[$index] as $key => $value) {

        array_push($additionalService,$value);

    }
}

SQLite UPSERT / UPDATE OR INSERT

The problem with all presented answers it complete lack of taking triggers (and probably other side effects) into account. Solution like

INSERT OR IGNORE ...
UPDATE ...

leads to both triggers executed (for insert and then for update) when row does not exist.

Proper solution is

UPDATE OR IGNORE ...
INSERT OR IGNORE ...

in that case only one statement is executed (when row exists or not).

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Some "real world" examples for static variables:

building a class where you can reach hardcoded values for your application. Similar to an enumeration, but with more flexibility on the datatype.

public static class Enemies
{
    public readonly static Guid Orc = new Guid("{937C145C-D432-4DE2-A08D-6AC6E7F2732C}");
}

The widely known singleton, this allows to control to have exactly one instance of a class. This is very useful if you want access to it in your whole application, but not pass it to every class just to allow this class to use it.

public sealed class TextureManager
    {
        private TextureManager() {}
        public string LoadTexture(string aPath);

        private static TextureManager sInstance = new TextureManager();

        public static TextureManager Instance
        {
            get { return sInstance; }
        }
    }

and this is how you would call the texturemanager

TextureManager.Instance.LoadTexture("myImage.png");

About your last question: You are refering to compiler error CS0176. I tried to find more infor about that, but could only find what the msdn had to say about it:

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.

Git mergetool generates unwanted .orig files

Besides the correct answers offered as long term solutions, you can use git to remove all unnecessary files once for you with the git clean -f command but use git clean --dry-run first to ensure nothing unintended would happen.

This has the benefit of using tested built in functionality of Git over scripts specific to your OS/shell to remove the files.

Create a txt file using batch file in a specific folder

You have it almost done. Just explicitly say where to create the file

@echo off
  echo.>"d:\testing\dblank.txt"

This creates a file containing a blank line (CR + LF = 2 bytes).

If you want the file empty (0 bytes)

@echo off
  break>"d:\testing\dblank.txt"

Check if a Python list item contains a string inside another string

mylist=['abc','def','ghi','abc']

pattern=re.compile(r'abc') 

pattern.findall(mylist)

How to call Oracle MD5 hash function?

In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.

select standard_hash('foo', 'MD5') from dual;

The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:

select rawtohex(
    DBMS_CRYPTO.Hash (
        UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
        2)
    ) from dual;

Output:

ACBD18DB4CC2F85CEDEF654FCCC4A4D8

Add a lower function call if needed. More on DBMS_CRYPTO.

How do you share constants in NodeJS modules?

I ended up doing this by exporting a frozen object with anonymous getter functions, rather than the constants themselves. This reduces the risk of nasty bugs introduced due to a simple typo of the const name, as a runtime error will be thrown in case of a typo. Here's a full example that also uses ES6 Symbols for the constants, ensuring uniqueness, and ES6 arrow functions. Would appreciate feedback if anything in this approach seems problematic.

'use strict';
const DIRECTORY = Symbol('the directory of all sheets');
const SHEET = Symbol('an individual sheet');
const COMPOSER = Symbol('the sheet composer');

module.exports = Object.freeze({
  getDirectory: () => DIRECTORY,
  getSheet: () => SHEET,
  getComposer: () => COMPOSER
});

Adding the "Clear" Button to an iPhone UITextField

this don't work, do like me:

swift:

customTextField.clearButtonMode = UITextField.ViewMode.Always

customTextField.clearsOnBeginEditing = true;

func textFieldShouldClear(textField: UITextField) -> Bool {
    return true
}

How to automatically update your docker containers, if base-images are updated

There are a lot of answers here, but none of them suited my needs. I wanted an actual answer to the asker's #1 question. How do I know when an image is updated on hub.docker.com?

The below script can be run daily. On first run, it gets a baseline of the tags and update dates from the HUB registry and saves them locally. From then out, every time it is run it checks the registry for new tags and update dates. Since this changes every time a new image exists, it tells us if the base image has changed. Here is the script:

#!/bin/bash

DATAPATH='/data/docker/updater/data'

if [ ! -d "${DATAPATH}" ]; then
        mkdir "${DATAPATH}";
fi
IMAGES=$(docker ps --format "{{.Image}}")
for IMAGE in $IMAGES; do
        ORIGIMAGE=${IMAGE}
        if [[ "$IMAGE" != *\/* ]]; then
                IMAGE=library/${IMAGE}
        fi
        IMAGE=${IMAGE%%:*}
        echo "Checking ${IMAGE}"
        PARSED=${IMAGE//\//.}
        if [ ! -f "${DATAPATH}/${PARSED}" ]; then
                # File doesn't exist yet, make baseline
                echo "Setting baseline for ${IMAGE}"
                curl -s "https://registry.hub.docker.com/v2/repositories/${IMAGE}/tags/" > "${DATAPATH}/${PARSED}"
        else
                # File does exist, do a compare
                NEW=$(curl -s "https://registry.hub.docker.com/v2/repositories/${IMAGE}/tags/")
                OLD=$(cat "${DATAPATH}/${PARSED}")
                if [[ "${VAR1}" == "${VAR2}" ]]; then
                        echo "Image ${IMAGE} is up to date";
                else
                        echo ${NEW} > "${DATAPATH}/${PARSED}"
                        echo "Image ${IMAGE} needs to be updated";
                        H=`hostname`
                        ssh -i /data/keys/<KEYFILE> <USER>@<REMOTEHOST>.com "{ echo \"MAIL FROM: root@${H}\"; echo \"RCPT TO: <USER>@<EMAILHOST>.com\"; echo \"DATA\"; echo \"Subject: ${H} - ${IMAGE} needs update\"; echo \"\"; echo -e \"\n${IMAGE} needs update.\n\ndocker pull ${ORIGIMAGE}\"; echo \"\"; echo \".\"; echo \"quit\"; sleep 1; } | telnet <SMTPHOST> 25"
                fi

        fi
done;

You will want to alter the DATAPATH variable at the top, and alter the email notification command at the end to suit your needs. For me, I have it SSH into a server on another network where my SMTP is located. But you could easily use the mail command, too.

Now, you also want to check for updated packages inside the containers themselves. This is actually probably more effective than doing a "pull" once your containers are working. Here's the script to pull that off:

#!/bin/bash


function needsUpdates() {
        RESULT=$(docker exec ${1} bash -c ' \
                if [[ -f /etc/apt/sources.list ]]; then \
                grep security /etc/apt/sources.list > /tmp/security.list; \
                apt-get update > /dev/null; \
                apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s; \
                fi; \
                ')
        RESULT=$(echo $RESULT)
        GOODRESULT="Reading package lists... Building dependency tree... Reading state information... Calculating upgrade... 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded."
        if [[ "${RESULT}" != "" ]] && [[ "${RESULT}" != "${GOODRESULT}" ]]; then
                return 0
        else
                return 1
        fi
}

function sendEmail() {
        echo "Container ${1} needs security updates";
        H=`hostname`
        ssh -i /data/keys/<KEYFILE> <USRER>@<REMOTEHOST>.com "{ echo \"MAIL FROM: root@${H}\"; echo \"RCPT TO: <USER>@<EMAILHOST>.com\"; echo \"DATA\"; echo \"Subject: ${H} - ${1} container needs security update\"; echo \"\"; echo -e \"\n${1} container needs update.\n\n\"; echo -e \"docker exec ${1} bash -c 'grep security /etc/apt/sources.list > /tmp/security.list; apt-get update > /dev/null; apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s'\n\n\"; echo \"Remove the -s to run the update\"; echo \"\"; echo \".\"; echo \"quit\"; sleep 1; } | telnet <SMTPHOST> 25"
}

CONTAINERS=$(docker ps --format "{{.Names}}")
for CONTAINER in $CONTAINERS; do
        echo "Checking ${CONTAINER}"
        if needsUpdates $CONTAINER; then
                sendEmail $CONTAINER
        fi
done

How to restore default perspective settings in Eclipse IDE

One way is just to revert your settings: If you delete the Metadata folder in your workspace eclipse will revert to its factory state for all settings (both perspective and general).

Source: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka11640.html

Excel formula to get week number in month (having Monday)

If week 1 always starts on the first Monday of the month try this formula for week number

=INT((6+DAY(A1+1-WEEKDAY(A1-1)))/7)

That gets the week number from the date in A1 with no intermediate calculations - if you want to use your "Monday's date" in B1 you can use this version

=INT((DAY(B1)+6)/7)

Get the time of a datetime using T-SQL?

In case of SQL Server, this should work

SELECT CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond

specifying goal in pom.xml

I ran into this when trying to run spring boot from the command line...

mvn spring-boot:run

I accidentally mis-typed the command as...

mvn spring-boot run

So it was looking for the commands... run, build etc...

How do I convert a C# List<string[]> to a Javascript array?

Many way to Json Parse but i have found most effective way to

 @model  List<string[]>

     <script>

         function DataParse() {
             var model = '@Html.Raw(Json.Encode(Model))';
             var data = JSON.parse(model);  

            for (i = 0; i < data.length; i++) {
            ......
             }

     </script>

What are type hints in Python 3.5?

The newly released PyCharm 5 supports type hinting. In their blog post about it (see Python 3.5 type hinting in PyCharm 5) they offer a great explanation of what type hints are and aren't along with several examples and illustrations for how to use them in your code.

Additionally, it is supported in Python 2.7, as explained in this comment:

PyCharm supports the typing module from PyPI for Python 2.7, Python 3.2-3.4. For 2.7 you have to put type hints in *.pyi stub files since function annotations were added in Python 3.0.

target="_blank" vs. target="_new"

In order to open a link in a new tab/window you'll use <a target="_blank">.

value _blank = targeted browsing context: a new one: tab or window depending on your browsing settings

value _new = not valid; no such value in HTML5 for target attribute on a element

target attribute with all its values on a element: video demo

What's the difference between "git reset" and "git checkout"?

  • git reset is specifically about updating the index, moving the HEAD.
  • git checkout is about updating the working tree (to the index or the specified tree). It will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD).
    (actually, with Git 2.23 Q3 2019, this will be git restore, not necessarily git checkout)

By comparison, since svn has no index, only a working tree, svn checkout will copy a given revision on a separate directory.
The closer equivalent for git checkout would:

  • svn update (if you are in the same branch, meaning the same SVN URL)
  • svn switch (if you checkout for instance the same branch, but from another SVN repo URL)

All those three working tree modifications (svn checkout, update, switch) have only one command in git: git checkout.
But since git has also the notion of index (that "staging area" between the repo and the working tree), you also have git reset.


Thinkeye mentions in the comments the article "Reset Demystified ".

For instance, if we have two branches, 'master' and 'develop' pointing at different commits, and we're currently on 'develop' (so HEAD points to it) and we run git reset master, 'develop' itself will now point to the same commit that 'master' does.

On the other hand, if we instead run git checkout master, 'develop' will not move, HEAD itself will. HEAD will now point to 'master'.

So, in both cases we're moving HEAD to point to commit A, but how we do so is very different. reset will move the branch HEAD points to, checkout moves HEAD itself to point to another branch.

http://git-scm.com/images/reset/reset-checkout.png

On those points, though:

LarsH adds in the comments:

The first paragraph of this answer, though, is misleading: "git checkout ... will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD)".
Not true: git checkout will update the HEAD even if you checkout a commit that's not a branch (and yes, you end up with a detached HEAD, but it still got updated).

git checkout a839e8f updates HEAD to point to commit a839e8f.

De Novo concurs in the comments:

@LarsH is correct.
The second bullet has a misconception about what HEAD is in will update the HEAD only if you checkout a branch.
HEAD goes wherever you are, like a shadow.
Checking out some non-branch ref (e.g., a tag), or a commit directly, will move HEAD. Detached head doesn't mean you've detached from the HEAD, it means the head is detached from a branch ref, which you can see from, e.g., git log --pretty=format:"%d" -1.

  • Attached head states will start with (HEAD ->,
  • detached will still show (HEAD, but will not have an arrow to a branch ref.

Reading a string with scanf

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

mysqld: Can't change dir to data. Server doesn't start

What I did (Windows 10) for a new installation:

  1. Start cmd in admin mode (run as administrator by hitting windows key, typing cmd, right clicking on it and selecting "Run as Administrator"

  2. Change into "MySQL Server X.Y" directory (for me the full path is C:\Program Files\MySQL\MySQL Server 5.7")

  3. using notepad create a my.ini with a mysqld section that points at your data directory

    [mysqld]
    datadir="X:\Your Directory Path and Name"
    
  4. created the directory identified in my.ini above.

  5. change into bin Directory under server directory and execute: mysqld --initialize

  6. Once complete, started the service and it came up fine.

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

How can I show line numbers in Eclipse?

in this file

[workspace].metadata.plugins\org.eclipse.core.runtime.settings\org.eclipse.ui.editors.prefs

make sure the parameter

lineNumberColor=0,0,0

is NOT 255,255, 255, which is white

Switch tabs using Selenium WebDriver with Java

Since the driver.window_handles is not in order , a better solution is this.

first switch to the first tab using the shortcut Control + X to switch to the 'x' th tab in the browser window .

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "1");
# goes to 1st tab

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "4");
# goes to 4th tab if its exists or goes to last tab.

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How to define the basic HTTP authentication using cURL correctly?

as header

AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)

curl \
  --header "Content-Type: application/json" \
  --header "Authorization: Basic $AUTH" \
  --request POST \
  --data  '{"key1":"value1", "key2":"value2"}' \
  https://example.com/

findViewById in Fragment

agreed with calling findViewById() on the View.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View V = inflater.inflate(R.layout.testclassfragment, container, false);
    ImageView imageView = (ImageView) V.findViewById(R.id.my_image);

    return V;
}

How do you beta test an iphone app?

Using testflight :

1) create the ipa file by development certificate

2) upload the ipa file on testflight

3) Now, to identify the device to be tested on , add the device id on apple account and refresh your development certificate. Download the updated certificate and upload it on testflight website. Check the device id you are getting.

4) Now email the ipa file to the testers.

5) While downloading the ipa file, if the testers are not getting any warnings, this means the device token + provisioning profile has been verified. So, the testers can now download the ipa file on device and do the testing job...

How do you get the current time of day?

Another option using String.Format()

string.Format("{0:HH:mm:ss tt}", DateTime.Now)

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

brew switch openssl 1.0.2r

it work for me,macOS Mojave, Version 10.14.6

Open an html page in default browser with VBA?

I find the most simple is

shell "explorer.exe URL"

This also works to open local folders.

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

You'll need to post your statement for more clarification. But...

That error means that the table you are inserting data into has a foreign key relationship with another table. Before data can be inserted, the value in the foreign key field must exist in the other table first.

Get name of current script in Python

You can do this without importing os or other libs.

If you want to get the path of current python script, use: __file__

If you want to get only the filename without .py extension, use this:

__file__.rsplit("/", 1)[1].split('.')[0]

Rounding up to next power of 2

unsigned long upper_power_of_two(unsigned long v)
{
    v--;
    v |= v >> 1;
    v |= v >> 2;
    v |= v >> 4;
    v |= v >> 8;
    v |= v >> 16;
    v++;
    return v;

}

Getting the array length of a 2D array in Java

Try this following program for 2d array in java:

public class ArrayTwo2 {
    public static void main(String[] args) throws  IOException,NumberFormatException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int[][] a;
        int sum=0;
        a=new int[3][2];
        System.out.println("Enter array with 5 elements");
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            a[i][j]=Integer.parseInt(br.readLine());
            }
        }
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            System.out.print(a[i][j]+"  ");
            sum=sum+a[i][j];
            }
        System.out.println();   
        //System.out.println("Array Sum: "+sum);
        sum=0;
        }
    }
}

LINQ Joining in C# with multiple conditions

Your and should be a && in the where clause.

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
and epl.ArriveAirportBy > sd.UTCArrivalTime

should be

where epl.DepartAirportAfter >  sd.UTCDepartureTime 
&& epl.ArriveAirportBy > sd.UTCArrivalTime

cannot redeclare block scoped variable (typescript)

In my case the following tsconfig.json solved problem:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "target": "ES2020",
    "moduleResolution": "node"
  }
}

There should be no type: module in package.json.

Changing factor levels with dplyr mutate

Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be

df <- iris %>%
  mutate(Species = recode(Species, 
     setosa = "SETOSA",
     versicolor = "VERSICOLOR",
     virginica = "VIRGINICA")
  )

How to animate GIFs in HTML document?

Agreed with Yuri Tkachenko's answer.

I wanna point this out.

It's a pretty specific scenario. BUT it happens.

When you copy a gif before its loaded fully in some site like google images. it just gives the preview image address of that gif. Which is clearly not a gif.

So, make sure it ends with .gif extension

REST API - Use the "Accept: application/json" HTTP Header

Well Curl could be a better option for json representation but in that case it would be difficult to understand the structure of json because its in command line. if you want to get your json on browser you simply remove all the XML Annotations like -

@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.NONE)
@XmlAttribute
@XmlElement

from your model class and than run the same url, you have used for xml representation.

Make sure that you have jacson-databind dependency in your pom.xml

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.4.1</version>
</dependency>