Programs & Examples On #Movieplayer

MoviePlayer is the informal name for class MPMoviePlayerController that manages the playback of a movie from a file or a network stream on iOS framework.

iPhone SDK:How do you play video inside a view? Rather than fullscreen

The best way is to use layers insted of views:

AVPlayer *player = [AVPlayer playerWithURL:[NSURL url...]]; // 

AVPlayerLayer *layer = [AVPlayerLayer layer];

[layer setPlayer:player];
[layer setFrame:CGRectMake(10, 10, 300, 200)];
[layer setBackgroundColor:[UIColor redColor].CGColor];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

[self.view.layer addSublayer:layer];

[player play];

Don't forget to add frameworks:

#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"

How to do a SQL NOT NULL with a DateTime?

I faced this problem where the following query doesn't work as expected:

select 1 where getdate()<>null

we expect it to show 1 because getdate() doesn't return null. I guess it has something to do with SQL failing to cast null as datetime and skipping the row! of course we know we should use IS or IS NOT keywords to compare a variable with null but when comparing two parameters it gets hard to handle the null situation. as a solution you can create your own compare function like the following:

CREATE FUNCTION [dbo].[fnCompareDates]
(
    @DateTime1 datetime,
    @DateTime2 datetime
)
RETURNS bit
AS
BEGIN
    if (@DateTime1 is null and @DateTime2 is null) return 1;
    if (@DateTime1 = @DateTime2) return 1;
    return 0
END

and re writing the query like:

select 1 where dbo.fnCompareDates(getdate(),null)=0

Eclipse error: "The import XXX cannot be resolved"

First Update Project in maven and Check for Jar/depdency in the required dependency in Class Path it Worked For me

A project with an Output Type of Class Library cannot be started directly

Just right click on the Project Solution A window pops up. Expand the common Properties. Select Start Up Project

In there on right hand side Select radio button with Single Startup Project Select your Project in there and apply.

That's it. Now save and build your project. Run the project to see the output.

Set value to an entire column of a pandas dataframe

Seems to me that:

df1 = df[df['col1']==some_value] WILL NOT create a new DataFrame, basically, changes in df1 will be reflected in the parent df. This leads to the warning. Whereas, df1 = df[df['col1]]==some_value].copy() WILL create a new DataFrame, and changes in df1 will not be reflected in df. the copy() method is recommended if you don't want to make changes to your original df.

Java Garbage Collection Log messages

  1. PSYoungGen refers to the garbage collector in use for the minor collection. PS stands for Parallel Scavenge.
  2. The first set of numbers are the before/after sizes of the young generation and the second set are for the entire heap. (Diagnosing a Garbage Collection problem details the format)
  3. The name indicates the generation and collector in question, the second set are for the entire heap.

An example of an associated full GC also shows the collectors used for the old and permanent generations:

3.757: [Full GC [PSYoungGen: 2672K->0K(35584K)] 
            [ParOldGen: 3225K->5735K(43712K)] 5898K->5735K(79296K) 
            [PSPermGen: 13533K->13516K(27584K)], 0.0860402 secs]

Finally, breaking down one line of your example log output:

8109.128: [GC [PSYoungGen: 109884K->14201K(139904K)] 691015K->595332K(1119040K), 0.0454530 secs]
  • 107Mb used before GC, 14Mb used after GC, max young generation size 137Mb
  • 675Mb heap used before GC, 581Mb heap used after GC, 1Gb max heap size
  • minor GC occurred 8109.128 seconds since the start of the JVM and took 0.04 seconds

get selected value in datePicker and format it

Use jquery-dateFormat. It will solve your problem.

You need to include the jquery.dateFormat in your html file.

<script>
var date = $('#scheduleDate').val();
document.write($.format.date(date, "dd,MM,yyyy"));

var dateTypeVar = $('#scheduleDate').datepicker('getDate');
document.write($.format.date(dateTypeVar, "dd-MM-yy"));
</script>

Intercept and override HTTP requests from WebView

Here is my solution I use for my app.

I have several asset folder with css / js / img anf font files.

The application gets all filenames and looks if a file with this name is requested. If yes, it loads it from asset folder.

//get list of files of specific asset folder
        private ArrayList listAssetFiles(String path) {

            List myArrayList = new ArrayList();
            String [] list;
            try {
                list = getAssets().list(path);
                for(String f1 : list){
                    myArrayList.add(f1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return (ArrayList) myArrayList;
        }

        //get mime type by url
        public String getMimeType(String url) {
            String type = null;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            if (extension != null) {
                if (extension.equals("js")) {
                    return "text/javascript";
                }
                else if (extension.equals("woff")) {
                    return "application/font-woff";
                }
                else if (extension.equals("woff2")) {
                    return "application/font-woff2";
                }
                else if (extension.equals("ttf")) {
                    return "application/x-font-ttf";
                }
                else if (extension.equals("eot")) {
                    return "application/vnd.ms-fontobject";
                }
                else if (extension.equals("svg")) {
                    return "image/svg+xml";
                }
                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }
            return type;
        }

        //return webresourceresponse
        public WebResourceResponse loadFilesFromAssetFolder (String folder, String url) {
            List myArrayList = listAssetFiles(folder);
            for (Object str : myArrayList) {
                if (url.contains((CharSequence) str)) {
                    try {
                        Log.i(TAG2, "File:" + str);
                        Log.i(TAG2, "MIME:" + getMimeType(url));
                        return new WebResourceResponse(getMimeType(url), "UTF-8", getAssets().open(String.valueOf(folder+"/" + str)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        //@TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @SuppressLint("NewApi")
        @Override
        public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
            //Log.i(TAG2, "SHOULD OVERRIDE INIT");
            //String url = webResourceRequest.getUrl().toString();
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            //I have some folders for files with the same extension
            if (extension.equals("css") || extension.equals("js") || extension.equals("img")) {
                return loadFilesFromAssetFolder(extension, url);
            }
            //more possible extensions for font folder
            if (extension.equals("woff") || extension.equals("woff2") || extension.equals("ttf") || extension.equals("svg") || extension.equals("eot")) {
                return loadFilesFromAssetFolder("font", url);
            }

            return null;
        }

Rounding a double value to x number of decimal places in swift

You can use Swift's round function to accomplish this.

To round a Double with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:

let x = 1.23556789
let y = Double(round(1000*x)/1000)
print(y)  // 1.236

Other than any kind of printf(...) or String(format: ...) solutions, the result of this operation is still of type Double.

EDIT:
Regarding the comments that it sometimes does not work, please read this:

What Every Programmer Should Know About Floating-Point Arithmetic

Change background image opacity

and you can do that by simple code:

filter:alpha(opacity=30);
-moz-opacity:0.3;
-khtml-opacity: 0.3;
opacity: 0.3;

Swift add icon/image in UITextField

let image = UIImage(systemName: "envelope")
let textField = UITextField()
textField.leftView = UIImageView(image: image)
textField.leftView?.frame = CGRect(x: 5, y: 5, width: 20 , height:20)
textField.leftViewMode = .always

How do I monitor all incoming http requests?

Microsoft Message Analyzer is the successor of the Microsoft Network Monitor 3.4

If your http incoming traffic is going to your web server at 58000 port, start the Analyzer in Administrator mode and click new session:

use filter: tcp.Port = 58000 and HTTP

trace scenario: "Local Network Interfaces (Win 8 and earlier)" or "Local Network Interfaces (Win 8.1 and later)" depends on your OS

Parsing Level: Full

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

Validate email address textbox using JavaScript

<h2>JavaScript Email Validation</h2>

<input id="textEmail">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo" style="color: red;"></p>

<script>
function myFunction() {
    var email;

    email = document.getElementById("textEmail").value;

        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(textEmail.value) == false) 
        {
        document.getElementById("demo").style.color = "red";
            document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
            alert('Invalid Email Address ->'+email);
            return false;
        } else{
        document.getElementById("demo").style.color = "DarkGreen";      
        document.getElementById("demo").innerHTML ="Valid Email ->"+email;
        }

   return true;
}
</script>

Resizing an image in an HTML5 canvas

I just ran a page of side by sides comparisons and unless something has changed recently, I could see no better downsizing (scaling) using canvas vs. simple css. I tested in FF6 Mac OSX 10.7. Still slightly soft vs. the original.

I did however stumble upon something that did make a huge difference and that was using image filters in browsers that support canvas. You can actually manipulate images much like you can in Photoshop with blur, sharpen, saturation, ripple, grayscale, etc.

I then found an awesome jQuery plug-in which makes application of these filters a snap: http://codecanyon.net/item/jsmanipulate-jquery-image-manipulation-plugin/428234

I simply apply the sharpen filter right after resizing the image which should give you the desired effect. I didn't even have to use a canvas element.

How to select records from last 24 hours using SQL?

In Oracle (For last 24 hours):

SELECT  *
FROM    my_table
WHERE   date_column >= SYSDATE - 24/24

In case, for any reason, you have rows with future dates, you can use between, like this:

SELECT  *
FROM    my_table
WHERE   date_column BETWEEN (SYSDATE - 24/24) AND SYSDATE

Can there exist two main methods in a Java program?

The below code in file "Locomotive.java" will compile and run successfully, with the execution results showing

2<SPACE>

As mentioned in above post, the overload rules still work for the main method. However, the entry point is the famous psvm (public static void main(String[] args))

public class Locomotive {
    Locomotive() { main("hi");}

    public static void main(String[] args) {
        System.out.print("2 ");
    }

    public static void main(String args) {
        System.out.print("3 " + args);
    }
}

Deleting rows from parent and child tables

Here's a complete example of how it can be done. However you need flashback query privileges on the child table.

Here's the setup.

create table parent_tab
  (parent_id number primary key,
  val varchar2(20));

create table child_tab
    (child_id number primary key,
    parent_id number,
    child_val number,
     constraint child_par_fk foreign key (parent_id) references parent_tab);

insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');

insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);

commit;

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).

delete from child_tab where child_val = 100;

Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab

delete from parent_tab
where parent_id in
  (select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
  minus
  select parent_id from child_tab);

'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

select * from parent_tab;

It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

In my project for C#, project property->[Build]->Platform target: Any CPU, and uncheck the Prefer 32-bit to let compiler to choose automatically.

How to search for a string inside an array of strings

It's as simple as iterating the array and looking for the regexp

function searchStringInArray (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if (strArray[j].match(str)) return j;
    }
    return -1;
}

Edit - make str as an argument to function.

Finding the average of a list

I had a similar question to solve in a Udacity´s problems. Instead of a built-in function i coded:

def list_mean(n):

    summing = float(sum(n))
    count = float(len(n))
    if n == []:
        return False
    return float(summing/count)

Much more longer than usual but for a beginner its quite challenging.

How do I diff the same file between two different commits on the same branch?

If you want a simple visual comparison on Windows such as you can get in Visual SourceSafe or Team Foundation Server (TFS), try this:

  • right-click on the file in File Explorer
  • select 'Git History'

Note: After upgrading to Windows 10 I have lost the Git context menu options. However, you can achieve the same thing using 'gitk' or 'gitk filename' in a command window.

Once you call 'Git History', the Git GUI tool will start, with a history of the file in the top left pane. Select one of the versions you would like to compare. Then right-click on the second version and choose either

Diff this -> selected

or

Diff selected -> this

Colour-coded differences will appear in the lower left-hand pane.

How to sum a variable by group

You can also use the dplyr package for that purpose:

library(dplyr)
x %>% 
  group_by(Category) %>% 
  summarise(Frequency = sum(Frequency))

#Source: local data frame [3 x 2]
#
#  Category Frequency
#1    First        30
#2   Second         5
#3    Third        34

Or, for multiple summary columns (works with one column too):

x %>% 
  group_by(Category) %>% 
  summarise(across(everything(), sum))

Here are some more examples of how to summarise data by group using dplyr functions using the built-in dataset mtcars:

# several summary columns with arbitrary names
mtcars %>% 
  group_by(cyl, gear) %>%                            # multiple group columns
  summarise(max_hp = max(hp), mean_mpg = mean(mpg))  # multiple summary columns

# summarise all columns except grouping columns using "sum" 
mtcars %>% 
  group_by(cyl) %>% 
  summarise(across(everything(), sum))

# summarise all columns except grouping columns using "sum" and "mean"
mtcars %>% 
  group_by(cyl) %>% 
  summarise(across(everything(), list(mean = mean, sum = sum)))

# multiple grouping columns
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(across(everything(), list(mean = mean, sum = sum)))

# summarise specific variables, not all
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(across(c(qsec, mpg, wt), list(mean = mean, sum = sum)))

# summarise specific variables (numeric columns except grouping columns)
mtcars %>% 
  group_by(gear) %>% 
  summarise(across(where(is.numeric), list(mean = mean, sum = sum)))

For more information, including the %>% operator, see the introduction to dplyr.

Can I Set "android:layout_below" at Runtime Programmatically?

Yes:

RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);

First, the code creates a new layout params by specifying the height and width. The addRule method adds the equivalent of the xml properly android:layout_below. Then you just call View#setLayoutParams on the view you want to have those params.

Regarding 'main(int argc, char *argv[])'

The arguments argc and argv of main is used as a way to send arguments to a program, the possibly most familiar way is to use the good ol' terminal where an user could type cat file. Here the word cat is a program that takes a file and outputs it to standard output (stdout).

The program receives the number of arguments in argc and the vector of arguments in argv, in the above the argument count would be two (The program name counts as the first argument) and the argument vector would contain [cat,file,null]. While the last element being a null-pointer.

Commonly, you would write it like this:

int  // Specifies that type of variable the function returns.
     // main() must return an integer
main ( int argc, char **argv ) {
     // code
     return 0; // Indicates that everything went well.
}

If your program does not require any arguments, it is equally valid to write a main-function in the following fashion:

int main() {
  // code
  return 0; // Zero indicates success, while any 
  // Non-Zero value indicates a failure/error
}

In the early versions of the C language, there was no int before main as this was implied. Today, this is considered to be an error.

On POSIX-compliant systems (and Windows), there exists the possibility to use a third parameter char **envp which contains a vector of the programs environment variables. Further variations of the argument list of the main function exists, but I will not detail it here since it is non-standard.

Also, the naming of the variables is a convention and has no actual meaning. It is always a good idea to adhere to this so that you do not confuse others, but it would be equally valid to define main as

int main(int c, char **v, char **e) {
   // code
   return 0;
}

And for your second question, there are several ways to send arguments to a program. I would recommend you to look at the exec*()family of functions which is POSIX-standard, but it is probably easier to just use system("command arg1 arg2"), but the use of system() is usually frowned upon as it is not guaranteed to work on every system. I have not tested it myself; but if there is no bash,zsh, or other shell installed on a *NIX-system, system() will fail.

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Adding the @ElementCollection to the List field solved this issue:

    @Column
    @ElementCollection(targetClass=Integer.class)
    private List<Integer> countries;

Do C# Timers elapse on a separate thread?

If the elapsed event takes longer then the interval, it will create another thread to raise the elapsed event. But there is a workaround for this

static void timer_Elapsed(object sender, ElapsedEventArgs e)    
{     
   try
   {
      timer.Stop(); 
      Thread.Sleep(2000);        
      Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);    
   }
   finally
   {
     timer.Start();
   }
}

When to use AtomicReference in Java?

Here is a use case for AtomicReference:

Consider this class that acts as a number range, and uses individual AtmomicInteger variables to maintain lower and upper number bounds.

public class NumberRange {
    // INVARIANT: lower <= upper
    private final AtomicInteger lower = new AtomicInteger(0);
    private final AtomicInteger upper = new AtomicInteger(0);

    public void setLower(int i) {
        // Warning -- unsafe check-then-act
        if (i > upper.get())
            throw new IllegalArgumentException(
                    "can't set lower to " + i + " > upper");
        lower.set(i);
    }

    public void setUpper(int i) {
        // Warning -- unsafe check-then-act
        if (i < lower.get())
            throw new IllegalArgumentException(
                    "can't set upper to " + i + " < lower");
        upper.set(i);
    }

    public boolean isInRange(int i) {
        return (i >= lower.get() && i <= upper.get());
    }
}

Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. This can be fixed by using a AtomicReference instead of using individual AtomicIntegers for upper and lower bounds.

public class CasNumberRange {
    // Immutable
    private static class IntPair {
        final int lower;  // Invariant: lower <= upper
        final int upper;

        private IntPair(int lower, int upper) {
            this.lower = lower;
            this.upper = upper;
        }
    }

    private final AtomicReference<IntPair> values = 
            new AtomicReference<IntPair>(new IntPair(0, 0));

    public int getLower() {
        return values.get().lower;
    }

    public void setLower(int lower) {
        while (true) {
            IntPair oldv = values.get();
            if (lower > oldv.upper)
                throw new IllegalArgumentException(
                    "Can't set lower to " + lower + " > upper");
            IntPair newv = new IntPair(lower, oldv.upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }

    public int getUpper() {
        return values.get().upper;
    }

    public void setUpper(int upper) {
        while (true) {
            IntPair oldv = values.get();
            if (upper < oldv.lower)
                throw new IllegalArgumentException(
                    "Can't set upper to " + upper + " < lower");
            IntPair newv = new IntPair(oldv.lower, upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }
}

Test if string begins with a string?

There are several ways to do this:

InStr

You can use the InStr build-in function to test if a String contains a substring. InStr will either return the index of the first match, or 0. So you can test if a String begins with a substring by doing the following:

If InStr(1, "Hello World", "Hello W") = 1 Then
    MsgBox "Yep, this string begins with Hello W!"
End If

If InStr returns 1, then the String ("Hello World"), begins with the substring ("Hello W").

Like

You can also use the like comparison operator along with some basic pattern matching:

If "Hello World" Like "Hello W*" Then
    MsgBox "Yep, this string begins with Hello W!"
End If

In this, we use an asterisk (*) to test if the String begins with our substring.

Flutter command not found

You need to edit you Zsh or bash profile. macOS Catalina uses the Z shell by default, so edit $HOME/.zshrc.

If you are using a different shell, the file path and filename will be different on your machine.

PATH_TO_FLUTTER_GIT_DIRECTORY == Location to your flutter SDK file.

To edit $HOME/.zshrc:

  1. open Terminal

  2. copy and paste nano $HOME/.zshrc

  3. copy next line and paste it at bottom

    export PATH="[PATH_TO_FLUTTER_GIT_DIRECTORY]/flutter/bin:$PATH"

  4. Edit your [PATH_TO_FLUTTER_GIT_DIRECTORY].

It will look something like this--> for example:

export PATH="/Users/flutter/bin:$PATH"

press CTRL X and when it asked you to save the file, choose yes.
Close and Restart the Terminal and try running flutter doctor

Verify that the flutter/bin directory is now in your PATH by running:

echo $PATH

[PATH_TO_FLUTTER_GIT_DIRECTORY] is where you installed flutter SDK.

Instead of nano, you can use any text editor to edit ~/.bash_profile or .zshrc

String Padding in C

The argument you passed "Hello" is on the constant data area. Unless you've allocated enough memory to char * string, it's overrunning to other variables.

char buffer[1024];
memset(buffer, 0, sizeof(buffer));
strncpy(buffer, "Hello", sizeof(buffer));
StringPadRight(buffer, 10, "0");

Edit: Corrected from stack to constant data area.

How do I pass JavaScript variables to PHP?

You can use JQuery Ajax and POST method:

var obj;

                
$(document).ready(function(){
            $("#button1").click(function(){
                var username=$("#username").val();
                var password=$("#password").val();
  $.ajax({
    url: "addperson.php",
    type: "POST", 
    async: false,
    data: {
        username: username,
        password: password
    }
})
.done (function(data, textStatus, jqXHR) { 
    
   obj = JSON.parse(data);
   
})
.fail (function(jqXHR, textStatus, errorThrown) { 
    
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
    
});
  
 
            });
        });

To take a response back from the php script JSON parse the the respone in .done() method. Here is the php script you can modify to your needs:

<?php
     $username1 = isset($_POST["username"]) ? $_POST["username"] : '';
    
     $password1 = isset($_POST["password"]) ? $_POST["password"] : '';

$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";

    ;  
    
    
   

if ($conn->query($sql) === TRUE) {
    
   echo json_encode(array('success' => 1));
} else{
    
    
  echo json_encode(array('success' => 0));
}





$conn->close();
?>

Javascript format date / time

For the date part:(month is 0-indexed while days are 1-indexed)

var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' +  date.getFullYear());

for the time you'll want to create a function to test different situations and convert.

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

How to format LocalDate to string?

A pretty nice way to do this is to use SimpleDateFormat I'll show you how:

SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);

I see that you have the date in a variable:

sdf.format(variable_name);

Cheers.

Print an integer in binary format in Java

Simply try it. If the scope is only printing the binary values of the given integer value. It can be positive or negative.

      public static void printBinaryNumbers(int n) {
        char[] arr = Integer.toBinaryString(n).toCharArray();
        StringBuilder sb = new StringBuilder();
        for (Character c : arr) {
          sb.append(c);
        }
        System.out.println(sb);
      }

input

5

Output

101

subtract two times in python

I had similar situation as you and I ended up with using external library called arrow.

Here is what it looks like:

>>> import arrow
>>> enter = arrow.get('12:30:45', 'HH:mm:ss')
>>> exit = arrow.now()
>>> duration = exit - enter
>>> duration
datetime.timedelta(736225, 14377, 757451)

Correct way to find max in an Array in Swift

var numbers = [1, 2, 7, 5];    
var val = sort(numbers){$0 > $1}[0];

Foreach value from POST from form

Use array-like fields:

<input name="name_for_the_items[]"/>

You can loop through the fields:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}

How to Fill an array from user input C#?

C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.

If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:

using Microsoft.VisualBasic;

You can do the following:

List<string> responses = new List<string>();
string response = "";

while(!(response = Interaction.InputBox("Please enter your information",
                                        "Window Title",
                                        "Default Text",
                                        xPosition,
                                        yPosition)).equals(""))
{
   responses.Add(response);
}

responses.ToArray();

About catching ANY exception

You can but you probably shouldn't:

try:
    do_something()
except:
    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

how to use getSharedPreferences in android

//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;  
prefsEditor = myPrefs.edit();  
//strVersionName->Any value to be stored  
prefsEditor.putString("STOREDVALUE", strVersionName);  
prefsEditor.commit();

//Get Preferenece  
SharedPreferences myPrefs;    
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);  
String StoredValue=myPrefs.getString("STOREDVALUE", "");

Try this..

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

Your code returns 0 if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.

>>> import commands
>>> ret = commands.getoutput("ps -p 2993 -o time --no-headers")
>>> print ret

Display calendar to pick a date in java

  1. Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.

  2. Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:

    TableModel datePicker = new DatePickerTable("01011999","12302000");
    
  3. Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:

    datePicker.interval = 15;
    
  4. Attach your table model into your JTable:

    JTable newtable = new JTable (datePicker);
    

    Your Java application now has a drop-down date selection dialog.

How do I improve ASP.NET MVC application performance?

I did all the answers above and it just didn't solve my problem.

Finally, I solved my slow site loading problem with setting PrecompileBeforePublish in Publish Profile to true. If you want to use msbuild you can use this argument:

 /p:PrecompileBeforePublish=true

It really help a lot. Now my MVC ASP.NET loads 10 times faster.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

Using domain Name may solve the problem (get domain name using powershell: $env:userdomain):

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    String principalName = "domainName\\userName";
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://URL:389/OU=ou-xx,DC=fr,DC=XXXXXX,DC=com");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, principalName);
    env.put(Context.SECURITY_CREDENTIALS, "Your Password");

    try {
        DirContext authContext = new InitialDirContext(env);
        // user is authenticated
        System.out.println("USER IS AUTHETICATED");
    } catch (AuthenticationException ex) {
        // Authentication failed
        System.out.println("AUTH FAILED : " + ex);

    } catch (NamingException ex) {
        ex.printStackTrace();
    }

How do I set the visibility of a text box in SSRS using an expression?

instead of this

=IIf((CountRows("ScannerStatisticsData")=0),False,True)

write only the expression when you want to hide

CountRows("ScannerStatisticsData")=0

or change the order of true and false places as below

=IIf((CountRows("ScannerStatisticsData")=0),True,False)

because the Visibility expression set up the Hidden value. that you can find above the text area as

" Set expression for: Hidden " 

Using the "start" command with parameters passed to the started program

Put the command inside a batch file, and call that with the parameters.

Also, did you try this yet? (Move end quote to encapsulate parameters)

start "c:\program files\Microsoft Virtual PC\Virtual PC.exe -pc MY-PC -launch"

An implementation of the fast Fourier transform (FFT) in C#

Math.NET's Iridium library provides a fast, regularly updated collection of math-related functions, including the FFT. It's licensed under the LGPL so you are free to use it in commercial products.

How do I make an http request using cookies on Android?

A cookie is just another HTTP header. You can always set it while making a HTTP call with the apache library or with HTTPUrlConnection. Either way you should be able to read and set HTTP cookies in this fashion.

You can read this article for more information.

I can share my peace of code to demonstrate how easy you can make it.

public static String getServerResponseByHttpGet(String url, String token) {

        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            get.setHeader("Cookie", "PHPSESSID=" + token + ";");
            Log.d(TAG, "Try to open => " + url);

            HttpResponse httpResponse = client.execute(get);
            int connectionStatusCode = httpResponse.getStatusLine().getStatusCode();
            Log.d(TAG, "Connection code: " + connectionStatusCode + " for request: " + url);

            HttpEntity entity = httpResponse.getEntity();
            String serverResponse = EntityUtils.toString(entity);
            Log.d(TAG, "Server response for request " + url + " => " + serverResponse);

            if(!isStatusOk(connectionStatusCode))
                return null;

            return serverResponse;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

Usage of $broadcast(), $emit() And $on() in AngularJS

  • Broadcast: We can pass the value from parent to child (i.e parent -> child controller.)
  • Emit: we can pass the value from child to parent (i.e.child ->parent controller.)
  • On: catch the event dispatched by $broadcast or $emit.

How to center a View inside of an Android Layout?

Add android:layout_centerInParent="true" to element which you want to center in the RelativeLayout

Difference in boto3 between resource, client, and session?

Here's some more detailed information on what Client, Resource, and Session are all about.

Client:

  • low-level AWS service access
  • generated from AWS service description
  • exposes botocore client to the developer
  • typically maps 1:1 with the AWS service API
  • all AWS service operations are supported by clients
  • snake-cased method names (e.g. ListBuckets API => list_buckets method)

Here's an example of client-level access to an S3 bucket's objects (at most 1000**):

import boto3

client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
    obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
    print(content['Key'], obj_dict['LastModified'])

** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.

Resource:

  • higher-level, object-oriented API
  • generated from resource description
  • uses identifiers and attributes
  • has actions (operations on resources)
  • exposes subresources and collections of AWS resources
  • does not provide 100% API coverage of AWS services

Here's the equivalent example using resource-level access to an S3 bucket's objects (all):

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
    print(obj.key, obj.last_modified)

Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.

You can see that the Resource version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client version of the code would actually be more complicated than shown above if you wanted to include pagination.

Session:

  • stores configuration information (primarily credentials and selected region)
  • allows you to create service clients and resources
  • boto3 creates a default session for you when needed

A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.

How to echo text during SQL script execution in SQLPLUS

The prompt command will echo text to the output:

prompt A useful comment.
select(*) from TableA;

Will be displayed as:

SQL> A useful comment.
SQL> 
  COUNT(*)
----------
     0

SQL alias for SELECT statement

Not sure exactly what you try to denote with that syntax, but in almost all RDBMS-es you can use a subquery in the FROM clause (sometimes called an "inline-view"):

SELECT..
FROM (
     SELECT ...
     FROM ...
     ) my_select
WHERE ...

In advanced "enterprise" RDBMS-es (like oracle, SQL Server, postgresql) you can use common table expressions which allows you to refer to a query by name and reuse it even multiple times:

-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;

(example from http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx)

Selenium WebDriver: Wait for complex page with JavaScript to load

You need to wait for Javascript and jQuery to finish loading. Execute Javascript to check if jQuery.active is 0 and document.readyState is complete, which means the JS and jQuery load is complete.

public boolean waitForJStoLoad() {

    WebDriverWait wait = new WebDriverWait(driver, 30);

    // wait for jQuery to load
    ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver driver) {
        try {
          return ((Long)executeJavaScript("return jQuery.active") == 0);
        }
        catch (Exception e) {
          return true;
        }
      }
    };

    // wait for Javascript to load
    ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver driver) {
        return executeJavaScript("return document.readyState")
            .toString().equals("complete");
      }
    };

  return wait.until(jQueryLoad) && wait.until(jsLoad);
}

How to split long commands over multiple lines in PowerShell

Splat Method with Calculations

If you choose splat method, beware calculations that are made using other parameters. In practice, sometimes I have to set variables first then create the hash table. Also, the format doesn't require single quotes around the key value or the semi-colon (as mentioned above).

Example of a call to a function that creates an Excel spreadsheet

$title = "Cut-off File Processing on $start_date_long_str"
$title_row = 1
$header_row = 2
$data_row_start = 3
$data_row_end = $($data_row_start + $($file_info_array.Count) - 1)

# use parameter hash table to make code more readable
$params = @{
    title = $title
    title_row = $title_row
    header_row = $header_row
    data_row_start = $data_row_start
    data_row_end = $data_row_end
}
$xl_wksht = Create-Excel-Spreadsheet @params

Note: The file array contains information that will affect how the spreadsheet is populated.

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Try this:

    private void comboBox1_KeyDown(object sender, KeyEventArgs e)
    {
        // comboBox1 is readonly
        e.SuppressKeyPress = true;
    }

Cross browser method to fit a child div to its parent's width

If you put position:relative; on the outer element, the inner element will place itself according to this one. Then a width:auto; on the inner element will be the same as the width of the outer.

Passing the argument to CMAKE via command prompt

CMake 3.13 on Ubuntu 16.04

This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:

$ cat CMakeLists.txt 
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE ) 
    message("MY_VARIABLE evaluates to True")
endif()

$ mkdir build && cd build

$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

What does PHP keyword 'var' do?

Answer: From php 5.3 and >, the var keyword is equivalent to public when declaring variables inside a class.

class myClass {
  var $x;
}

is the same as (for php 5.3 and >):

class myClass {
  public $x;
}

History: It was previously the norm for declaring variables in classes, though later became depreciated, but later (PHP 5.3) it became un-depreciated.

how to make a cell of table hyperlink

Easy with onclick-function and a javascript link:

<td onclick="location.href='yourpage.html'">go to yourpage</td>

How to align footer (div) to the bottom of the page?

I am a newbie and these methods are not working for me. However, I tried a margin-top property in css and simply added the value of content pixels +5.

Example: my content layout had a height of 1000px so I put a margin-top value of 1005px in the footer css which gave me a 5px border and a footer that sits delightfully at the bottom of my site.

Probably an amateur way of doing it, but EFFECTIVE!!!

How to remove &quot; from my Json in javascript?

i used replace feature in Notepad++ and replaced &quot; (without quotes) with " and result was valid json

Get the Last Inserted Id Using Laravel Eloquent

Use insertGetId to insert and get inserted id at the same time

From doc

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

By Model

$id = Model::insertGetId(["name"=>"Niklesh","email"=>"[email protected]"]);

By DB

$id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"[email protected]"]);

For more details : https://laravel.com/docs/5.5/queries#inserts

How to make clang compile to llvm IR

Given some C/C++ file foo.c:

> clang -S -emit-llvm foo.c

Produces foo.ll which is an LLVM IR file.

The -emit-llvm option can also be passed to the compiler front-end directly, and not the driver by means of -cc1:

> clang -cc1 foo.c -emit-llvm

Produces foo.ll with the IR. -cc1 adds some cool options like -ast-print. Check out -cc1 --help for more details.


To compile LLVM IR further to assembly, use the llc tool:

> llc foo.ll

Produces foo.s with assembly (defaulting to the machine architecture you run it on). llc is one of the LLVM tools - here is its documentation.

Best way to check if an PowerShell Object exist?

In your particular example perhaps you do not have to perform any checks at all. Is that possible that New-Object return null? I have never seen that. The command should fail in case of a problem and the rest of the code in the example will not be executed. So why should we do that checks at all?

Only in the code like below we need some checks (explicit comparison with $null is the best):

# we just try to get a new object
$ie = $null
try {
    $ie = New-Object -ComObject InternetExplorer.Application
}
catch {
    Write-Warning $_
}

# check and continuation
if ($ie -ne $null) {
    ...
}

How to get scrollbar position with Javascript?

it's like this :)

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});

Run a shell script with an html button

As stated by Luke you need to use a server side language, like php. This is a really simple php example:

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  exec("/path/to/name.sh");
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

Save this as myfilename.php and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...

Check div is hidden using jquery

You can use,

if (!$("#car-2").is(':visible'))
{
      alert('car 2 is hidden');
}

Comparing Arrays of Objects in JavaScript

As serialization doesn't work generally (only when the order of properties matches: JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})) you have to check the count of properties and compare each property as well:

_x000D_
_x000D_
const objectsEqual = (o1, o2) =>_x000D_
    Object.keys(o1).length === Object.keys(o2).length _x000D_
        && Object.keys(o1).every(p => o1[p] === o2[p]);_x000D_
_x000D_
const obj1 = { name: 'John', age: 33};_x000D_
const obj2 = { age: 33, name: 'John' };_x000D_
const obj3 = { name: 'John', age: 45 };_x000D_
        _x000D_
console.log(objectsEqual(obj1, obj2)); // true_x000D_
console.log(objectsEqual(obj1, obj3)); // false
_x000D_
_x000D_
_x000D_

If you need a deep comparison, you can call the function recursively:

_x000D_
_x000D_
const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };_x000D_
const obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };_x000D_
const obj3 = { name: 'John', age: 33 };_x000D_
_x000D_
const objectsEqual = (o1, o2) => _x000D_
    typeof o1 === 'object' && Object.keys(o1).length > 0 _x000D_
        ? Object.keys(o1).length === Object.keys(o2).length _x000D_
            && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))_x000D_
        : o1 === o2;_x000D_
        _x000D_
console.log(objectsEqual(obj1, obj2)); // true_x000D_
console.log(objectsEqual(obj1, obj3)); // false
_x000D_
_x000D_
_x000D_

Then it's easy to use this function to compare objects in arrays:

const arr1 = [obj1, obj1];
const arr2 = [obj1, obj2];
const arr3 = [obj1, obj3];

const arraysEqual = (a1, a2) => 
   a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));

console.log(arraysEqual(arr1, arr2)); // true
console.log(arraysEqual(arr1, arr3)); // false

IFrame: This content cannot be displayed in a frame

The X-Frame-Options is defined in the Http Header and not in the <head> section of the page you want to use in the iframe.

Accepted values are: DENY, SAMEORIGIN and ALLOW-FROM "url"

How do I find out which keystore was used to sign an app?

First, unzip the APK and extract the file /META-INF/ANDROID_.RSA (this file may also be CERT.RSA, but there should only be one .RSA file).

Then issue this command:

keytool -printcert -file ANDROID_.RSA

You will get certificate fingerprints like this:

     MD5:  B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB
     SHA1: 16:59:E7:E3:0C:AA:7A:0D:F2:0D:05:20:12:A8:85:0B:32:C5:4F:68
     Signature algorithm name: SHA1withRSA

Then use the keytool again to print out all the aliases of your signing keystore:

keytool -list -keystore my-signing-key.keystore

You will get a list of aliases and their certificate fingerprint:

android_key, Jan 23, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB

Voila! we can now determined the apk has been signed with this keystore, and with the alias 'android_key'.

Keytool is part of Java, so make sure your PATH has Java installation dir in it.

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s

On a server using a logon script, tell the logon to run the batch file. Jason

Delete certain lines in a txt file via a batch file

Use the following:

type file.txt | findstr /v ERROR | findstr /v REFERENCE

This has the advantage of using standard tools in the Windows OS, rather than having to find and install sed/awk/perl and such.

See the following transcript for it in operation:

C:\>type file.txt
Good Line of data
bad line of C:\Directory\ERROR\myFile.dll
Another good line of data
bad line: REFERENCE
Good line

C:\>type file.txt | findstr /v ERROR | findstr /v REFERENCE
Good Line of data
Another good line of data
Good line

SQL Server FOR EACH Loop

Here is an option with a table variable:

DECLARE @MyVar TABLE(Val DATETIME)
DECLARE @I INT, @StartDate DATETIME
SET @I = 1
SET @StartDate = '20100101'

WHILE @I <= 5
BEGIN
    INSERT INTO @MyVar(Val)
    VALUES(@StartDate)

    SET @StartDate = DATEADD(DAY,1,@StartDate)
    SET @I = @I + 1
END
SELECT *
FROM @MyVar

You can do the same with a temp table:

CREATE TABLE #MyVar(Val DATETIME)
DECLARE @I INT, @StartDate DATETIME
SET @I = 1
SET @StartDate = '20100101'

WHILE @I <= 5
BEGIN
    INSERT INTO #MyVar(Val)
    VALUES(@StartDate)

    SET @StartDate = DATEADD(DAY,1,@StartDate)
    SET @I = @I + 1
END
SELECT *
FROM #MyVar

You should tell us what is your main goal, as was said by @JohnFx, this could probably be done another (more efficient) way.

In Python How can I declare a Dynamic Array

you can declare a Numpy array dynamically for 1 dimension as shown below:

import numpy as np

n = 2
new_table = np.empty(shape=[n,1])

new_table[0,0] = 2
new_table[1,0] = 3
print(new_table)

The above example assumes we know we need to have 1 column but we want to allocate the number of rows dynamically (in this case the number or rows required is equal to 2)

output is shown below:

[[2.] [3.]]

UTL_FILE.FOPEN() procedure not accepting path for directory?

You need to register the directory with Oracle. fopen takes the name of a directory object, not the path. For example:

(you may need to login as SYS to execute these)

CREATE DIRECTORY MY_DIR AS 'C:\';

GRANT READ ON DIRECTORY MY_DIR TO SCOTT;

Then, you can refer to it in the call to fopen:

execute sal_status('MY_DIR','vin1.txt');

How do I delete multiple rows in Entity Framework (without foreach)

Thanh's answer worked best for me. Deleted all my records in a single server trip. I struggled with actually calling the extension method, so thought I would share mine (EF 6):

I added the extension method to a helper class in my MVC project and changed the name to "RemoveWhere". I inject a dbContext into my controllers, but you could also do a using.

// make a list of items to delete or just use conditionals against fields
var idsToFilter = dbContext.Products
    .Where(p => p.IsExpired)
    .Select(p => p.ProductId)
    .ToList();

// build the expression
Expression<Func<Product, bool>> deleteList = 
    (a) => idsToFilter.Contains(a.ProductId);

// Run the extension method (make sure you have `using namespace` at the top)
dbContext.RemoveWhere(deleteList);

This generated a single delete statement for the group.

3D Plotting from X, Y, Z Data, Excel or other Tools

You can use r libraries for 3 D plotting.

Steps are:

First create a data frame using data.frame() command.

Create a 3D plot by using scatterplot3D library.

Or You can also rotate your chart using rgl library by plot3d() command.

Alternately you can use plot3d() command from rcmdr library.

In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.

[http://in.mathworks.com/help/matlab/examples/creating-3-d-plots.html]

MySQL > Table doesn't exist. But it does (or it should)

For me on Mac OS (MySQL DMG Installation) a simple restart of the MySQL server solved the problem. I am guessing the hibernation caused it.

How do I check two or more conditions in one <c:if>?

Recommendation:

when you have more than one condition with and and or is better separate with () to avoid verification problems

<c:if test="${(not validID) and (addressIso == 'US' or addressIso == 'BR')}">

MySQL's now() +1 day

Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)

PHP Warning Permission denied (13) on session_start()

It seems that you don't have WRITE permission on /tmp.

Edit the configuration variable session.save_path with the function session_save_path() to 1 directory above public_html (so external users wouldn't access the info).

Does IMDB provide an API?

Another legal alternative to get movie info is the Rotten-Tomatoes API (by Fandango).

How to use the IEqualityComparer

Just code, with implementation of GetHashCode and NULL validation:

public class Class_reglementComparer : IEqualityComparer<Class_reglement>
{
    public bool Equals(Class_reglement x, Class_reglement y)
    {
        if (x is null || y is null))
            return false;

        return x.Numf == y.Numf;
    }

    public int GetHashCode(Class_reglement product)
    {
        //Check whether the object is null 
        if (product is null) return 0;

        //Get hash code for the Numf field if it is not null. 
        int hashNumf = product.hashNumf == null ? 0 : product.hashNumf.GetHashCode();

        return hashNumf;
    }
}

Example: list of Class_reglement distinct by Numf

List<Class_reglement> items = items.Distinct(new Class_reglementComparer());

Android button font size

I tried to put the font size in the styles.xml but when i went to use it it was only allowing resources from the dimen folder so put it in there instead, dont know it this is right

        <Button
                android:layout_weight="1"
                android:id="@+id/three_btn"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:onClick="onButtonClick"
                android:textColor="#EEEEEE"
                android:textStyle="bold"
                android:textSize="@dimen/buttonFontSize"
                android:text="3"/>

repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

In your pom.xml you should add distributionManagement configuration to where to deploy.

In the following example I have used file system as the locations.

<distributionManagement>
       <repository>
         <id>internal.repo</id>
         <name>Internal repo</name>
         <url>file:///home/thara/testesb/in</url>
       </repository>
   </distributionManagement>

you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :

mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in

CSS: fixed position on x-axis but not y?

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

Thanks

To delay JavaScript function call using jQuery

function sample() {
    alert("This is sample function");
}

$(function() {
    $("#button").click(function() {
        setTimeout(sample, 2000);
    });

});

jsFiddle.

If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

Useful link here: Access Tomcat Manager App from different host

From Tomcat version 8 onward's, manager/html url won't be accessible to anyone except localhost.

In order to access /manager/html url, you need to do below change in context.xml of manager app. 1. Go to /apache-tomcat-8.5.23/webapps/manager/META-INF location, then edit context.xml

<Context antiResourceLocking="false" privileged="true" >
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="^.*$" />
 ......
</Context>
  1. Restart the server.

How do I remove the non-numeric character from a string in java?

you could use a recursive method like below:

public static String getAllNumbersFromString(String input) {
        if (input == null || input.length() == 0) {
            return "";
        }
        char c = input.charAt(input.length() - 1);
        String newinput = input.substring(0, input.length() - 1);

            if (c >= '0' && c<= '9') {
            return getAllNumbersFromString(newinput) + c;

        } else {
            return getAllNumbersFromString(newinput);
        }
    } 

Sending HTML mail using a shell script

Mime header and from, to address also can be included in the html file it self.

Command

cat cpu_alert.html | /usr/lib/sendmail -t

cpu_alert.html file sample.

From: [email protected]
To: [email protected]
Subject: CPU utilization heigh
Mime-Version: 1.0
Content-Type: text/html

<h1>Mail body will be here</h1>
The mail body should start after one blank line from the header.

Sample code available here: http://sugunan.net/git/slides/shell/cpu.php

List of tuples to dictionary

With dict comprehension:

h = {k:v for k,v in l}

How to determine the current language of a wordpress page when using polylang?

I use something like this:

<?php 

$lang = get_bloginfo("language"); 

if ($lang == 'fr-FR') : ?>

   <p>Bienvenue!</p>

<?php endif; ?>

Xcode/Simulator: How to run older iOS version?

In XCode under Targets, right-click on your project and Get Info. Under the Build tab look for iOS Deployment Target. By changing this you should be able to test different iOS version.

alt text

How to check if a table exists in MS Access for vb macros

This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.

Basically, which works fastest depends on what database object you use with it.

How can I get Eclipse to show .* files?

Preferences -> Remote Systems -> Files -> Show hidden files

(make sure this is checked)

JavaScript replace \n with <br />

Handles either type of line break

str.replace(new RegExp('\r?\n','g'), '<br />');

How to sort findAll Doctrine's method?

Simple:

$this->getDoctrine()->getRepository('AcmeBundle:User')->findBy(
    array(),
    array('username' => 'ASC')
);

Using std::max_element on a vector<double>

As others have said, std::max_element() and std::min_element() return iterators, which need to be dereferenced to obtain the value.

The advantage of returning an iterator (rather than just the value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.

For example (using C++11 for brevity):

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};

    auto biggest = std::max_element(std::begin(v), std::end(v));
    std::cout << "Max element is " << *biggest
        << " at position " << std::distance(std::begin(v), biggest) << std::endl;

    auto smallest = std::min_element(std::begin(v), std::end(v));
    std::cout << "min element is " << *smallest
        << " at position " << std::distance(std::begin(v), smallest) << std::endl;
}

This yields:

Max element is 5 at position 4
min element is 1 at position 0

Note:

Using std::minmax_element() as suggested in the comments above may be faster for large data sets, but may give slightly different results. The values for my example above would be the same, but the position of the "max" element would be 9 since...

If several elements are equivalent to the largest element, the iterator to the last such element is returned.

Execute raw SQL using Doctrine 2

How to execute a raw Query and return the data.

Hook onto your manager and make a new connection:

$manager = $this->getDoctrine()->getManager();
$conn = $manager->getConnection();

Create your query and fetchAll:

$result= $conn->query('select foobar from mytable')->fetchAll();

Get the data out of result like this:

$this->appendStringToFile("first row foobar is: " . $result[0]['foobar']);

What is the difference between HTML tags <div> and <span>?

This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc.

For example:

<div>This a large main division, with <span>a small bit</span> of spanned text!</div>

Note that it is illegal to place a block-level element within an inline element, so:

<div>Some <span>text that <div>I want</div> to mark</span> up</div>

...is illegal.


EDIT: As of HTML5, some block elements can be placed inside of some inline elements. See the MDN reference here for a pretty clear listing. The above is still illegal, as <span> only accepts phrasing content, and <div> is flow content.


You asked for some concrete examples, so is one taken from my bowling website, BowlSK:

_x000D_
_x000D_
<div id="header">_x000D_
  <div id="userbar">_x000D_
    Hi there, <span class="username">Chris Marasti-Georg</span> |_x000D_
    <a href="/edit-profile.html">Profile</a> |_x000D_
    <a href="https://www.bowlsk.com/_ah/logout?...">Sign out</a>_x000D_
  </div>_x000D_
  <h1><a href="/">Bowl<span class="sk">SK</span></a></h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ok, what's going on?

At the top of my page, I have a logical section, the "header". Since this is a section, I use a div (with an appropriate id). Within that, I have a couple of sections: the user bar and the actual page title. The title uses the appropriate tag, h1. The userbar, being a section, is wrapped in a div. Within that, the username is wrapped in a span, so that I can change the style. As you can see, I have also wrapped a span around 2 letters in the title - this allows me to change their color in my stylesheet.

Also note that HTML5 includes a broad new set of elements that define common page structures, such as article, section, nav, etc.

Section 4.4 of the HTML 5 working draft lists them and gives hints as to their usage. HTML5 is still a working spec, so nothing is "final" yet, but it is highly doubtful that any of these elements are going anywhere. There is a javascript hack that you will need to use if you want to style these elements in some older version of IE - You need to create one of each element using document.createElement before any of those elements are specified in your source. There are a bunch of libraries that will take care of this for you - a quick Google search turned up html5shiv.

How to iterate std::set?

Another example for the C++11 standard:

set<int> data;
data.insert(4);
data.insert(5);

for (const int &number : data)
  cout << number;

How can I pair socks from a pile efficiently?

When I sort socks, I do an approximate radix sort, dropping socks near other socks of the same colour/pattern type. Except in the case when I can see an exact match at/near the location I'm about to drop the sock I extract the pair at that point.

Almost all the other algorithms (including the top scoring answer by usr) sort, then remove pairs. I find that, as a human, it is better to minimize the number of socks being considered at one time.

I do this by:

  1. Picking a distinctive sock (whatever catches my eye first in the pile).
  2. Starting a radix sort from that conceptual location by pulling socks from the pile based on similarity to that one.
  3. Place the new sock near into the current pile, with a distance based on how different it is. If you find yourself putting the sock on top of another because it is identical, form the pair there, and remove them. This means that future comparisons take less effort to find the correct place.

This takes advantage of the human ability to fuzzy-match in O(1) time, which is somewhat equivalent to the establishment of a hash-map on a computing device.

By pulling the distinctive socks first, you leave space to "zoom" in on the features which are less distinctive, to begin with.

After eliminating the fluro coloured, the socks with stripes, and the three pairs of long socks, you might end up with mostly white socks roughly sorted by how worn they are.

At some point, the differences between socks are small enough that other people won't notice the difference, and any further matching effort is not needed.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

By default

  1. Primitives are passed by value. Unlikely to Java, string is primitive in PHP
  2. Arrays of primitives are passed by value
  3. Objects are passed by reference
  4. Arrays of objects are passed by value (the array) but each object is passed by reference.

    <?php
    $obj=new stdClass();
    $obj->field='world';
    
    $original=array($obj);
    
    
    function example($hello) {
        $hello[0]->field='mundo'; // change will be applied in $original
        $hello[1]=new stdClass(); // change will not be applied in $original
        $
    }
    
    example($original);
    
    var_dump($original);
    // array(1) { [0]=> object(stdClass)#1 (1) { ["field"]=> string(5) "mundo" } } 
    

Note: As an optimization, every single value is passed as reference until its modified inside the function. If it's modified and the value was passed by reference then, it's copied and the copy is modified.

How can I listen for keypress event on the whole page?

I think this does the best job

https://angular.io/api/platform-browser/EventManager

for instance in app.component

constructor(private eventManager: EventManager) {
    const removeGlobalEventListener = this.eventManager.addGlobalEventListener(
      'document',
      'keypress',
      (ev) => {
        console.log('ev', ev);
      }
    );
  }

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

How to run html file on localhost?

You can install Xampp and run apache serve and place your file to www folder and access your file at localhost/{file name} or simply at localhost if your file is named index.html

concatenate two strings

The best way in my eyes is to use the concat() method provided by the String class itself.

The useage would, in your case, look like this:

String myConcatedString = cursor.getString(numcol).concat('-').
       concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));

Fastest way to check if a value exists in a list

Or use __contains__:

sequence.__contains__(value)

Demo:

>>> l = [1, 2, 3]
>>> l.__contains__(3)
True
>>> 

How to load/reference a file as a File instance from the classpath

Try getting hold of a URL for your classpath resource:

URL url = this.getClass().getResource("/com/path/to/file.txt")

Then create a file using the constructor that accepts a URI:

File file = new File(url.toURI());

Add a properties file to IntelliJ's classpath

This is one of the dumb mistakes I've done. I spent a lot of time trying to debug this problem and tried all the responses posted above, but in the end, it was one of my many dumb mistakes.

I was using org.apache.logging.log4j.Logger (:fml:) whereas I should have used org.apache.log4j.Logger. Using this correct logger saved my evening.

Interface/enum listing standard mime-type constants

I solved this with a static class:

@SuppressWarnings("serial")
public class MimeTypes {

    private static final HashMap<String, String> mimeTypes;

    static {
        mimeTypes = new HashMap<String, String>() {
            {
                put(".323", "text/h323");
                put(".3g2", "video/3gpp2");
                put(".3gp", "video/3gpp");
                put(".3gp2", "video/3gpp2");
                put(".3gpp", "video/3gpp");
                put(".7z", "application/x-7z-compressed");
                put(".aa", "audio/audible");
                put(".AAC", "audio/aac");
                put(".aaf", "application/octet-stream");
                put(".aax", "audio/vnd.audible.aax");
                put(".ac3", "audio/ac3");
                put(".aca", "application/octet-stream");
                put(".accda", "application/msaccess.addin");
                put(".accdb", "application/msaccess");
                put(".accdc", "application/msaccess.cab");
                put(".accde", "application/msaccess");
                put(".accdr", "application/msaccess.runtime");
                put(".accdt", "application/msaccess");
                put(".accdw", "application/msaccess.webapplication");
                put(".accft", "application/msaccess.ftemplate");
                put(".acx", "application/internet-property-stream");
                put(".AddIn", "text/xml");
                put(".ade", "application/msaccess");
                put(".adobebridge", "application/x-bridge-url");
                put(".adp", "application/msaccess");
                put(".ADT", "audio/vnd.dlna.adts");
                put(".ADTS", "audio/aac");
                put(".afm", "application/octet-stream");
                put(".ai", "application/postscript");
                put(".aif", "audio/x-aiff");
                put(".aifc", "audio/aiff");
                put(".aiff", "audio/aiff");
                put(".air", "application/vnd.adobe.air-application-installer-package+zip");
                put(".amc", "application/x-mpeg");
                put(".application", "application/x-ms-application");
                put(".art", "image/x-jg");
                put(".asa", "application/xml");
                put(".asax", "application/xml");
                put(".ascx", "application/xml");
                put(".asd", "application/octet-stream");
                put(".asf", "video/x-ms-asf");
                put(".ashx", "application/xml");
                put(".asi", "application/octet-stream");
                put(".asm", "text/plain");
                put(".asmx", "application/xml");
                put(".aspx", "application/xml");
                put(".asr", "video/x-ms-asf");
                put(".asx", "video/x-ms-asf");
                put(".atom", "application/atom+xml");
                put(".au", "audio/basic");
                put(".avi", "video/x-msvideo");
                put(".axs", "application/olescript");
                put(".bas", "text/plain");
                put(".bcpio", "application/x-bcpio");
                put(".bin", "application/octet-stream");
                put(".bmp", "image/bmp");
                put(".c", "text/plain");
                put(".cab", "application/octet-stream");
                put(".caf", "audio/x-caf");
                put(".calx", "application/vnd.ms-office.calx");
                put(".cat", "application/vnd.ms-pki.seccat");
                put(".cc", "text/plain");
                put(".cd", "text/plain");
                put(".cdda", "audio/aiff");
                put(".cdf", "application/x-cdf");
                put(".cer", "application/x-x509-ca-cert");
                put(".chm", "application/octet-stream");
                put(".class", "application/x-java-applet");
                put(".clp", "application/x-msclip");
                put(".cmx", "image/x-cmx");
                put(".cnf", "text/plain");
                put(".cod", "image/cis-cod");
                put(".config", "application/xml");
                put(".contact", "text/x-ms-contact");
                put(".coverage", "application/xml");
                put(".cpio", "application/x-cpio");
                put(".cpp", "text/plain");
                put(".crd", "application/x-mscardfile");
                put(".crl", "application/pkix-crl");
                put(".crt", "application/x-x509-ca-cert");
                put(".cs", "text/plain");
                put(".csdproj", "text/plain");
                put(".csh", "application/x-csh");
                put(".csproj", "text/plain");
                put(".css", "text/css");
                put(".csv", "text/csv");
                put(".cur", "application/octet-stream");
                put(".cxx", "text/plain");
                put(".dat", "application/octet-stream");
                put(".datasource", "application/xml");
                put(".dbproj", "text/plain");
                put(".dcr", "application/x-director");
                put(".def", "text/plain");
                put(".deploy", "application/octet-stream");
                put(".der", "application/x-x509-ca-cert");
                put(".dgml", "application/xml");
                put(".dib", "image/bmp");
                put(".dif", "video/x-dv");
                put(".dir", "application/x-director");
                put(".disco", "text/xml");
                put(".dll", "application/x-msdownload");
                put(".dll.config", "text/xml");
                put(".dlm", "text/dlm");
                put(".doc", "application/msword");
                put(".docm", "application/vnd.ms-word.document.macroEnabled.12");
                put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                put(".dot", "application/msword");
                put(".dotm", "application/vnd.ms-word.template.macroEnabled.12");
                put(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
                put(".dsp", "application/octet-stream");
                put(".dsw", "text/plain");
                put(".dtd", "text/xml");
                put(".dtsConfig", "text/xml");
                put(".dv", "video/x-dv");
                put(".dvi", "application/x-dvi");
                put(".dwf", "drawing/x-dwf");
                put(".dwp", "application/octet-stream");
                put(".dxr", "application/x-director");
                put(".eml", "message/rfc822");
                put(".emz", "application/octet-stream");
                put(".eot", "application/octet-stream");
                put(".eps", "application/postscript");
                put(".etl", "application/etl");
                put(".etx", "text/x-setext");
                put(".evy", "application/envoy");
                put(".exe", "application/octet-stream");
                put(".exe.config", "text/xml");
                put(".fdf", "application/vnd.fdf");
                put(".fif", "application/fractals");
                put(".filters", "Application/xml");
                put(".fla", "application/octet-stream");
                put(".flr", "x-world/x-vrml");
                put(".flv", "video/x-flv");
                put(".fsscript", "application/fsharp-script");
                put(".fsx", "application/fsharp-script");
                put(".generictest", "application/xml");
                put(".gif", "image/gif");
                put(".group", "text/x-ms-group");
                put(".gsm", "audio/x-gsm");
                put(".gtar", "application/x-gtar");
                put(".gz", "application/x-gzip");
                put(".h", "text/plain");
                put(".hdf", "application/x-hdf");
                put(".hdml", "text/x-hdml");
                put(".hhc", "application/x-oleobject");
                put(".hhk", "application/octet-stream");
                put(".hhp", "application/octet-stream");
                put(".hlp", "application/winhlp");
                put(".hpp", "text/plain");
                put(".hqx", "application/mac-binhex40");
                put(".hta", "application/hta");
                put(".htc", "text/x-component");
                put(".htm", "text/html");
                put(".html", "text/html");
                put(".htt", "text/webviewhtml");
                put(".hxa", "application/xml");
                put(".hxc", "application/xml");
                put(".hxd", "application/octet-stream");
                put(".hxe", "application/xml");
                put(".hxf", "application/xml");
                put(".hxh", "application/octet-stream");
                put(".hxi", "application/octet-stream");
                put(".hxk", "application/xml");
                put(".hxq", "application/octet-stream");
                put(".hxr", "application/octet-stream");
                put(".hxs", "application/octet-stream");
                put(".hxt", "text/html");
                put(".hxv", "application/xml");
                put(".hxw", "application/octet-stream");
                put(".hxx", "text/plain");
                put(".i", "text/plain");
                put(".ico", "image/x-icon");
                put(".ics", "application/octet-stream");
                put(".idl", "text/plain");
                put(".ief", "image/ief");
                put(".iii", "application/x-iphone");
                put(".inc", "text/plain");
                put(".inf", "application/octet-stream");
                put(".inl", "text/plain");
                put(".ins", "application/x-internet-signup");
                put(".ipa", "application/x-itunes-ipa");
                put(".ipg", "application/x-itunes-ipg");
                put(".ipproj", "text/plain");
                put(".ipsw", "application/x-itunes-ipsw");
                put(".iqy", "text/x-ms-iqy");
                put(".isp", "application/x-internet-signup");
                put(".ite", "application/x-itunes-ite");
                put(".itlp", "application/x-itunes-itlp");
                put(".itms", "application/x-itunes-itms");
                put(".itpc", "application/x-itunes-itpc");
                put(".IVF", "video/x-ivf");
                put(".jar", "application/java-archive");
                put(".java", "application/octet-stream");
                put(".jck", "application/liquidmotion");
                put(".jcz", "application/liquidmotion");
                put(".jfif", "image/pjpeg");
                put(".jnlp", "application/x-java-jnlp-file");
                put(".jpb", "application/octet-stream");
                put(".jpe", "image/jpeg");
                put(".jpeg", "image/jpeg");
                put(".jpg", "image/jpeg");
                put(".js", "application/x-javascript");
                put(".json", "application/json");
                put(".jsx", "text/jscript");
                put(".jsxbin", "text/plain");
                put(".latex", "application/x-latex");
                put(".library-ms", "application/windows-library+xml");
                put(".lit", "application/x-ms-reader");
                put(".loadtest", "application/xml");
                put(".lpk", "application/octet-stream");
                put(".lsf", "video/x-la-asf");
                put(".lst", "text/plain");
                put(".lsx", "video/x-la-asf");
                put(".lzh", "application/octet-stream");
                put(".m13", "application/x-msmediaview");
                put(".m14", "application/x-msmediaview");
                put(".m1v", "video/mpeg");
                put(".m2t", "video/vnd.dlna.mpeg-tts");
                put(".m2ts", "video/vnd.dlna.mpeg-tts");
                put(".m2v", "video/mpeg");
                put(".m3u", "audio/x-mpegurl");
                put(".m3u8", "audio/x-mpegurl");
                put(".m4a", "audio/m4a");
                put(".m4b", "audio/m4b");
                put(".m4p", "audio/m4p");
                put(".m4r", "audio/x-m4r");
                put(".m4v", "video/x-m4v");
                put(".mac", "image/x-macpaint");
                put(".mak", "text/plain");
                put(".man", "application/x-troff-man");
                put(".manifest", "application/x-ms-manifest");
                put(".map", "text/plain");
                put(".master", "application/xml");
                put(".mda", "application/msaccess");
                put(".mdb", "application/x-msaccess");
                put(".mde", "application/msaccess");
                put(".mdp", "application/octet-stream");
                put(".me", "application/x-troff-me");
                put(".mfp", "application/x-shockwave-flash");
                put(".mht", "message/rfc822");
                put(".mhtml", "message/rfc822");
                put(".mid", "audio/mid");
                put(".midi", "audio/mid");
                put(".mix", "application/octet-stream");
                put(".mk", "text/plain");
                put(".mmf", "application/x-smaf");
                put(".mno", "text/xml");
                put(".mny", "application/x-msmoney");
                put(".mod", "video/mpeg");
                put(".mov", "video/quicktime");
                put(".movie", "video/x-sgi-movie");
                put(".mp2", "video/mpeg");
                put(".mp2v", "video/mpeg");
                put(".mp3", "audio/mpeg");
                put(".mp4", "video/mp4");
                put(".mp4v", "video/mp4");
                put(".mpa", "video/mpeg");
                put(".mpe", "video/mpeg");
                put(".mpeg", "video/mpeg");
                put(".mpf", "application/vnd.ms-mediapackage");
                put(".mpg", "video/mpeg");
                put(".mpp", "application/vnd.ms-project");
                put(".mpv2", "video/mpeg");
                put(".mqv", "video/quicktime");
                put(".ms", "application/x-troff-ms");
                put(".msi", "application/octet-stream");
                put(".mso", "application/octet-stream");
                put(".mts", "video/vnd.dlna.mpeg-tts");
                put(".mtx", "application/xml");
                put(".mvb", "application/x-msmediaview");
                put(".mvc", "application/x-miva-compiled");
                put(".mxp", "application/x-mmxp");
                put(".nc", "application/x-netcdf");
                put(".nsc", "video/x-ms-asf");
                put(".nws", "message/rfc822");
                put(".ocx", "application/octet-stream");
                put(".oda", "application/oda");
                put(".odc", "text/x-ms-odc");
                put(".odh", "text/plain");
                put(".odl", "text/plain");
                put(".odp", "application/vnd.oasis.opendocument.presentation");
                put(".ods", "application/oleobject");
                put(".odt", "application/vnd.oasis.opendocument.text");
                put(".one", "application/onenote");
                put(".onea", "application/onenote");
                put(".onepkg", "application/onenote");
                put(".onetmp", "application/onenote");
                put(".onetoc", "application/onenote");
                put(".onetoc2", "application/onenote");
                put(".orderedtest", "application/xml");
                put(".osdx", "application/opensearchdescription+xml");
                put(".p10", "application/pkcs10");
                put(".p12", "application/x-pkcs12");
                put(".p7b", "application/x-pkcs7-certificates");
                put(".p7c", "application/pkcs7-mime");
                put(".p7m", "application/pkcs7-mime");
                put(".p7r", "application/x-pkcs7-certreqresp");
                put(".p7s", "application/pkcs7-signature");
                put(".pbm", "image/x-portable-bitmap");
                put(".pcast", "application/x-podcast");
                put(".pct", "image/pict");
                put(".pcx", "application/octet-stream");
                put(".pcz", "application/octet-stream");
                put(".pdf", "application/pdf");
                put(".pfb", "application/octet-stream");
                put(".pfm", "application/octet-stream");
                put(".pfx", "application/x-pkcs12");
                put(".pgm", "image/x-portable-graymap");
                put(".pic", "image/pict");
                put(".pict", "image/pict");
                put(".pkgdef", "text/plain");
                put(".pkgundef", "text/plain");
                put(".pko", "application/vnd.ms-pki.pko");
                put(".pls", "audio/scpls");
                put(".pma", "application/x-perfmon");
                put(".pmc", "application/x-perfmon");
                put(".pml", "application/x-perfmon");
                put(".pmr", "application/x-perfmon");
                put(".pmw", "application/x-perfmon");
                put(".png", "image/png");
                put(".pnm", "image/x-portable-anymap");
                put(".pnt", "image/x-macpaint");
                put(".pntg", "image/x-macpaint");
                put(".pnz", "image/png");
                put(".pot", "application/vnd.ms-powerpoint");
                put(".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12");
                put(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
                put(".ppa", "application/vnd.ms-powerpoint");
                put(".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12");
                put(".ppm", "image/x-portable-pixmap");
                put(".pps", "application/vnd.ms-powerpoint");
                put(".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12");
                put(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
                put(".ppt", "application/vnd.ms-powerpoint");
                put(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
                put(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
                put(".prf", "application/pics-rules");
                put(".prm", "application/octet-stream");
                put(".prx", "application/octet-stream");
                put(".ps", "application/postscript");
                put(".psc1", "application/PowerShell");
                put(".psd", "application/octet-stream");
                put(".psess", "application/xml");
                put(".psm", "application/octet-stream");
                put(".psp", "application/octet-stream");
                put(".pub", "application/x-mspublisher");
                put(".pwz", "application/vnd.ms-powerpoint");
                put(".qht", "text/x-html-insertion");
                put(".qhtm", "text/x-html-insertion");
                put(".qt", "video/quicktime");
                put(".qti", "image/x-quicktime");
                put(".qtif", "image/x-quicktime");
                put(".qtl", "application/x-quicktimeplayer");
                put(".qxd", "application/octet-stream");
                put(".ra", "audio/x-pn-realaudio");
                put(".ram", "audio/x-pn-realaudio");
                put(".rar", "application/octet-stream");
                put(".ras", "image/x-cmu-raster");
                put(".rat", "application/rat-file");
                put(".rc", "text/plain");
                put(".rc2", "text/plain");
                put(".rct", "text/plain");
                put(".rdlc", "application/xml");
                put(".resx", "application/xml");
                put(".rf", "image/vnd.rn-realflash");
                put(".rgb", "image/x-rgb");
                put(".rgs", "text/plain");
                put(".rm", "application/vnd.rn-realmedia");
                put(".rmi", "audio/mid");
                put(".rmp", "application/vnd.rn-rn_music_package");
                put(".roff", "application/x-troff");
                put(".rpm", "audio/x-pn-realaudio-plugin");
                put(".rqy", "text/x-ms-rqy");
                put(".rtf", "application/rtf");
                put(".rtx", "text/richtext");
                put(".ruleset", "application/xml");
                put(".s", "text/plain");
                put(".safariextz", "application/x-safari-safariextz");
                put(".scd", "application/x-msschedule");
                put(".sct", "text/scriptlet");
                put(".sd2", "audio/x-sd2");
                put(".sdp", "application/sdp");
                put(".sea", "application/octet-stream");
                put(".searchConnector-ms", "application/windows-search-connector+xml");
                put(".setpay", "application/set-payment-initiation");
                put(".setreg", "application/set-registration-initiation");
                put(".settings", "application/xml");
                put(".sgimb", "application/x-sgimb");
                put(".sgml", "text/sgml");
                put(".sh", "application/x-sh");
                put(".shar", "application/x-shar");
                put(".shtml", "text/html");
                put(".sit", "application/x-stuffit");
                put(".sitemap", "application/xml");
                put(".skin", "application/xml");
                put(".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12");
                put(".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide");
                put(".slk", "application/vnd.ms-excel");
                put(".sln", "text/plain");
                put(".slupkg-ms", "application/x-ms-license");
                put(".smd", "audio/x-smd");
                put(".smi", "application/octet-stream");
                put(".smx", "audio/x-smd");
                put(".smz", "audio/x-smd");
                put(".snd", "audio/basic");
                put(".snippet", "application/xml");
                put(".snp", "application/octet-stream");
                put(".sol", "text/plain");
                put(".sor", "text/plain");
                put(".spc", "application/x-pkcs7-certificates");
                put(".spl", "application/futuresplash");
                put(".src", "application/x-wais-source");
                put(".srf", "text/plain");
                put(".SSISDeploymentManifest", "text/xml");
                put(".ssm", "application/streamingmedia");
                put(".sst", "application/vnd.ms-pki.certstore");
                put(".stl", "application/vnd.ms-pki.stl");
                put(".sv4cpio", "application/x-sv4cpio");
                put(".sv4crc", "application/x-sv4crc");
                put(".svc", "application/xml");
                put(".swf", "application/x-shockwave-flash");
                put(".t", "application/x-troff");
                put(".tar", "application/x-tar");
                put(".tcl", "application/x-tcl");
                put(".testrunconfig", "application/xml");
                put(".testsettings", "application/xml");
                put(".tex", "application/x-tex");
                put(".texi", "application/x-texinfo");
                put(".texinfo", "application/x-texinfo");
                put(".tgz", "application/x-compressed");
                put(".thmx", "application/vnd.ms-officetheme");
                put(".thn", "application/octet-stream");
                put(".tif", "image/tiff");
                put(".tiff", "image/tiff");
                put(".tlh", "text/plain");
                put(".tli", "text/plain");
                put(".toc", "application/octet-stream");
                put(".tr", "application/x-troff");
                put(".trm", "application/x-msterminal");
                put(".trx", "application/xml");
                put(".ts", "video/vnd.dlna.mpeg-tts");
                put(".tsv", "text/tab-separated-values");
                put(".ttf", "application/octet-stream");
                put(".tts", "video/vnd.dlna.mpeg-tts");
                put(".txt", "text/plain");
                put(".u32", "application/octet-stream");
                put(".uls", "text/iuls");
                put(".user", "text/plain");
                put(".ustar", "application/x-ustar");
                put(".vb", "text/plain");
                put(".vbdproj", "text/plain");
                put(".vbk", "video/mpeg");
                put(".vbproj", "text/plain");
                put(".vbs", "text/vbscript");
                put(".vcf", "text/x-vcard");
                put(".vcproj", "Application/xml");
                put(".vcs", "text/plain");
                put(".vcxproj", "Application/xml");
                put(".vddproj", "text/plain");
                put(".vdp", "text/plain");
                put(".vdproj", "text/plain");
                put(".vdx", "application/vnd.ms-visio.viewer");
                put(".vml", "text/xml");
                put(".vscontent", "application/xml");
                put(".vsct", "text/xml");
                put(".vsd", "application/vnd.visio");
                put(".vsi", "application/ms-vsi");
                put(".vsix", "application/vsix");
                put(".vsixlangpack", "text/xml");
                put(".vsixmanifest", "text/xml");
                put(".vsmdi", "application/xml");
                put(".vspscc", "text/plain");
                put(".vss", "application/vnd.visio");
                put(".vsscc", "text/plain");
                put(".vssettings", "text/xml");
                put(".vssscc", "text/plain");
                put(".vst", "application/vnd.visio");
                put(".vstemplate", "text/xml");
                put(".vsto", "application/x-ms-vsto");
                put(".vsw", "application/vnd.visio");
                put(".vsx", "application/vnd.visio");
                put(".vtx", "application/vnd.visio");
                put(".wav", "audio/wav");
                put(".wave", "audio/wav");
                put(".wax", "audio/x-ms-wax");
                put(".wbk", "application/msword");
                put(".wbmp", "image/vnd.wap.wbmp");
                put(".wcm", "application/vnd.ms-works");
                put(".wdb", "application/vnd.ms-works");
                put(".wdp", "image/vnd.ms-photo");
                put(".webarchive", "application/x-safari-webarchive");
                put(".webtest", "application/xml");
                put(".wiq", "application/xml");
                put(".wiz", "application/msword");
                put(".wks", "application/vnd.ms-works");
                put(".WLMP", "application/wlmoviemaker");
                put(".wlpginstall", "application/x-wlpg-detect");
                put(".wlpginstall3", "application/x-wlpg3-detect");
                put(".wm", "video/x-ms-wm");
                put(".wma", "audio/x-ms-wma");
                put(".wmd", "application/x-ms-wmd");
                put(".wmf", "application/x-msmetafile");
                put(".wml", "text/vnd.wap.wml");
                put(".wmlc", "application/vnd.wap.wmlc");
                put(".wmls", "text/vnd.wap.wmlscript");
                put(".wmlsc", "application/vnd.wap.wmlscriptc");
                put(".wmp", "video/x-ms-wmp");
                put(".wmv", "video/x-ms-wmv");
                put(".wmx", "video/x-ms-wmx");
                put(".wmz", "application/x-ms-wmz");
                put(".wpl", "application/vnd.ms-wpl");
                put(".wps", "application/vnd.ms-works");
                put(".wri", "application/x-mswrite");
                put(".wrl", "x-world/x-vrml");
                put(".wrz", "x-world/x-vrml");
                put(".wsc", "text/scriptlet");
                put(".wsdl", "text/xml");
                put(".wvx", "video/x-ms-wvx");
                put(".x", "application/directx");
                put(".xaf", "x-world/x-vrml");
                put(".xaml", "application/xaml+xml");
                put(".xap", "application/x-silverlight-app");
                put(".xbap", "application/x-ms-xbap");
                put(".xbm", "image/x-xbitmap");
                put(".xdr", "text/plain");
                put(".xht", "application/xhtml+xml");
                put(".xhtml", "application/xhtml+xml");
                put(".xla", "application/vnd.ms-excel");
                put(".xlam", "application/vnd.ms-excel.addin.macroEnabled.12");
                put(".xlc", "application/vnd.ms-excel");
                put(".xld", "application/vnd.ms-excel");
                put(".xlk", "application/vnd.ms-excel");
                put(".xll", "application/vnd.ms-excel");
                put(".xlm", "application/vnd.ms-excel");
                put(".xls", "application/vnd.ms-excel");
                put(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12");
                put(".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12");
                put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                put(".xlt", "application/vnd.ms-excel");
                put(".xltm", "application/vnd.ms-excel.template.macroEnabled.12");
                put(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
                put(".xlw", "application/vnd.ms-excel");
                put(".xml", "text/xml");
                put(".xmta", "application/xml");
                put(".xof", "x-world/x-vrml");
                put(".XOML", "text/plain");
                put(".xpm", "image/x-xpixmap");
                put(".xps", "application/vnd.ms-xpsdocument");
                put(".xrm-ms", "text/xml");
                put(".xsc", "application/xml");
                put(".xsd", "text/xml");
                put(".xsf", "text/xml");
                put(".xsl", "text/xml");
                put(".xslt", "text/xml");
                put(".xsn", "application/octet-stream");
                put(".xss", "application/xml");
                put(".xtp", "application/octet-stream");
                put(".xwd", "image/x-xwindowdump");
                put(".z", "application/x-compress");
                put(".zip", "application/x-zip-compressed");
            }
        };
    }

    public static String getMimeType(String extension) {
        if (extension == null) {
            return null;
        }

        if (!extension.startsWith(".")) {
            extension = "." + extension.toLowerCase(Locale.getDefault());
        }

        String mime = mimeTypes.get(extension);

        return mime != null ? mime : "application/octet-stream";
    }
}

How to deal with persistent storage (e.g. databases) in Docker

My solution is to get use of the new docker cp, which is now able to copy data out from containers, not matter if it's running or not and share a host volume to the exact same location where the database application is creating its database files inside the container. This double solution works without a data-only container, straight from the original database container.

So my systemd init script is taking the job of backuping the database into an archive on the host. I placed a timestamp in the filename to never rewrite a file.

It's doing it on the ExecStartPre:

ExecStartPre=-/usr/bin/docker cp lanti-debian-mariadb:/var/lib/mysql /home/core/sql
ExecStartPre=-/bin/bash -c '/usr/bin/tar -zcvf /home/core/sql/sqlbackup_$$(date +%%Y-%%m-%%d_%%H-%%M-%%S)_ExecStartPre.tar.gz /home/core/sql/mysql --remove-files'

And it is doing the same thing on ExecStopPost too:

ExecStopPost=-/usr/bin/docker cp lanti-debian-mariadb:/var/lib/mysql /home/core/sql
ExecStopPost=-/bin/bash -c 'tar -zcvf /home/core/sql/sqlbackup_$$(date +%%Y-%%m-%%d_%%H-%%M-%%S)_ExecStopPost.tar.gz /home/core/sql/mysql --remove-files'

Plus I exposed a folder from the host as a volume to the exact same location where the database is stored:

mariadb:
  build: ./mariadb
  volumes:
    - $HOME/server/mysql/:/var/lib/mysql/:rw

It works great on my VM (I building a LEMP stack for myself): https://github.com/DJviolin/LEMP

But I just don't know if is it a "bulletproof" solution when your life depends on it actually (for example, webshop with transactions in any possible miliseconds)?

At 20 min 20 secs from this official Docker keynote video, the presenter does the same thing with the database:

Getting Started with Docker

"For the database we have a volume, so we can make sure that, as the database goes up and down, we don't loose data, when the database container stopped."

Get timezone from DateTime

DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means.

DateTimeOffset is somewhat better - that's basically a UTC time and an offset. However, that's still not really enough to determine the timezone, as many different timezones can have the same offset at any one point in time. This sounds like it may be good enough for you though, as all you've got to work with when parsing the date/time is the offset.

The support for time zones as of .NET 3.5 is a lot better than it was, but I'd really like to see a standard "ZonedDateTime" or something like that - a UTC time and an actual time zone. It's easy to build your own, but it would be nice to see it in the standard libraries.

EDIT: Nearly four years later, I'd now suggest using Noda Time which has a rather richer set of date/time types. I'm biased though, as the main author of Noda Time :)

Excel 2010 VBA Referencing Specific Cells in other worksheets

Private Sub Click_Click()

 Dim vaFiles As Variant
 Dim i As Long

For j = 1 To 2
vaFiles = Application.GetOpenFilename _
     (FileFilter:="Excel Filer (*.xlsx),*.xlsx", _
     Title:="Open File(s)", MultiSelect:=True)

If Not IsArray(vaFiles) Then Exit Sub

 With Application
  .ScreenUpdating = False
  For i = 1 To UBound(vaFiles)
     Workbooks.Open vaFiles(i)
     wrkbk_name = vaFiles(i)
    Next i
  .ScreenUpdating = True
End With

If j = 1 Then
work1 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
Else: work2 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
End If



Next j

'Filling the values of the group name

'check = Application.WorksheetFunction.Search(Name, work1)
check = InStr(UCase("Qoute Request"), work1)

If check = 1 Then
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
End If

ActiveWorkbook.Sheets("GI Quote Request").Select
ActiveSheet.Range("B4:C12").Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Range("K3").Select
ActiveSheet.Paste


Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select

Range("D3").Value = Range("L3").Value
Range("D7").Value = Range("L9").Value
Range("D11").Value = Range("L7").Value

For i = 4 To 5

If i = 5 Then
GoTo NextIteration
End If

If Left(ActiveSheet.Range("B" & i).Value, Len(ActiveSheet.Range("B" & i).Value) - 1) = Range("K" & i).Value Then
    ActiveSheet.Range("D" & i).Value = Range("L" & i).Value
 End If

NextIteration:
Next i

'eligibles part
Count = Range("D11").Value
For i = 27 To Count + 24
Range("C" & i).EntireRow.Offset(1, 0).Insert
Next i

check = Left(work1, InStrRev(work1, ".") - 1)

'check = InStr("Census", work1)
If check = "Census" Then
workbk = work1
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
workbk = work2
End If

'DOB
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("D2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
ActiveSheet.Range("C27").Select
ActiveSheet.Paste

'Gender
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("C2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False

ActiveSheet.Range("k27").Select
ActiveSheet.Paste

For i = 27 To Count + 27
ActiveSheet.Range("E" & i).Value = Left(ActiveSheet.Range("k" & i).Value, 1)
Next i

'Salary
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("N2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False

ActiveSheet.Range("F27").Select
ActiveSheet.Paste


ActiveSheet.Range("K3:L" & Count).Select
selction.ClearContents
End Sub

Python: Remove division decimal

You could probably do like below

# p and q are the numbers to be divided
if p//q==p/q:
    print(p//q)
else:
    print(p/q)

Can a table have two foreign keys?

Yes, a table have one or many foreign keys and each foreign keys hava a different parent table.

Create zip file and ignore directory structure

Somewhat related - I was looking for a solution to do the same for directories. Unfortunately the -j option does not work for this :(

Here is a good solution on how to get it done: https://superuser.com/questions/119649/avoid-unwanted-path-in-zip-file

Reading from a text file and storing in a String

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

@selector() in Swift?

you create the Selector like below.
1.

UIBarButtonItem(
    title: "Some Title",
    style: UIBarButtonItemStyle.Done,
    target: self,
    action: "flatButtonPressed"
)

2.

flatButton.addTarget(self, action: "flatButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)

Take note that the @selector syntax is gone and replaced with a simple String naming the method to call. There’s one area where we can all agree the verbosity got in the way. Of course, if we declared that there is a target method called flatButtonPressed: we better write one:

func flatButtonPressed(sender: AnyObject) {
  NSLog("flatButtonPressed")
}

set the timer:

    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
                    target: self, 
                    selector: Selector("flatButtonPressed"), 
                    userInfo: userInfo, 
                    repeats: true)
    let mainLoop = NSRunLoop.mainRunLoop()  //1
    mainLoop.addTimer(timer, forMode: NSDefaultRunLoopMode) //2 this two line is optinal

In order to be complete, here’s the flatButtonPressed

func flatButtonPressed(timer: NSTimer) {
}

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

in this scenario:

DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));

aren't you missing the column you want to compare to? example:

DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));    

I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Create a template file and use a template engine to read/update the file. It will increase your code's maintainability in the future as well as separate display from logic.

An example using Smarty:

Template File

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>{$title}</title></head>
<body>{$string}</body>
</html>

Code

function TestBlockHTML(){
  $smarty = new Smarty();
  $smarty->assign('title', 'My Title');
  $smarty->assign('string', $replStr);
  return $smarty->render('template.tpl');
}

Laravel: PDOException: could not find driver

ERROR: could not find driver (SQL: select * from tests where slug = a limit 1)

I was getting the above error in my laravel project, i am using nginx server on ubuntu 16.04

This error is because, php-mysql driver is missing. To install it type following command.

sudo apt-get install php7.2-mysql

Please specify your current php version in above command.

Open php.ini file and uncomment the followling line of code(Remove Semicolon).

;extension=pdo_mysql

Then Restart the nginx and php service

sudo systemctl restart php7.2-fpm
sudo systemctl restart nginx

It worked for me.

How to apply an XSLT Stylesheet in C#

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

http://support.microsoft.com/kb/307322/en-us/

and here how to write files:

http://support.microsoft.com/kb/816149/en-us

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

http://support.microsoft.com/kb/307379/en-us/

i added this just to provide some more information.

Remove spaces from a string in VB.NET

You can also use a small function that will loop through and remove any spaces.

This is very clean and simple.

Public Shared Function RemoveXtraSpaces(strVal As String) As String
     Dim iCount As Integer = 1
     Dim sTempstrVal As String

     sTempstrVal = ""

     For iCount = 1 To Len(strVal)
        sTempstrVal = sTempstrVal + Mid(strVal, iCount, 1).Trim
     Next

     RemoveXtraSpaces = sTempstrVal

     Return RemoveXtraSpaces

End Function

Detect if the device is iPhone X

There are several reasons to want to know what the device is.

  1. You can check the device height (and width). This is useful for layout, but you usually don't want to do that if you want to know the exact device.

  2. For layout purposes, you can also use UIView.safeAreaInsets.

  3. If you want to display the device name, for example, to be included in a email for diagnostic purposes, after retrieving the device model using sysctl (), you can use the equivalent of this to figure the name:

    $ curl http://appledevicenames.com/devices/iPhone10,6
    
    iPhone X
    

What is the difference between Python and IPython?

IPython is a powerful interactive Python interpreter that is more interactive comparing to the standard interpreter.

To get the standard Python interpreter you type python and you will get the >>> prompt from where you can work.

To get IPython interpreter, you need to install it first. pip install ipython. You type ipython and you get In [1]: as a prompt and you get In [2]: for the next command. You can call history to check the list of previous commands, and write %recall 1 to recall the command.

Even you are in Python you can run shell commands directly like !ping www.google.com. Looks like a command line Jupiter notebook if you used that before.

You can use [Tab] to autocomplete as shown in the image. enter image description here

Most useful NLog configurations

I provided a couple of reasonably interesting answers to this question:

Nlog - Generating Header Section for a log file

Adding a Header:

The question wanted to know how to add a header to the log file. Using config entries like this allow you to define the header format separately from the format of the rest of the log entries. Use a single logger, perhaps called "headerlogger" to log a single message at the start of the application and you get your header:

Define the header and file layouts:

  <variable name="HeaderLayout" value="This is the header.  Start time = ${longdate} Machine = ${machinename} Product version = ${gdc:item=version}"/>
  <variable name="FileLayout" value="${longdate} | ${logger} | ${level} | ${message}" />

Define the targets using the layouts:

<target name="fileHeader" xsi:type="File" fileName="xxx.log" layout="${HeaderLayout}" />
<target name="file" xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" />

Define the loggers:

<rules>
  <logger name="headerlogger" minlevel="Trace" writeTo="fileHeader" final="true" />
  <logger name="*" minlevel="Trace" writeTo="file" />
</rules>

Write the header, probably early in the program:

  GlobalDiagnosticsContext.Set("version", "01.00.00.25");

  LogManager.GetLogger("headerlogger").Info("It doesn't matter what this is because the header format does not include the message, although it could");

This is largely just another version of the "Treating exceptions differently" idea.

Log each log level with a different layout

Similarly, the poster wanted to know how to change the format per logging level. It wasn't clear to me what the end goal was (and whether it could be achieved in a "better" way), but I was able to provide a configuration that did what he asked:

  <variable name="TraceLayout" value="This is a TRACE - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="DebugLayout" value="This is a DEBUG - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="InfoLayout" value="This is an INFO - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="WarnLayout" value="This is a WARN - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="ErrorLayout" value="This is an ERROR - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="FatalLayout" value="This is a FATAL - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <targets> 
    <target name="fileAsTrace" xsi:type="FilteringWrapper" condition="level==LogLevel.Trace"> 
      <target xsi:type="File" fileName="xxx.log" layout="${TraceLayout}" /> 
    </target> 
    <target name="fileAsDebug" xsi:type="FilteringWrapper" condition="level==LogLevel.Debug"> 
      <target xsi:type="File" fileName="xxx.log" layout="${DebugLayout}" /> 
    </target> 
    <target name="fileAsInfo" xsi:type="FilteringWrapper" condition="level==LogLevel.Info"> 
      <target xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" /> 
    </target> 
    <target name="fileAsWarn" xsi:type="FilteringWrapper" condition="level==LogLevel.Warn"> 
      <target xsi:type="File" fileName="xxx.log" layout="${WarnLayout}" /> 
    </target> 
    <target name="fileAsError" xsi:type="FilteringWrapper" condition="level==LogLevel.Error"> 
      <target xsi:type="File" fileName="xxx.log" layout="${ErrorLayout}" /> 
    </target> 
    <target name="fileAsFatal" xsi:type="FilteringWrapper" condition="level==LogLevel.Fatal"> 
      <target xsi:type="File" fileName="xxx.log" layout="${FatalLayout}" /> 
    </target> 
  </targets> 


    <rules> 
      <logger name="*" minlevel="Trace" writeTo="fileAsTrace,fileAsDebug,fileAsInfo,fileAsWarn,fileAsError,fileAsFatal" /> 
      <logger name="*" minlevel="Info" writeTo="dbg" /> 
    </rules> 

Again, very similar to Treating exceptions differently.

Elastic Search: how to see the indexed data

If you are using Google Chrome then you can simply use this extension named as Sense it is also a tool if you use Marvel.

https://chrome.google.com/webstore/detail/sense-beta/lhjgkmllcaadmopgmanpapmpjgmfcfig

Stopping python using ctrl+c

The interrupt process is hardware and OS dependent. So you will have very different behavior depending on where you run your python script. For example, on Windows machines we have Ctrl+C (SIGINT) and Ctrl+Break (SIGBREAK).

So while SIGINT is present on all systems and can be handled and caught, the SIGBREAK signal is Windows specific (and can be disabled in CONFIG.SYS) and is really handled by the BIOS as an interrupt vector INT 1Bh, which is why this key is much more powerful than any other. So if you're using some *nix flavored OS, you will get different results depending on the implementation, since that signal is not present there, but others are. In Linux you can check what signals are available to you by:

$ kill -l
 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
 6) SIGABRT      7) SIGEMT       8) SIGFPE       9) SIGKILL     10) SIGBUS
11) SIGSEGV     12) SIGSYS      13) SIGPIPE     14) SIGALRM     15) SIGTERM
16) SIGURG      17) SIGSTOP     18) SIGTSTP     19) SIGCONT     20) SIGCHLD
21) SIGTTIN     22) SIGTTOU     23) SIGIO       24) SIGXCPU     25) SIGXFSZ
26) SIGVTALRM   27) SIGPROF     28) SIGWINCH    29) SIGPWR      30) SIGUSR1
31) SIGUSR2     32) SIGRTMAX

So if you want to catch the CTRL+BREAK signal on a linux system you'll have to check to what POSIX signal they have mapped that key. Popular mappings are:

CTRL+\     = SIGQUIT 
CTRL+D     = SIGQUIT
CTRL+C     = SIGINT
CTRL+Z     = SIGTSTOP 
CTRL+BREAK = SIGKILL or SIGTERM or SIGSTOP

In fact, many more functions are available under Linux, where the SysRq (System Request) key can take on a life of its own...

Can Mysql Split a column?

Use

substring_index(`column`,',',1) ==> first value
substring_index(substring_index(`column`,',',-2),',',1)=> second value
substring_index(substring_index(`column`,',',-1),',',1)=> third value

in your where clause.

SELECT * FROM `table`
WHERE 
substring_index(`column`,',',1)<0 
AND
substring_index(`column`,',',1)>5

"Can't find Project or Library" for standard VBA functions

Even when all references are fine the prefix problem causes compile errors.

What about creating a find and replace sub for all 'built-in VBA functions' in all modules, like this:

replace text in code module

e.g. "= Date" will be replaced with "= VBA.Date".

e.g. " Date(" will be replaced with " VBA.Date(" .

(excluding "dim t As Date" or "mydate")

All vba functions for find and replace are written here :

vba functions list

PivotTable's Report Filter using "greater than"

In an Excel pivot table, you are correct that a filter only allows values that are explicitly selected. If the filter field is placed on the pivot table rows or columns, however, you get a much wider set of Label Filter conditions, including Greater Than. If you did that in your case, then the added benefit would be that the various probability levels that match your condition are shown in the body of the table.

RegEx match open tags except XHTML self-contained tags

I like to parse HTML with regular expressions. I don't attempt to parse idiot HTML that is deliberately broken. This code is my main parser (Perl edition):

$_ = join "",<STDIN>; tr/\n\r \t/ /s; s/</\n</g; s/>/>\n/g; s/\n ?\n/\n/g;
s/^ ?\n//s; s/ $//s; print

It's called htmlsplit, splits the HTML into lines, with one tag or chunk of text on each line. The lines can then be processed further with other text tools and scripts, such as grep, sed, Perl, etc. I'm not even joking :) Enjoy.

It is simple enough to rejig my slurp-everything-first Perl script into a nice streaming thing, if you wish to process enormous web pages. But it's not really necessary.

HTML Split


Some better regular expressions:

/(<.*?>|[^<]+)\s*/g    # Get tags and text
/(\w+)="(.*?)"/g       # Get attibutes

They are good for XML / XHTML.

With minor variations, it can cope with messy HTML... or convert the HTML -> XHTML first.


The best way to write regular expressions is in the Lex / Yacc style, not as opaque one-liners or commented multi-line monstrosities. I didn't do that here, yet; these ones barely need it.

ORA-01882: timezone region not found

In my case I could get the query working by changing "TZR" with "TZD"..

String query = "select * from table1 to_timestamp_tz(origintime,'dd-mm-yyyy hh24:mi:ss TZD') between ?  and ?";

How to quietly remove a directory with content in PowerShell

rm -Force -Recurse -Confirm:$false $directory2Delete didn't work in the PowerShell ISE, but it worked through the regular PowerShell CLI.

I hope this helps. It was driving me bannanas.

How to get client's IP address using JavaScript?

Try this: http://httpbin.org/ip (or https://httpbin.org/ip)

Example with https:

$.getJSON('https://httpbin.org/ip', function(data) {
                console.log(data['origin']);
});

Source: http://httpbin.org/

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

I might be little late for answer and probably world knows about this now.

All you have to open your ports of docker container to access it. For example while running the container :

docker run --name mysql_container -e MYSQL_ROOT_PASSWORD=root -d -p 3306:3306 mysql/mysql-server:5.7

This will allow your container's mysql to be accessible from the host machine. Later you can connect to it.

docker exec -it mysql_container mysql -u root -p

How to delete/remove nodes on Firebase

I hope this code will help someone - it is from official Google Firebase documentation:

var adaRef = firebase.database().ref('users/ada');
adaRef.remove()
  .then(function() {
    console.log("Remove succeeded.")
  })
  .catch(function(error) {
    console.log("Remove failed: " + error.message)
  });

How to get ID of button user just clicked?

With pure javascript:

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
        alert(this.id);
    };
}?

http://jsfiddle.net/TKKBV/2/

How to detect orientation change in layout in Android?

use this method

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
    {
        Toast.makeText(getActivity(),"PORTRAIT",Toast.LENGTH_LONG).show();
       //add your code what you want to do when screen on PORTRAIT MODE
    }
    else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
    {
        Toast.makeText(getActivity(),"LANDSCAPE",Toast.LENGTH_LONG).show();
        //add your code what you want to do when screen on LANDSCAPE MODE
   }
}

And Do not forget to Add this in your Androidmainfest.xml

android:configChanges="orientation|screenSize"

like this

<activity android:name=".MainActivity"
          android:theme="@style/Theme.AppCompat.NoActionBar"
          android:configChanges="orientation|screenSize">

    </activity>

openssl s_client using a proxy

since openssl v1.1.0

C:\openssl>openssl version
OpenSSL 1.1.0g  2 Nov 2017
C:\openssl>openssl s_client -proxy 192.168.103.115:3128 -connect www.google.com -CAfile C:\TEMP\internalCA.crt
CONNECTED(00000088)
depth=2 DC = com, DC = xxxx, CN = xxxx CA interne
verify return:1
depth=1 C = FR, L = CROIX, CN = svproxysg1, emailAddress = [email protected]
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google Inc, CN = www.google.com
verify return:1
---
Certificate chain
 0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com
   i:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
 1 s:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
   i:/DC=com/DC=xxxxx/CN=xxxxx CA interne
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIDkTCCAnmgAwIBAgIJAIv4/hQAAAAAMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV
BAYTAkZSMQ4wDAYDVQQHEwVDUk9JWDETMBEGA1UEAxMKc3Zwcm94eXNnMTEeMBwG

Can someone give an example of cosine similarity, in a very simple, graphical way?

I'm guessing you are more interested in getting some insight into "why" the cosine similarity works (why it provides a good indication of similarity), rather than "how" it is calculated (the specific operations used for the calculation). If your interest is in the latter, see the reference indicated by Daniel in this post, as well as a related SO Question.

To explain both the how and even more so the why, it is useful, at first, to simplify the problem and to work only in two dimensions. Once you get this in 2D, it is easier to think of it in three dimensions, and of course harder to imagine in many more dimensions, but by then we can use linear algebra to do the numeric calculations and also to help us think in terms of lines / vectors / "planes" / "spheres" in n dimensions, even though we can't draw these.

So, in two dimensions: with regards to text similarity this means that we would focus on two distinct terms, say the words "London" and "Paris", and we'd count how many times each of these words is found in each of the two documents we wish to compare. This gives us, for each document, a point in the the x-y plane. For example, if Doc1 had Paris once, and London four times, a point at (1,4) would present this document (with regards to this diminutive evaluation of documents). Or, speaking in terms of vectors, this Doc1 document would be an arrow going from the origin to point (1,4). With this image in mind, let's think about what it means for two documents to be similar and how this relates to the vectors.

VERY similar documents (again with regards to this limited set of dimensions) would have the very same number of references to Paris, AND the very same number of references to London, or maybe, they could have the same ratio of these references. A Document, Doc2, with 2 refs to Paris and 8 refs to London, would also be very similar, only with maybe a longer text or somehow more repetitive of the cities' names, but in the same proportion. Maybe both documents are guides about London, only making passing references to Paris (and how uncool that city is ;-) Just kidding!!!.

Now, less similar documents may also include references to both cities, but in different proportions. Maybe Doc2 would only cite Paris once and London seven times.

Back to our x-y plane, if we draw these hypothetical documents, we see that when they are VERY similar, their vectors overlap (though some vectors may be longer), and as they start to have less in common, these vectors start to diverge, to have a wider angle between them.

By measuring the angle between the vectors, we can get a good idea of their similarity, and to make things even easier, by taking the Cosine of this angle, we have a nice 0 to 1 or -1 to 1 value that is indicative of this similarity, depending on what and how we account for. The smaller the angle, the bigger (closer to 1) the cosine value, and also the higher the similarity.

At the extreme, if Doc1 only cites Paris and Doc2 only cites London, the documents have absolutely nothing in common. Doc1 would have its vector on the x-axis, Doc2 on the y-axis, the angle 90 degrees, Cosine 0. In this case we'd say that these documents are orthogonal to one another.

Adding dimensions:
With this intuitive feel for similarity expressed as a small angle (or large cosine), we can now imagine things in 3 dimensions, say by bringing the word "Amsterdam" into the mix, and visualize quite well how a document with two references to each would have a vector going in a particular direction, and we can see how this direction would compare to a document citing Paris and London three times each, but not Amsterdam, etc. As said, we can try and imagine the this fancy space for 10 or 100 cities. It's hard to draw, but easy to conceptualize.

I'll wrap up just by saying a few words about the formula itself. As I've said, other references provide good information about the calculations.

First in two dimensions. The formula for the Cosine of the angle between two vectors is derived from the trigonometric difference (between angle a and angle b):

cos(a - b) = (cos(a) * cos(b)) + (sin (a) * sin(b))

This formula looks very similar to the dot product formula:

Vect1 . Vect2 =  (x1 * x2) + (y1 * y2)

where cos(a) corresponds to the x value and sin(a) the y value, for the first vector, etc. The only problem, is that x, y, etc. are not exactly the cos and sin values, for these values need to be read on the unit circle. That's where the denominator of the formula kicks in: by dividing by the product of the length of these vectors, the x and y coordinates become normalized.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Regex Match all characters between two strings

for a quick search in VIM, you could use at Vim Control prompt: /This is.*\_.*sentence

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Use of main thread to present and dismiss view controller worked for me.

DispatchQueue.main.async { self.present(viewController, animated: true, completion: nil) }

How to add Android Support Repository to Android Studio?

I used to get similar issues. Even after installing the support repository, the build used to fail.

Basically the issues is due to the way the version number of the jar files are specified in the gradle files are specified properly.

For example, in my case i had set it as "compile 'com.android.support:support-v4:21.0.3+'"

On removing "+" the build was sucessful!!

Finding last occurrence of substring in string, replacing that

This should do it

old_string = "this is going to have a full stop. some written sstuff!"
k = old_string.rfind(".")
new_string = old_string[:k] + ". - " + old_string[k+1:]

How do I run a PowerShell script when the computer starts?

Try this. Create a shortcut in startup folder and iuput

PowerShell "&.'PathToFile\script.ps1'"

This is the easiest way.

SQL Server: use CASE with LIKE

SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname, 
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE 
Lname END AS LnameTrue FROM dbo.____Fname_Lname

Bootstrap 3: How do you align column content to bottom of row

Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)

.profile-header > div {
  display: inline-block;
  vertical-align: bottom;
  float: none;
  margin: -2px;
}
.profile-header {
  margin-bottom:20px;
  border:2px solid green;
  display: table-cell;
}
.profile-pic {
  height:300px;
  border:2px solid red;
}
.profile-about {
  border:2px solid blue;
}
.profile-about2 {
  border:2px solid pink;
}

Example here: http://www.bootply.com/125740#

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

We can try by using latest jQuery library. I got the same issue. I used jQuery-1.4.2.min before and getting the error. After that I used version 1.9.1 and it works. Thanks

How can I delete derived data in Xcode 8?

The simplest and fastest way is the following (if you have not changed the defaults folder for DerivedData).

Open terminal and past the following:

rm -rf ~/Library/Developer/Xcode/DerivedData

New Intent() starts new instance with Android: launchMode="singleTop"

This should do the trick.

<activity ... android:launchMode="singleTop" />

When you create an intent to start the app use:

Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

This is that should be needed.

Get cart item name, quantity all details woocommerce

Most of the time you want to get the IDs of the products in the cart so that you can make some comparison with some other logic - example settings in the backend.

In such a case you can extend the answer from @Rohil_PHPBeginner and return the IDs in an array as follows :

<?php 

    function njengah_get_ids_of_products_in_cart(){
    
            global $woocommerce;
    
            $productsInCart = array(); 
            
            $items = $woocommerce->cart->get_cart(); 
            
            foreach($items as $item => $values) { 
            
                $_product =  wc_get_product( $values['data']->get_id()); 
                
               /* Display Cart Items Content  */ 
               
                echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
                $price = get_post_meta($values['product_id'] , '_price', true);
                echo "  Price: ".$price."<br>";
                
                /**Get IDs and in put them in an  Array**/ 
                
                $productsInCart_Ids[] =  $_product->get_id();
            }
           
           /** To Display **/ 
              
           print_r($productsInCart_Ids);
           
           /**To Return for Comparision with some Other Logic**/ 
           
           return $productsInCart_Ids; 
    
        }

How to generate and manually insert a uniqueidentifier in sql server?

ApplicationId must be of type UniqueIdentifier. Your code works fine if you do:

DECLARE @TTEST TABLE
(
  TEST UNIQUEIDENTIFIER
)

DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();

INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);

SELECT * FROM @TTEST

Therefore I would say it is safe to assume that ApplicationId is not the correct data type.

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I had to face this problem too and had a work around which i checked on HTC one, galaxy s1, s2, s3, note and HTC sensation.

put a global layout listener on the root view of your layout

mRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
            public void onGlobalLayout() {
                checkHeightDifference();
            }
    });

and in there i checked the height difference and if the height difference of the screen is bigger then a third on the screen height then we can assume the keyboard is open. took it from this answer.

private void checkHeightDifference(){
    // get screen frame rectangle 
    Rect r = new Rect();
    mRootView.getWindowVisibleDisplayFrame(r);
    // get screen height
    int screenHeight = mRootView.getRootView().getHeight();
    // calculate the height difference
    int heightDifference = screenHeight - (r.bottom - r.top);

    // if height difference is different then the last height difference and
    // is bigger then a third of the screen we can assume the keyboard is open
    if (heightDifference > screenHeight/3 && heightDifference != mLastHeightDifferece) {
        // keyboard visiblevisible
        // get root view layout params
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mRootView.getLayoutParams();
        // set the root view height to screen height minus the height difference
        lp.height = screenHeight - heightDifference;
        // call request layout so the changes will take affect
        .requestLayout();
        // save the height difference so we will run this code only when a change occurs.
        mLastHeightDifferece = heightDifference;
    } else if (heightDifference != mLastHeightDifferece) {
        // keyboard hidden
        PFLog.d("[ChatroomActivity] checkHeightDifference keyboard hidden");
        // get root view layout params and reset all the changes we have made when the keyboard opened.
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mRootView.getLayoutParams();
        lp.height = screenHeight;
        // call request layout so the changes will take affect
        mRootView.requestLayout();
        // save the height difference so we will run this code only when a change occurs.
        mLastHeightDifferece = heightDifference;
    }
}

this is probably not bullet proof and maybe on some devices it will not work but it worked for me and hope it will help you too.

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

I have a similar situation and here's how i solved it:
All my scrollable elements get the class scrollable.

$(document).on('wheel', '.scrollable', function(evt) {
  var offsetTop = this.scrollTop + parseInt(evt.originalEvent.deltaY, 10);
  var offsetBottom = this.scrollHeight - this.getBoundingClientRect().height - offsetTop;

  if (offsetTop < 0 || offsetBottom < 0) {
    evt.preventDefault();
  } else {
    evt.stopImmediatePropagation();
  }
});

stopImmediatePropagation() makes sure not to scroll parent scrollable area from scrollable child area.

Here's a vanilla JS implementation of it: http://jsbin.com/lugim/2/edit?js,output

How to save Excel Workbook to Desktop regardless of user?

You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.

Public Sub SaveToDesktop()
    ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _ 
    FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub

I'm not sure whether this would be a requirement, but may help!

Select DataFrame rows between two dates

With my testing of pandas version 0.22.0 you can now answer this question easier with more readable code by simply using between.

# create a single column DataFrame with dates going from Jan 1st 2018 to Jan 1st 2019
df = pd.DataFrame({'dates':pd.date_range('2018-01-01','2019-01-01')})

Let's say you want to grab the dates between Nov 27th 2018 and Jan 15th 2019:

# use the between statement to get a boolean mask
df['dates'].between('2018-11-27','2019-01-15', inclusive=False)

0    False
1    False
2    False
3    False
4    False

# you can pass this boolean mask straight to loc
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=False)]

    dates
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
335 2018-12-02

Notice the inclusive argument. very helpful when you want to be explicit about your range. notice when set to True we return Nov 27th of 2018 as well:

df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]

    dates
330 2018-11-27
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01

This method is also faster than the previously mentioned isin method:

%%timeit -n 5
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
868 µs ± 164 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)


%%timeit -n 5

df.loc[df['dates'].isin(pd.date_range('2018-01-01','2019-01-01'))]
1.53 ms ± 305 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

However, it is not faster than the currently accepted answer, provided by unutbu, only if the mask is already created. but if the mask is dynamic and needs to be reassigned over and over, my method may be more efficient:

# already create the mask THEN time the function

start_date = dt.datetime(2018,11,27)
end_date = dt.datetime(2019,1,15)
mask = (df['dates'] > start_date) & (df['dates'] <= end_date)

%%timeit -n 5
df.loc[mask]
191 µs ± 28.5 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

Change image onmouseover

jQuery has .mouseover() and .html(). You can tie the mouseover event to a function:

  1. Hides the current image.
  2. Replaces the current html image with the one you want to toggle.
  3. Shows the div that you hid.

The same thing can be done when you get the mouseover event indicating that the cursor is no longer hanging over the div.

What Ruby IDE do you prefer?

RubyMine is so awesome. Everything just works. I could go on and on. Code completion is fast, smooth, and accurate. Formatting is instantaneous. Project navigation is easy and without struggle. You can pop open any file with a few keystrokes. You don't even need to keep the project tree open, but it's there if you want. You can configure just about any aspect of it to behave exactly how you want.

NetBeans, Eclipse, and RubyMine all have more or less the same set of features. However, RubyMine is just so much more cleanly designed and easy to use. There's nothing awkward or clunky about it. There are all these nice little design touches that show how JetBrains really put thought into it instead of just amassing a big pile of features.

Incidentally RubyMine can do a lot of the things that Vim can do like select and edit a column of text or split the view into several editing panels with different files in them.

Best Practices for Custom Helpers in Laravel 5

in dir bootstrap\autoload.php

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add

add this file

app\Helpers\function.php

using stored procedure in entity framework

Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good?

How to develop Android app completely using python?

To answer your first question: yes it is feasible to develop an android application in pure python, in order to achieve this I suggest you use BeeWare, which is just a suite of python tools, that work together very well and they enable you to develop platform native applications in python.

checkout this video by the creator of BeeWare that perfectly explains and demonstrates it's application

How it works

Android's preferred language of implementation is Java - so if you want to write an Android application in Python, you need to have a way to run your Python code on a Java Virtual Machine. This is what VOC does. VOC is a transpiler - it takes Python source code, compiles it to CPython Bytecode, and then transpiles that bytecode into Java-compatible bytecode. The end result is that your Python source code files are compiled directly to a Java .class file, which can be packaged into an Android application.

VOC also allows you to access native Java objects as if they were Python objects, implement Java interfaces with Python classes, and subclass Java classes with Python classes. Using this, you can write an Android application directly against the native Android APIs.

Once you've written your native Android application, you can use Briefcase to package your Python code as an Android application.

Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:

  • Mac
  • Windows
  • Linux
  • iPhone/iPad
  • Android
  • AppleTV
  • tvOS.

You can check This native Android Tic Tac Toe app written in Python, using the BeeWare suite. on GitHub

in addition to the BeeWare tools, you'll need to have a JDK and Android SDK installed to test run your application.

and to answer your second question: a good environment can be anything you are comfortable with be it a text editor and a command line, or an IDE, if you're looking for a good python IDE I would suggest you try Pycharm, it has a community edition which is free, and it has a similar environment as android studio, due to to the fact that were made by the same company.

I hope this has been helpful

How to find if an array contains a specific string in JavaScript/jQuery?

You really don't need jQuery for this.

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs

or

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

It's worth noting that array.indexOf(..) is not supported in IE < 9, but jQuery's indexOf(...) function will work even for those older versions.

Factorial in numpy and scipy

SciPy has the function scipy.special.factorial (formerly scipy.misc.factorial)

>>> import math
>>> import scipy.special
>>> math.factorial(6)
720
>>> scipy.special.factorial(6)
array(720.0)

What does "control reaches end of non-void function" mean?

I had the same problem. My code below didn't work, but when I replaced the last "if" with "else", it works. The error was: may reach end of non-void function.

int shifted(char key_letter)
  {
        if(isupper(key_letter))
        {
            return key_letter - 'A'; 
        }

        if(islower(key_letter)   //<----------- doesn't work, replace with else

        {                                            


            return key_letter - 'a'; 
        }

  }

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

I needed to use this as a cell function (like SUM or VLOOKUP) and found that it was easy to:

  1. Make sure you are in a Macro Enabled Excel File (save as xlsm).
  2. Open developer tools Alt + F11
  3. Add Microsoft VBScript Regular Expressions 5.5 as in other answers
  4. Create the following function either in workbook or in its own module:

    Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
        Dim regex As New VBScript_RegExp_55.RegExp
        Dim strInput As String
    
        strInput = myRange.Value
    
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
    
        REGPLACE = regex.Replace(strInput, outputPattern)
    
    End Function
    
  5. Then you can use in cell with =REGPLACE(B1, "(\w) (\d+)", "$1$2") (ex: "A 243" to "A243")

How to check if pytorch is using the GPU?

If you are here because your pytorch always gives False for torch.cuda.is_available() that's probably because you installed your pytorch version without GPU support. (Eg: you coded up in laptop then testing on server).

The solution is to uninstall and install pytorch again with the right command from pytorch downloads page. Also refer this pytorch issue.

How do I use Maven through a proxy?

The above postings helped in resolving my problem. In addition to the above I had to make the following changes to make it work :

  • Modified Maven's JRE net settings(\jre\lib\net.properties) to use system proxy setting.

    https.proxyHost=proxy DNS
    https.proxyPort=proxy port
    
  • Included proxy server settings in settings.xml. I did not provide username and password settings as to use NTLM authentication.

Ansible - Save registered variable to file

A local action will run once for each remote host (in parallel). If you want a unique file per host, make sure to put the inventory_hostname as part of the file name.

- local_action: copy content={{ foo_result }} dest=/path/to/destination/{{ inventory_hostname }}file

If you instead want a single file with all host's information, one way is to have a serial task (don't want to append in parallel) and then append to the file with a module (lineinfile is capable, or could pipe with a shell command)

- hosts: web_servers
  serial: 1
  tasks:
  - local_action: lineinfile line={{ foo_result }} path=/path/to/destination/file

Alternatively, you can add a second play/role/task to the playbook which runs against only local host. Then access the variable from each of the hosts where the registration command ran inside a template Access Other Hosts Variables Docs Template Module Docs

Escaping single quote in PHP when inserting into MySQL

You should be escaping each of these strings (in both snippets) with mysql_real_escape_string().

http://us3.php.net/mysql-real-escape-string

The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien").

Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien". So, you will need to pass it through mysql_real_escape_string().

Bootstrap carousel multiple frames at once

Updated 2019...

Bootstrap 4

The carousel has changed in 4.x, and the multi-slide animation transitions can be overridden like this...

.carousel-inner .carousel-item-right.active,
.carousel-inner .carousel-item-next {
  transform: translateX(33.33%);
}

.carousel-inner .carousel-item-left.active, 
.carousel-inner .carousel-item-prev {
  transform: translateX(-33.33%)
}

.carousel-inner .carousel-item-right,
.carousel-inner .carousel-item-left{ 
  transform: translateX(0);
}

Bootstrap 4 Alpha.6 Demo
Bootstrap 4.0.0 (show 4, advance 1 at a time)
Bootstrap 4.1.0 (show 3, advance 1 at a time)
Bootstrap 4.1.0 (advance all 4 at once)
Bootstrap 4.3.1 responsive (show multiple, advance 1)new
Bootstrap 4.3.1 carousel with cardsnew


Another option is a responsive carousel that only shows and advances 1 slide on smaller screens, but shows multiple slides are larger screens. Instead of cloning the slides like the previous example, this one adjusts the CSS and use jQuery only to move the extra slides to allow for continuous cycling (wrap around):

Please don't just copy-and-paste this code. First, understand how it works.

Bootstrap 4 Responsive (show 3, 1 slide on mobile)

@media (min-width: 768px) {

    /* show 3 items */
    .carousel-inner .active,
    .carousel-inner .active + .carousel-item,
    .carousel-inner .active + .carousel-item + .carousel-item {
        display: block;
    }

    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left),
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item,
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item + .carousel-item {
        transition: none;
    }

    .carousel-inner .carousel-item-next,
    .carousel-inner .carousel-item-prev {
      position: relative;
      transform: translate3d(0, 0, 0);
    }

    .carousel-inner .active.carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: absolute;
        top: 0;
        right: -33.3333%;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* left or forward direction */
    .active.carousel-item-left + .carousel-item-next.carousel-item-left,
    .carousel-item-next.carousel-item-left + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(-100%, 0, 0);
        visibility: visible;
    }

    /* farthest right hidden item must be abso position for animations */
    .carousel-inner .carousel-item-prev.carousel-item-right {
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* right or prev direction */
    .active.carousel-item-right + .carousel-item-prev.carousel-item-right,
    .carousel-item-prev.carousel-item-right + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(100%, 0, 0);
        visibility: visible;
        display: block;
        visibility: visible;
    }

}

<div class="container-fluid">
    <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="9000">
        <div class="carousel-inner row w-100 mx-auto" role="listbox">
            <div class="carousel-item col-md-4 active">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400/000/fff?text=1" alt="slide 1">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=2" alt="slide 2">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=3" alt="slide 3">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=4" alt="slide 4">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=5" alt="slide 5">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=6" alt="slide 6">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=7" alt="slide 7">
            </div>
            <div class="carousel-item col-md-4">
                <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=8" alt="slide 7">
            </div>
        </div>
        <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev">
            <i class="fa fa-chevron-left fa-lg text-muted"></i>
            <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next text-faded" href="#carouselExample" role="button" data-slide="next">
            <i class="fa fa-chevron-right fa-lg text-muted"></i>
            <span class="sr-only">Next</span>
        </a>
    </div>
</div>

Example - Bootstrap 4 Responsive (show 4, 1 slide on mobile)
Example - Bootstrap 4 Responsive (show 5, 1 slide on mobile)


Bootstrap 3

Here is a 3.x example on Bootply: http://bootply.com/89193

You need to put an entire row of images in the item active. Here is another version that doesn't stack the images at smaller screen widths: http://bootply.com/92514

EDIT Alternative approach to advance one slide at a time:

Use jQuery to clone the next items..

$('.carousel .item').each(function(){
  var next = $(this).next();
  if (!next.length) {
    next = $(this).siblings(':first');
  }
  next.children(':first-child').clone().appendTo($(this));

  if (next.next().length>0) {
    next.next().children(':first-child').clone().appendTo($(this));
  }
  else {
    $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
  }
});

And then CSS to position accordingly...

Before 3.3.1

.carousel-inner .active.left { left: -33%; }
.carousel-inner .next        { left:  33%; }

After 3.3.1

.carousel-inner .item.left.active {
  transform: translateX(-33%);
}
.carousel-inner .item.right.active {
  transform: translateX(33%);
}

.carousel-inner .item.next {
  transform: translateX(33%)
}
.carousel-inner .item.prev {
  transform: translateX(-33%)
}

.carousel-inner .item.right,
.carousel-inner .item.left { 
  transform: translateX(0);
}

This will show 3 at time, but only slide one at a time:

Bootstrap 3.x Demo


Please don't copy-and-paste this code. First, understand how it works. This answer is here to help you learn.

Doubling up this modified bootstrap 4 carousel only functions half correctly (scroll loop stops working)
how to make 2 bootstrap sliders in single page without mixing their css and jquery?
Bootstrap 4 Multi Carousel show 4 images instead of 3

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

How to get the android Path string to a file on Assets folder?

You can use this method.

    public static File getRobotCacheFile(Context context) throws IOException {
        File cacheFile = new File(context.getCacheDir(), "robot.png");
        try {
            InputStream inputStream = context.getAssets().open("robot.png");
            try {
                FileOutputStream outputStream = new FileOutputStream(cacheFile);
                try {
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, len);
                    }
                } finally {
                    outputStream.close();
                }
            } finally {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new IOException("Could not open robot png", e);
        }
        return cacheFile;
    }

You should never use InputStream.available() in such cases. It returns only bytes that are buffered. Method with .available() will never work with bigger files and will not work on some devices at all.

In Kotlin (;D):

@Throws(IOException::class)
fun getRobotCacheFile(context: Context): File = File(context.cacheDir, "robot.png")
    .also {
        it.outputStream().use { cache -> context.assets.open("robot.png").use { it.copyTo(cache) } }
    }

Save image from url with curl PHP

Improved version of Komang answer (add referer and user agent, check if you can write the file), return true if it's ok, false if there is an error :

public function downloadImage($url,$filename){
    if(file_exists($filename)){
        @unlink($filename);
    }
    $fp = fopen($filename,'w');
    if($fp){
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $result = parse_url($url);
        curl_setopt($ch, CURLOPT_REFERER, $result['scheme'].'://'.$result['host']);
        curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0');
        $raw=curl_exec($ch);
        curl_close ($ch);
        if($raw){
            fwrite($fp, $raw);
        }
        fclose($fp);
        if(!$raw){
            @unlink($filename);
            return false;
        }
        return true;
    }
    return false;
}

What is the use of adding a null key or value to a HashMap in Java?

The answers so far only consider the worth of have a null key, but the question also asks about any number of null values.

The benefit of storing the value null against a key in a HashMap is the same as in databases, etc - you can record a distinction between having a value that is empty (e.g. string ""), and not having a value at all (null).

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

Disable PHP in directory (including all sub-directories) with .htaccess

None of those answers are working for me (either generating a 500 error or doing nothing). That is probably due to the fact that I'm working on a hosted server where I can't have access to Apache configuration.

But this worked for me :

RewriteRule ^.*\.php$ - [F,L]

This line will generate a 403 Forbidden error for any URL that ends with .php and ends up in this subdirectory.

@Oussama lead me to the right direction here, thanks to him.

json_decode returns NULL after webservice call

You should try out json_last_error_msg(). It will give you the error message and tell you what is wrong. It was introduced in PHP 5.5.

$foo = "{"action":"set","user":"123123123123","status":"OK"}";
$data = json_decode($foo, true);
if($data == null) {
    throw new Exception('Decoding JSON failed with the following message: '
                             . json_last_error_msg());
}

// ... JSON decode was good => Let's use the data

Exception.Message vs Exception.ToString()

Exception.Message contains only the message (doh) associated with the exception. Example:

Object reference not set to an instance of an object

The Exception.ToString() method will give a much more verbose output, containing the exception type, the message (from before), a stack trace, and all of these things again for nested/inner exceptions. More precisely, the method returns the following:

ToString returns a representation of the current exception that is intended to be understood by humans. Where the exception contains culture-sensitive data, the string representation returned by ToString is required to take into account the current system culture. Although there are no exact requirements for the format of the returned string, it should attempt to reflect the value of the object as perceived by the user.

The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is a null reference (Nothing in Visual Basic), its value is not included in the returned string.

If there is no error message or if it is an empty string (""), then no error message is returned. The name of the inner exception and the stack trace are returned only if they are not a null reference (Nothing in Visual Basic).

convert json ipython notebook(.ipynb) to .py file

According to https://ipython.org/ipython-doc/3/notebook/nbconvert.html you are looking for the nbconvert command with the --to script option.

ipython nbconvert notebook.ipynb --to script

plot with custom text for x axis points

You can manually set xticks (and yticks) using pyplot.xticks:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()

Extract Month and Year From Date in R

This will add a new column to your data.frame with the specified format.

df$Month_Yr <- format(as.Date(df$Date), "%Y-%m")

df
#>   ID       Date Month_Yr
#> 1  1 2004-02-06  2004-02
#> 2  2 2006-03-14  2006-03
#> 3  3 2007-07-16  2007-07

# your data sample
  df <- data.frame( ID=1:3,Date = c("2004-02-06" , "2006-03-14" , "2007-07-16") )

a simple example:

dates <- "2004-02-06"

format(as.Date(dates), "%Y-%m")
> "2004-02"

side note: the data.table approach can be quite faster in case you're working with a big dataset.

library(data.table)
setDT(df)[, Month_Yr := format(as.Date(Date), "%Y-%m") ]

View stored procedure/function definition in MySQL

You can use table proc in database mysql:

mysql> SELECT body FROM mysql.proc
WHERE db = 'yourdb' AND name = 'procedurename' ;

Note that you must have a grant for select to mysql.proc:

mysql> GRANT SELECT ON mysql.proc TO 'youruser'@'yourhost' IDENTIFIED BY 'yourpass' ;

python: how to identify if a variable is an array or a scalar

You can check data type of variable.

N = [2,3,5]
P = 5
type(P)

It will give you out put as data type of P.

<type 'int'>

So that you can differentiate that it is an integer or an array.

Calculate percentage Javascript

It seems working :

HTML :

 <input type='text' id="pointspossible"/>
<input type='text' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>

JavaScript :

    $(function(){

    $('#pointspossible').on('input', function() {
      calculate();
    });
    $('#pointsgiven').on('input', function() {
     calculate();
    });
    function calculate(){
        var pPos = parseInt($('#pointspossible').val()); 
        var pEarned = parseInt($('#pointsgiven').val());
        var perc="";
        if(isNaN(pPos) || isNaN(pEarned)){
            perc=" ";
           }else{
           perc = ((pEarned/pPos) * 100).toFixed(3);
           }

        $('#pointsperc').val(perc);
    }

});

Demo : http://jsfiddle.net/vikashvverma/1khs8sj7/1/

In Visual Basic how do you create a block comment

There's not a way as of 11/2012, HOWEVER

Highlight Text (In visual Studio.net)

ctrl + k + c, ctrl + k + u

Will comment / uncomment, respectively

Interview question: Check if one string is a rotation of other string

Opera's simple pointer rotation trick works, but it is extremely inefficient in the worst case in running time. Simply imagine a string with many long repetitive runs of characters, ie:

S1 = HELLOHELLOHELLO1HELLOHELLOHELLO2

S2 = HELLOHELLOHELLO2HELLOHELLOHELLO1

The "loop until there's a mismatch, then increment by one and try again" is a horrible approach, computationally.

To prove that you can do the concatenation approach in plain C without too much effort, here is my solution:

  int isRotation(const char* s1, const char* s2) {
        assert(s1 && s2);

        size_t s1Len = strlen(s1);

        if (s1Len != strlen(s2)) return 0;

        char s1SelfConcat[ 2 * s1Len + 1 ];

        sprintf(s1SelfConcat, "%s%s", s1, s1);   

        return (strstr(s1SelfConcat, s2) ? 1 : 0);
}

This is linear in running time, at the expense of O(n) memory usage in overhead.

(Note that the implementation of strstr() is platform-specific, but if particularly brain-dead, can always be replaced with a faster alternative such as the Boyer-Moore algorithm)

T-SQL split string

This is based on Andy Robertson's answer, I needed a delimiter other than comma.

CREATE FUNCTION dbo.splitstring ( @stringToSplit nvarchar(MAX), @delim nvarchar(max))
RETURNS
 @returnList TABLE ([value] [nvarchar] (MAX))
AS
BEGIN

 DECLARE @value NVARCHAR(max)
 DECLARE @pos INT

 WHILE CHARINDEX(@delim, @stringToSplit) > 0
 BEGIN
  SELECT @pos  = CHARINDEX(@delim, @stringToSplit)  
  SELECT @value = SUBSTRING(@stringToSplit, 1, @pos - 1)

  INSERT INTO @returnList 
  SELECT @value

  SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos + LEN(@delim), LEN(@stringToSplit) - @pos)
 END

 INSERT INTO @returnList
 SELECT @stringToSplit

 RETURN
END
GO

And to use it:

SELECT * FROM dbo.splitstring('test1 test2 test3', ' ');

(Tested on SQL Server 2008 R2)

EDIT: correct test code

Where to put Gradle configuration (i.e. credentials) that should not be committed?

For those of you who are building on a MacOS, and don't like leaving your password in clear text on your machine, you can use the keychain tool to store the credentials and then inject it into the build. Credits go to Viktor Eriksson. https://pilloxa.gitlab.io/posts/safer-passwords-in-gradle/

Get all variables sent with POST?

So, something like the $_POST array?

You can use http_build_query($_POST) to get them in a var=xxx&var2=yyy string again. Or just print_r($_POST) to see what's there.

How can I create an error 404 in PHP?

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

How to sort two lists (which reference each other) in the exact same way

One classic approach to this problem is to use the "decorate, sort, undecorate" idiom, which is especially simple using python's built-in zip function:

>>> list1 = [3,2,4,1, 1]
>>> list2 = ['three', 'two', 'four', 'one', 'one2']
>>> list1, list2 = zip(*sorted(zip(list1, list2)))
>>> list1
(1, 1, 2, 3, 4)
>>> list2 
('one', 'one2', 'two', 'three', 'four')

These of course are no longer lists, but that's easily remedied, if it matters:

>>> list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2))))
>>> list1
[1, 1, 2, 3, 4]
>>> list2
['one', 'one2', 'two', 'three', 'four']

It's worth noting that the above may sacrifice speed for terseness; the in-place version, which takes up 3 lines, is a tad faster on my machine for small lists:

>>> %timeit zip(*sorted(zip(list1, list2)))
100000 loops, best of 3: 3.3 us per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100000 loops, best of 3: 2.84 us per loop

On the other hand, for larger lists, the one-line version could be faster:

>>> %timeit zip(*sorted(zip(list1, list2)))
100 loops, best of 3: 8.09 ms per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100 loops, best of 3: 8.51 ms per loop

As Quantum7 points out, JSF's suggestion is a bit faster still, but it will probably only ever be a little bit faster, because Python uses the very same DSU idiom internally for all key-based sorts. It's just happening a little closer to the bare metal. (This shows just how well optimized the zip routines are!)

I think the zip-based approach is more flexible and is a little more readable, so I prefer it.