Programs & Examples On #Scalacheck

ScalaCheck is a powerful tool for automatic unit testing of Scala and Java programs.

Sql Server : How to use an aggregate function like MAX in a WHERE clause

The correct way to use max in the having clause is by performing a self join first:

select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
  on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)

The following is how you would join with a subquery:

select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
                 from table1 t1_max
                 where t1.id = t1_max.id)

Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
join #dataset d_max
  on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c

Sub query version:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
                from #dataset d_max
                where d.id = d_max.id)

MS SQL Date Only Without Time

Careful here, if you use anything a long the lines of WHERE CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam it will force a scan on the table and no indexes will be used for that portion.

A much cleaner way of doing this is defining a calculated column

create table #t (
    d datetime, 

    d2 as 
        cast (datepart(year,d) as varchar(4)) + '-' +
        right('0' + cast (datepart(month,d) as varchar(2)),2) + '-' + 
        right('0' + cast (datepart(day,d) as varchar(2)),2) 
) 
-- notice a lot of care need to be taken to ensure the format is comparable. (zero padding)

insert #t 
values (getdate())

create index idx on #t(d2)

select d2, count(d2) from #t 
where d2 between '2008-01-01' and '2009-01-22'
group by d2
-- index seek is used

This way you can directly check the d2 column and an index will be used and you dont have to muck around with conversions.

Do we have router.reload in vue-router?

`<router-link :to='`/products`' @click.native="$router.go()" class="sub-link"></router-link>`

I have tried this for reloading current page.

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

Make Sure that in Project Navigator > Signing > Team , A team name must need be selected.

enter image description here

How to calculate UILabel height dynamically?

Copy & paste this method & used It like:

[lblText setFrame:CGRectMake(lblText.frame.origin.x, lblText.frame.origin.y, width, [self getLabelHeight:lblText])];

 - (CGFloat)getLabelHeight:(UILabel*)label
    {
        CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
        CGSize size;

        NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
        CGSize boundingBox = [label.text boundingRectWithSize:constraint
                                                      options:NSStringDrawingUsesLineFragmentOrigin
                                                   attributes:@{NSFontAttributeName:label.font}
                                                      context:context].size;

        size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

        return size.height;
    }

Fastest way to check if a file exist using standard C++/C++11/C?

You can use std::ifstream, funcion like is_open, fail, for example as below code (the cout "open" means file exist or not):

enter image description here

enter image description here

cited from this answer

Kill detached screen session

screen -wipe

Should clean all dead screen sessions.

How do you find the sum of all the numbers in an array in Java?

It depends. How many numbers are you adding? Testing many of the above suggestions:

import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;

public class Main {

    public static final NumberFormat FORMAT = NumberFormat.getInstance(Locale.US);

    public static long sumParallel(int[] array) {
        final long start = System.nanoTime();
        int sum = Arrays.stream(array).parallel().reduce(0,(a,b)->  a + b);
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }

    public static long sumStream(int[] array) {
        final long start = System.nanoTime();
        int sum = Arrays.stream(array).reduce(0,(a,b)->  a + b);
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }

    public static long sumLoop(int[] array) {
        final long start = System.nanoTime();
        int sum = 0;
        for (int v: array) {
            sum += v;
        }
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }

    public static long sumArray(int[] array) {
        final long start = System.nanoTime();
        int sum = Arrays.stream(array) .sum();
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }

    public static long sumStat(int[] array) {
        final long start = System.nanoTime();
        int sum = 0;
        final long end = System.nanoTime();
        System.out.println(sum);
        return  end - start;
    }


    public static void test(int[] nums) {
        System.out.println("------");
        System.out.println(FORMAT.format(nums.length) + " numbers");
        long p = sumParallel(nums);
        System.out.println("parallel " + FORMAT.format(p));
        long s = sumStream(nums);
        System.out.println("stream " +  FORMAT.format(s));
        long ar = sumArray(nums);
        System.out.println("arrays " +  FORMAT.format(ar));
        long lp = sumLoop(nums);
        System.out.println("loop " +  FORMAT.format(lp));

    }

    public static void testNumbers(int howmany) {
        int[] nums = new int[howmany];
        for (int i =0; i < nums.length;i++) {
            nums[i] = (i + 1)%100;
        }
        test(nums);
    }

    public static void main(String[] args) {
        testNumbers(3);
        testNumbers(300);
        testNumbers(3000);
        testNumbers(30000);
        testNumbers(300000);
        testNumbers(3000000);
        testNumbers(30000000);
        testNumbers(300000000);
    }
}

I found, using an 8 core, 16 G Ubuntu18 machine, the loop was fastest for smaller values and the parallel for larger. But of course it would depend on the hardware you're running:

------
3 numbers
6
parallel 4,575,234
6
stream 209,849
6
arrays 251,173
6
loop 576
------
300 numbers
14850
parallel 671,428
14850
stream 73,469
14850
arrays 71,207
14850
loop 4,958
------
3,000 numbers
148500
parallel 393,112
148500
stream 306,240
148500
arrays 335,795
148500
loop 47,804
------
30,000 numbers
1485000
parallel 794,223
1485000
stream 1,046,927
1485000
arrays 366,400
1485000
loop 459,456
------
300,000 numbers
14850000
parallel 4,715,590
14850000
stream 1,369,509
14850000
arrays 1,296,287
14850000
loop 1,327,592
------
3,000,000 numbers
148500000
parallel 3,996,803
148500000
stream 13,426,933
148500000
arrays 13,228,364
148500000
loop 1,137,424
------
30,000,000 numbers
1485000000
parallel 32,894,414
1485000000
stream 131,924,691
1485000000
arrays 131,689,921
1485000000
loop 9,607,527
------
300,000,000 numbers
1965098112
parallel 338,552,816
1965098112
stream 1,318,649,742
1965098112
arrays 1,308,043,340
1965098112
loop 98,986,436

How to use auto-layout to move other views when a view is hidden?

What I ended up doing was creating 2 xibs. One with the left view and one without it. I registered both in the controller and then decided which to use during cellForRowAtIndexPath.

They use the same UITableViewCell class. The downside is that there is some duplication of the content between the xibs, but these cells are pretty basic. The upside is that I don't have a bunch of code to manually manage removing view, updating constraints, etc.

In general, this is probably a better solution since they are technically different layouts and therefore should have different xibs.

[self.table registerNib:[UINib nibWithNibName:@"TrackCell" bundle:nil] forCellReuseIdentifier:@"TrackCell"];
[self.table registerNib:[UINib nibWithNibName:@"TrackCellNoImage" bundle:nil] forCellReuseIdentifier:@"TrackCellNoImage"];

TrackCell *cell = [tableView dequeueReusableCellWithIdentifier:(appDelegate.showImages ? @"TrackCell" : @"TrackCellNoImage") forIndexPath:indexPath];

php: how to get associative array key from numeric index?

Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,

    function get_key($array, $index){
      $idx=0;
      while($idx!=$index  && next($array)) $idx++;
      if($idx==$index) return key($array);
      else return '';
    }

How to read a file into vector in C++?

1. In the loop you are assigning value rather than comparing value so

i=((Main.size())-1) -> i=(-1) since Main.size()

Main[i] will yield "Vector Subscript out of Range" coz i = -1.

2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.

How to parse a JSON string to an array using Jackson

I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.

 Main Class:-

String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";

        ObjectMapper mapper = new ObjectMapper();

        MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);

        for (MyPojo itr : jsonObj) {

            System.out.println("Val of getName is: " + itr.getName());
            System.out.println("Val of getCity is: " + itr.getCity());
            System.out.println("Val of getJob is: " + itr.getJob());
            System.out.println("Val of getCars is: " + itr.getCars() + "\n");

        }

POJO:

public class MyPojo {

private List<String> cars = new ArrayList<String>();

private String name;

private String job;

private String city;

public List<String> getCars() {
    return cars;
}

public void setCars(List<String> cars) {
    this.cars = cars;
}

public String getName() {
    return name;
}

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

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
} }

  RESULT:-
         Val of getName is: John
         Val of getCity is: Berlin
         Val of getJob is: Teacher
         Val of getCars is: [FIAT, Toyata]

          Val of getName is: Mark
          Val of getCity is: Oslo
          Val of getJob is: Doctor
          Val of getCars is: [VW, Toyata]

How do I create a self-signed certificate for code signing on Windows?

It's fairly easy using the New-SelfSignedCertificate command in Powershell. Open powershell and run these 3 commands.

1) Create certificate:
$cert = New-SelfSignedCertificate -DnsName www.yourwebsite.com -Type CodeSigning -CertStoreLocation Cert:\CurrentUser\My

2) set the password for it:
$CertPassword = ConvertTo-SecureString -String "my_passowrd" -Force –AsPlainText

3) Export it:
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath "d:\selfsigncert.pfx" -Password $CertPassword

Your certificate selfsigncert.pfx will be located @ D:/


Optional step: You would also require to add certificate password to system environment variables. do so by entering below in cmd: setx CSC_KEY_PASSWORD "my_password"

Generate GUID in MySQL for existing Data?

I'm not sure if it's the easiest way, but it works. The idea is to create a trigger that does all work for you, then, to execute a query that updates your table, and finally to drop this trigger:

delimiter //
create trigger beforeYourTableUpdate  BEFORE UPDATE on YourTable
FOR EACH ROW
BEGIN
  SET new.guid_column := (SELECT UUID());
END
//

Then execute

UPDATE YourTable set guid_column = (SELECT UUID());

And DROP TRIGGER beforeYourTableUpdate;

UPDATE Another solution that doesn't use triggers, but requires primary key or unique index :

UPDATE YourTable,
INNER JOIN (SELECT unique_col, UUID() as new_id FROM YourTable) new_data 
ON (new_data.unique_col = YourTable.unique_col)
SET guid_column = new_data.new_id

UPDATE once again: It seems that your original query should also work (maybe you don't need WHERE columnID is not null, so all my fancy code is not needed.

How to add items to array in nodejs

Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.

You can download from (https://npmjs.org/package/underscore)

$ npm install underscore

Here is small snippet to demonstrate how you can do it.

var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
    newArray = [];

_.each(calendars, function (item, index) {
    newArray.push(item);
});

console.log(newArray);

C# - Winforms - Global Variables

Or you could put your globals in the app.config

Appending a line break to an output file in a shell script

Try:

echo "`date` User `whoami` started the script."$'\n' >> output.log

or just:

echo $'\n' >> output.log

How to increase space between dotted border dots

Short answer: You can't.

You will have to use border-image property and a few images.

Set initial focus in an Android application

Use the code below,

TableRow _tableRow =(TableRow)findViewById(R.id.tableRowMainBody);
tableRow.requestFocus();

that should work.

De-obfuscate Javascript code to make it readable again

Try this: http://jsbeautifier.org/

I tested with your code and worked as good as possible. =D

scale fit mobile web content using viewport meta tag

For Android there is the addition of target-density tag.

target-densitydpi=device-dpi

So, the code would look like

<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />

Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.

How do change the color of the text of an <option> within a <select>?

I was recently having trouble with this same thing and I found a really simple solution.

All you have to do is set the first option to disabled and selected. Like this:

_x000D_
_x000D_
<select id="select">_x000D_
    <option disabled="disabled" selected="selected">select one option</option>_x000D_
    <option>one</option>_x000D_
    <option>two</option>_x000D_
    <option>three</option>_x000D_
    <option>four</option>_x000D_
    <option>five</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

This will display the first option (grayed out) when the page is loaded. It also prevents the user from being able to select it once they click on the list.

How do I stop/start a scheduled task on a remote computer programmatically?

Here's what I found.

stop:

schtasks /end /s <machine name> /tn <task name>

start:

schtasks /run /s <machine name> /tn <task name>


C:\>schtasks /?

SCHTASKS /parameter [arguments]

Description:
    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system. Replaces AT.exe.

Parameter List:
    /Create         Creates a new scheduled task.

    /Delete         Deletes the scheduled task(s).

    /Query          Displays all scheduled tasks.

    /Change         Changes the properties of scheduled task.

    /Run            Runs the scheduled task immediately.

    /End            Stops the currently running scheduled task.

    /?              Displays this help message.

Examples:
    SCHTASKS
    SCHTASKS /?
    SCHTASKS /Run /?
    SCHTASKS /End /?
    SCHTASKS /Create /?
    SCHTASKS /Delete /?
    SCHTASKS /Query  /?
    SCHTASKS /Change /?

HTML table with fixed headers?

A lot of people seem to be looking for this answer. I found it buried in an answer to another question here: Syncing column width of between tables in two different frames, etc

Of the dozens of methods I have tried this is the only method I found that works reliably to allow you to have a scrolling bottom table with the header table having the same widths.

Here is how I did it, first I improved upon the jsfiddle above to create this function, which works on both td and th (in case that trips up others who use th for styling of their header rows).

var setHeaderTableWidth= function (headertableid,basetableid) {
            $("#"+headertableid).width($("#"+basetableid).width());
            $("#"+headertableid+" tr th").each(function (i) {
                $(this).width($($("#"+basetableid+" tr:first td")[i]).width());
            });
            $("#" + headertableid + " tr td").each(function (i) {
                $(this).width($($("#" + basetableid + " tr:first td")[i]).width());
            });
        }

Next, you need to create two tables, NOTE the header table should have an extra TD to leave room in the top table for the scrollbar, like this:

 <table id="headertable1" class="input-cells table-striped">
        <thead>
            <tr style="background-color:darkgray;color:white;"><th>header1</th><th>header2</th><th>header3</th><th>header4</th><th>header5</th><th>header6</th><th></th></tr>
        </thead>
     </table>
    <div id="resizeToBottom" style="overflow-y:scroll;overflow-x:hidden;">
        <table id="basetable1" class="input-cells table-striped">
            <tbody >
                <tr>
                    <td>testdata</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</span></td>
                    <td>55555555555555</td>
                    <td>test</td></tr>
            </tbody>
        </table>
    </div>

Then do something like:

        setHeaderTableWidth('headertable1', 'basetable1');
        $(window).resize(function () {
            setHeaderTableWidth('headertable1', 'basetable1');
        });

This is the only solution that I found on Stack Overflow that works out of many similar questions that have been posted, that works in all my cases.

For example, I tried the jQuery stickytables plugin which does not work with durandal, and the Google Code project here https://code.google.com/p/js-scroll-table-header/issues/detail?id=2

Other solutions involving cloning the tables, have poor performance, or suck and don't work in all cases.

There is no need for these overly complex solutions. Just make two tables like the examples below and call setHeaderTableWidth function like described here and boom, you are done.

If this does not work for you, you probably were playing with your CSS box-sizing property and you need to set it correctly. It is easy to screw up your CSS content by accident. There are many things that can go wrong, so just be aware/careful of that. This approach works for me.

Get the IP Address of local computer

In DEV C++, I used pure C with WIN32, with this given piece of code:

case IDC_IP:

             gethostname(szHostName, 255);
             host_entry=gethostbyname(szHostName);
             szLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
             //WSACleanup(); 
             writeInTextBox("\n");
             writeInTextBox("IP: "); 
             writeInTextBox(szLocalIP);
             break;

When I click the button 'show ip', it works. But on the second time, the program quits (without warning or error). When I do:

//WSACleanup(); 

The program does not quit, even clicking the same button multiple times with fastest speed. So WSACleanup() may not work well with Dev-C++..

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

If you are using arrow functions:

it('should do something', async () => {
  // do your testing
}).timeout(15000)

Can you recommend a free light-weight MySQL GUI for Linux?

Why not try MySQL GUI Tools? It's light, and does its job well.

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

C# Version... note that I am getting color strings in this format #FF12AE34, and need to cut out the #FF.

    private string GetSmartShadeColorByBase(string s, float percent)
    {
        if (string.IsNullOrEmpty(s))
            return "";
        var r = s.Substring(3, 2);
        int rInt = int.Parse(r, NumberStyles.HexNumber);
        var g = s.Substring(5, 2);
        int gInt = int.Parse(g, NumberStyles.HexNumber);
        var b = s.Substring(7, 2);
        int bInt = int.Parse(b, NumberStyles.HexNumber);

        var t = percent < 0 ? 0 : 255;
        var p = percent < 0 ? percent*-1 : percent;

        int newR = Convert.ToInt32(Math.Round((t - rInt) * p) + rInt);
        var newG = Convert.ToInt32(Math.Round((t - gInt) * p) + gInt);
        var newB = Convert.ToInt32(Math.Round((t - bInt) * p) + bInt);

        return String.Format("#{0:X2}{1:X2}{2:X2}", newR, newG, newB);
    }

Can I delete data from the iOS DeviceSupport directory?

The ~/Library/Developer/Xcode/iOS DeviceSupport folder is basically only needed to symbolicate crash logs.

You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.

I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

YouTube embedded video: set different thumbnail

This solution will play the video upon clicking. You'll need to edit your picture to add a button image yourself.

You're going to need the URL of your picture and the YouTube video ID. The YouTube video id is the part of the URL after the v= parameter, so for https://www.youtube.com/watch?v=DODLEX4zzLQ the ID would be DODLEX4zzLQ.

<div width="560px" height="315px" style="position: static; clear: both; width: 560px; height: 315px;">&nbsp;<div style="position: relative"><img id="vidimg" width="560px" height="315px" src="URL_TO_PICTURE" style="position: absolute; top: 0; left: 0; cursor: pointer; pointer-events: none; z-index: 2;" /><iframe id="unlocked-video" style="position: absolute; top: 0; left: 0; z-index: 1;" src="https://www.youtube.com/embed/YOUTUBE_VIDEO_ID" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div></div>
<script type="application/javascript">
  // Adapted from https://stackoverflow.com/a/32138108
  var monitor = setInterval(function(){
    var elem = document.activeElement;
    if(elem && elem.id == 'unlocked-video'){
      document.getElementById('vidimg').style.display='none';
      clearInterval(monitor);
    }
  }, 100);
</script>

Be sure to replace URL_TO_PICTURE and YOUTUBE_VIDEO_ID in the above snippet.

To clarify what's going on here, this displays the image on top of the video, but allows clicks to pass through the image. The script monitors for clicks in the video iframe, and then hides the image if a click occurs. You may not need the float: clear.

I haven't compared this to the other answers here, but this is what I have used.

JPA Query selecting only specific columns without using Criteria Query?

Excellent answer! I do have a small addition. Regarding this solution:

TypedQuery<CustomObject> typedQuery = em.createQuery(query , String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=100";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();CustomObject.class);

To prevent a class not found error simply insert the full package name. Assuming org.company.directory is the package name of CustomObject:

String query = "SELECT NEW org.company.directory.CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();

JComboBox Selection Change Listener?

I would try the itemStateChanged() method of the ItemListener interface if jodonnell's solution fails.

How do I compare two strings in Perl?

The obvious subtext of this question is:

why can't you just use == to check if two strings are the same?

Perl doesn't have distinct data types for text vs. numbers. They are both represented by the type "scalar". Put another way, strings are numbers if you use them as such.

if ( 4 == "4" ) { print "true"; } else { print "false"; }
true

if ( "4" == "4.0" ) { print "true"; } else { print "false"; }
true

print "3"+4
7

Since text and numbers aren't differentiated by the language, we can't simply overload the == operator to do the right thing for both cases. Therefore, Perl provides eq to compare values as text:

if ( "4" eq "4.0" ) { print "true"; } else { print "false"; }
false

if ( "4.0" eq "4.0" ) { print "true"; } else { print "false"; }
true

In short:

  • Perl doesn't have a data-type exclusively for text strings
  • use == or !=, to compare two operands as numbers
  • use eq or ne, to compare two operands as text

There are many other functions and operators that can be used to compare scalar values, but knowing the distinction between these two forms is an important first step.

update to python 3.7 using anaconda

Python 3.7 is now available to be installed, but many packages have not been updated yet. As noted by another answer here, there is a GitHub issue tracking the progress of Anaconda building all the updated packages.


Until someone creates a conda package for Python 3.7, you can't install it. Unfortunately, something like 3500 packages show up in a search for "python" on Anaconda.org (https://anaconda.org/search?q=%22python%22) so I couldn't see if anyone has done that yet.

You might be able to build your own package, depending on what OS you want it for. You can start with the recipe that conda-forge uses to build Python: https://github.com/conda-forge/python-feedstock/

In the past, I think Continuum have generally waited until a stable release to push out packages for new Pythons, but I don't work there, so I don't know what their actual policy is.

embedding image in html email

There's actually a very good blog post that lists pro's and cons of three different approaches to this problem by Martyn Davies. You can read it at https://sendgrid.com/blog/embedding-images-emails-facts/.

I'd like to add a fourth approach using CSS background images.

Add

<div id="myImage"></div>

to your e-mail body and a css class like:

#myImage {
    background-image:  url('data:image/png;base64,iVBOR...[some more encoding]...rkggg==');
    width: [the-actual-image-width];
    height: [the-actual-image-height];
}

Lua - Current time in milliseconds

If your environment is Windows and you have access to system commands, you can get time of centiseconds precision with io.popen(command):

local handle = io.popen("echo %time%")
local result = handle:read("*a")
handle:close()

The result will hold string of hh:mm:ss.cc format: (with trailing line break)

"19:56:53.90\n"

Note, it's in local timesone, so you probably want to extract only the .cc part and combine it with epoch seconds from os.time().

Seedable JavaScript random number generator

If you don't need the seeding capability just use Math.random() and build helper functions around it (eg. randRange(start, end)).

I'm not sure what RNG you're using, but it's best to know and document it so you're aware of its characteristics and limitations.

Like Starkii said, Mersenne Twister is a good PRNG, but it isn't easy to implement. If you want to do it yourself try implementing a LCG - it's very easy, has decent randomness qualities (not as good as Mersenne Twister), and you can use some of the popular constants.

EDIT: consider the great options at this answer for short seedable RNG implementations, including an LCG option.

_x000D_
_x000D_
function RNG(seed) {_x000D_
  // LCG using GCC's constants_x000D_
  this.m = 0x80000000; // 2**31;_x000D_
  this.a = 1103515245;_x000D_
  this.c = 12345;_x000D_
_x000D_
  this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1));_x000D_
}_x000D_
RNG.prototype.nextInt = function() {_x000D_
  this.state = (this.a * this.state + this.c) % this.m;_x000D_
  return this.state;_x000D_
}_x000D_
RNG.prototype.nextFloat = function() {_x000D_
  // returns in range [0,1]_x000D_
  return this.nextInt() / (this.m - 1);_x000D_
}_x000D_
RNG.prototype.nextRange = function(start, end) {_x000D_
  // returns in range [start, end): including start, excluding end_x000D_
  // can't modulu nextInt because of weak randomness in lower bits_x000D_
  var rangeSize = end - start;_x000D_
  var randomUnder1 = this.nextInt() / this.m;_x000D_
  return start + Math.floor(randomUnder1 * rangeSize);_x000D_
}_x000D_
RNG.prototype.choice = function(array) {_x000D_
  return array[this.nextRange(0, array.length)];_x000D_
}_x000D_
_x000D_
var rng = new RNG(20);_x000D_
for (var i = 0; i < 10; i++)_x000D_
  console.log(rng.nextRange(10, 50));_x000D_
_x000D_
var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];_x000D_
for (var i = 0; i < 10; i++)_x000D_
  console.log(rng.choice(digits));
_x000D_
_x000D_
_x000D_

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

Have you tried using the "auto-fill" in Excel?

If you have an entire column of items you put the formula in the first cell, make sure you get the result you desire and then you can do the copy/paste, or use auto fill which is an option that sits on the bottom right corner of the cell.

You go to that corner in the cell and once your cursor changes to a "+", you can double-click on it and it should populate all the way down to the last entry (as long as there are no populated cells, that is).

How to remove word wrap from textarea?

The following CSS based solution works for me:

<html>
 <head>
  <style type='text/css'>
   textarea {
    white-space: nowrap;
    overflow:    scroll;
    overflow-y:  hidden;
    overflow-x:  scroll;
    overflow:    -moz-scrollbars-horizontal;
   }
  </style>
 </head>
 <body>
  <form>
   <textarea>This is a long line of text for testing purposes...</textarea>
  </form>
 </body>
</html>

Return a 2d array from a function

This code returns a 2d array.

 #include <cstdio>

    // Returns a pointer to a newly created 2d array the array2D has size [height x width]

    int** create2DArray(unsigned height, unsigned width)
    {
      int** array2D = 0;
      array2D = new int*[height];

      for (int h = 0; h < height; h++)
      {
            array2D[h] = new int[width];

            for (int w = 0; w < width; w++)
            {
                  // fill in some initial values
                  // (filling in zeros would be more logic, but this is just for the example)
                  array2D[h][w] = w + width * h;
            }
      }

      return array2D;
    }

    int main()
    {
      printf("Creating a 2D array2D\n");
      printf("\n");

      int height = 15;
      int width = 10;
      int** my2DArray = create2DArray(height, width);
      printf("Array sized [%i,%i] created.\n\n", height, width);

      // print contents of the array2D
      printf("Array contents: \n");

      for (int h = 0; h < height; h++)
      {
            for (int w = 0; w < width; w++)
            {
                  printf("%i,", my2DArray[h][w]);
            }
            printf("\n");
      }

          // important: clean up memory
          printf("\n");
          printf("Cleaning up memory...\n");
          for (  h = 0; h < height; h++)
          {
            delete [] my2DArray[h];
          }
          delete [] my2DArray;
          my2DArray = 0;
          printf("Ready.\n");

      return 0;
    }

What is the Oracle equivalent of SQL Server's IsNull() function?

coalesce is supported in both Oracle and SQL Server and serves essentially the same function as nvl and isnull. (There are some important differences, coalesce can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull matches the type of the first argument, that is not true for coalesce, at least on SQL Server.)

How to get value from form field in django framework?

To retrieve data from form which send post request you can do it like this

def login_view(request):
    if(request.POST):
        login_data = request.POST.dict()
        username = login_data.get("username")
        password = login_data.get("password")
        user_type = login_data.get("user_type")
        print(user_type, username, password)
        return HttpResponse("This is a post request")
    else:
        return render(request, "base.html")

oracle plsql: how to parse XML and insert into table

CREATE OR REPLACE PROCEDURE ADDEMP
    (xml IN CLOB)
AS
BEGIN
    INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
    SELECT 
        ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
       ,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
       ,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
       ,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
       ,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
    FROM   TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;

    COMMIT;
END;

How can a LEFT OUTER JOIN return more records than exist in the left table?

In response to your postscript, that depends on what you would like.

You are getting (possible) multiple rows for each row in your left table because there are multiple matches for the join condition. If you want your total results to have the same number of rows as there is in the left part of the query you need to make sure your join conditions cause a 1-to-1 match.

Alternatively, depending on what you actually want you can use aggregate functions (if for example you just want a string from the right part you could generate a column that is a comma delimited string of the right side results for that left row.

If you are only looking at 1 or 2 columns from the outer join you might consider using a scalar subquery since you will be guaranteed 1 result.

What is “assert” in JavaScript?

assert() is not a native javascript function. It is a custom function someone made. You will have to look for it on your page or in your files and post it for anybody to help determine what it's doing.

Live-stream video from one android phone to another over WiFi

You can use IP Webcam, or perhaps use DLNA. For example Samsung devices come with an app called AllShare which can share and access DLNA enabled devices on the network. I think IP Webcam is your best bet, though. You should be able to open the stream it creates using MX Video player or something like that.

LINQ Where with AND OR condition

from item in db.vw_Dropship_OrderItems
    where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
    (listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
    select item;

Might give strange behavior if both listMerchants and listStatus are both null.

How to check if a file exists in the Documents directory in Swift?

For the benefit of Swift 3 beginners:

  1. Swift 3 has done away with most of the NextStep syntax
  2. So NSURL, NSFilemanager, NSSearchPathForDirectoriesInDomain are no longer used
  3. Instead use URL and FileManager
  4. NSSearchPathForDirectoriesInDomain is not needed
  5. Instead use FileManager.default.urls

Here is a code sample to verify if a file named "database.sqlite" exists in application document directory:

func findIfSqliteDBExists(){

    let docsDir     : URL       = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let dbPath      : URL       = docsDir.appendingPathComponent("database.sqlite")
    let strDBPath   : String    = dbPath.path
    let fileManager : FileManager   = FileManager.default

    if fileManager.fileExists(atPath:strDBPath){
        print("An sqlite database exists at this path :: \(strDBPath)")
    }else{
        print("SQLite NOT Found at :: \(strDBPath)")
    }

}

Number of days between past date and current date in Google spreadsheet

If you are using the two formulas at the same time, it will not work... Here is a simple spreadsheet with it working: https://docs.google.com/spreadsheet/ccc?key=0AiOy0YDBXjt4dDJSQWg1Qlp6TEw5SzNqZENGOWgwbGc If you are still getting problems I would need to know what type of erroneous result you are getting.

Today() returns a numeric integer value: Returns the current computer system date. The value is updated when your document recalculates. TODAY is a function without arguments.

Simple way to read single record from MySQL

Easy way to Fetch Single Record from MySQL Database by using PHP List

The SQL Query is SELECT user_name from user_table WHERE user_id = 6

The PHP Code for the above Query is

$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= "  user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;

$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);

Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows

search in java ArrayList

Others have pointed out the error in your existing code, but I'd like to take two steps further. Firstly, assuming you're using Java 1.5+, you can achieve greater readability using the enhanced for loop:

Customer findCustomerByid(int id){    
    for (Customer customer : customers) {
        if (customer.getId() == id) {
            return customer;
        }
    }
    return null; 
}

This has also removed the micro-optimisation of returning null before looping - I doubt that you'll get any benefit from it, and it's more code. Likewise I've removed the exists flag: returning as soon as you know the answer makes the code simpler.

Note that in your original code I think you had a bug. Having found that the customer at index i had the right ID, you then returned the customer at index id - I doubt that this is really what you intended.

Secondly, if you're going to do a lot of lookups by ID, have you considered putting your customers into a Map<Integer, Customer>?

Error in model.frame.default: variable lengths differ

Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))

If you then try predict(m), you get the same error as in this question.

Push an associative item into an array in JavaScript

JavaScript doesn't have associate arrays. You need to use Objects instead:

var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?

To get value you can use now different ways:

console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?

How can I use jQuery to move a div across the screen

You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.

Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.

To read up on this, check out this thread (from my very first Stackoverflow post no less)!

Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

To complete your setup or MySQL:

sudo vim /etc/profile
  1. Add alias

    alias mysql=/usr/local/mysql/bin/mysql
    alias mysqladmin=/usr/local/mysql/bin/mysqladmin
    
  2. Then set your root password

    mysqladmin -u root password 'yourPassword'
    
  3. Then you can login with

    mysql -u root -p
    

Where is the IIS Express configuration / metabase file found?

For Visual Studio 2019 (v16.2.4) I was only able to find this file here:

C:\Users\\Documents\IISExpress\config\applicationhost.config applicationhost.config

Hope this helps as I wasn't able to find the .vs folder location as mentioned in the above suggestions.

Curl to return http status code along with the response

while : ; do curl -sL -w "%{http_code} %{url_effective}\\n" http://host -o /dev/null; done

WPF Datagrid Get Selected Cell Value

I'm extending the solution by Rushi to following (which solved the puzzle for me)

var cellInfo = Grid1.SelectedCells[0];
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

Why use a READ UNCOMMITTED isolation level?

This can be useful to see the progress of long insert queries, make any rough estimates (like COUNT(*) or rough SUM(*)) etc.

In other words, the results the dirty read queries return are fine as long as you treat them as estimates and don't make any critical decisions based upon them.

How to define constants in ReactJS

Warning: this is an experimental feature that could dramatically change or even cease to exist in future releases

You can use ES7 statics:

npm install babel-preset-stage-0

And then add "stage-0" to .babelrc presets:

{
    "presets": ["es2015", "react", "stage-0"]
}

Afterwards, you go

class Component extends React.Component {
    static foo = 'bar';
    static baz = {a: 1, b: 2}
}

And then you use them like this:

Component.foo

JOIN two SELECT statement results

Try something like this:

SELECT 
* 
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1 
INNER JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON t1.ks = t2.ks

Facebook database design?

My best bet is that they created a graph structure. The nodes are users and "friendships" are edges.

Keep one table of users, keep another table of edges. Then you can keep data about the edges, like "day they became friends" and "approved status," etc.

What's the difference between equal?, eql?, ===, and ==?

Ruby exposes several different methods for handling equality:

a.equal?(b) # object identity - a and b refer to the same object

a.eql?(b) # object equivalence - a and b have the same value

a == b # object equivalence - a and b have the same value with type conversion.

Continue reading by clicking the link below, it gave me a clear summarized understanding.

https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/equality-matchers

Hope it helps others.

Set background colour of cell to RGB value of data in cell

Setting the Color property alone will guarantee an exact match. Excel 2003 can only handle 56 colors at once. The good news is that you can assign any rgb value at all to those 56 slots (which are called ColorIndexs). When you set a cell's color using the Color property this causes Excel to use the nearest "ColorIndex". Example: Setting a cell to RGB 10,20,50 (or 3281930) will actually cause it to be set to color index 56 which is 51,51,51 (or 3355443).

If you want to be assured you got an exact match, you need to change a ColorIndex to the RGB value you want and then change the Cell's ColorIndex to said value. However you should be aware that by changing the value of a color index you change the color of all cells already using that color within the workbook. To give an example, Red is ColorIndex 3. So any cell you made Red you actually made ColorIndex 3. And if you redefine ColorIndex 3 to be say, purple, then your cell will indeed be made purple, but all other red cells in the workbook will also be changed to purple.

There are several strategies to deal with this. One way is to choose an index not yet in use, or just one that you think will not be likely to be used. Another way is to change the RGB value of the nearest ColorIndex so your change will be subtle. The code I have posted below takes this approach. Taking advantage of the knowledge that the nearest ColorIndex is assigned, it assigns the RGB value directly to the cell (thereby yielding the nearest color) and then assigns the RGB value to that index.

Sub Example()
    Dim lngColor As Long
    lngColor = RGB(10, 20, 50)
    With Range("A1").Interior
        .Color = lngColor
        ActiveWorkbook.Colors(.ColorIndex) = lngColor
    End With
End Sub

How do I get a Cron like scheduler in Python?

I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see http://docs.python.org/library/time.html

The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you do need to rely on system dependent solutions.

Producer/Consumer threads using a Queue

This is a very simple code.

import java.util.*;

// @author : rootTraveller, June 2017

class ProducerConsumer {
    public static void main(String[] args) throws Exception {
        Queue<Integer> queue = new LinkedList<>();
        Integer buffer = new Integer(10);  //Important buffer or queue size, change as per need.

        Producer producerThread = new Producer(queue, buffer, "PRODUCER");
        Consumer consumerThread = new Consumer(queue, buffer, "CONSUMER");

        producerThread.start();  
        consumerThread.start();
    }   
}

class Producer extends Thread {
    private Queue<Integer> queue;
    private int queueSize ;

    public Producer (Queue<Integer> queueIn, int queueSizeIn, String ThreadName){
        super(ThreadName);
        this.queue = queueIn;
        this.queueSize = queueSizeIn;
    }

    public void run() {
        while(true){
            synchronized (queue) {
                while(queue.size() == queueSize){
                    System.out.println(Thread.currentThread().getName() + " FULL         : waiting...\n");
                    try{
                        queue.wait();   //Important
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                //queue empty then produce one, add and notify  
                int randomInt = new Random().nextInt(); 
                System.out.println(Thread.currentThread().getName() + " producing... : " + randomInt); 
                queue.add(randomInt); 
                queue.notifyAll();  //Important
            } //synchronized ends here : NOTE
        }
    }
}

class Consumer extends Thread {
    private Queue<Integer> queue;
    private int queueSize;

    public Consumer(Queue<Integer> queueIn, int queueSizeIn, String ThreadName){
        super (ThreadName);
        this.queue = queueIn;
        this.queueSize = queueSizeIn;
    }

    public void run() {
        while(true){
            synchronized (queue) {
                while(queue.isEmpty()){
                    System.out.println(Thread.currentThread().getName() + " Empty        : waiting...\n");
                    try {
                        queue.wait();  //Important
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                //queue not empty then consume one and notify
                System.out.println(Thread.currentThread().getName() + " consuming... : " + queue.remove());
                queue.notifyAll();
            } //synchronized ends here : NOTE
        }
    }
}

C++ - Assigning null to a std::string

Many C APIs use a null pointer to indicate "use the default", e.g. mosquittopp. Here is the pattern I am using, based on David Cormack's answer:

    mosqpp::tls_set(
        MqttOptions->CAFile.length() > 0 ? MqttOptions->CAFile.c_str() : NULL,
        MqttOptions->CAPath.length() > 0 ? MqttOptions->CAPath.c_str() : NULL,
        MqttOptions->CertFile.length() > 0 ? MqttOptions->CertFile.c_str() : NULL,
        MqttOptions->KeyFile.length() > 0 ? MqttOptions->KeyFile.c_str() : NULL
    );

It is a little cumbersome, but allows one to keep everything as a std::string up until the API call itself.

What is the difference between onBlur and onChange attribute in HTML?

I think it's important to note here that onBlur() fires regardless.

This is a helpful thread but the only thing it doesn't clarify is that onBlur() will fire every single time.

onChange() will only fire when the value is changed.

Sieve of Eratosthenes - Finding Primes Python

A simple speed hack: when you define the variable "primes," set the step to 2 to skip all even numbers automatically, and set the starting point to 1.

Then you can further optimize by instead of for i in primes, use for i in primes[:round(len(primes) ** 0.5)]. That will dramatically increase performance. In addition, you can eliminate numbers ending with 5 to further increase speed.

How do a send an HTTPS request through a proxy in Java?

HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.

You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,

http://www.javaworld.com/javaworld/javatips/jw-javatip111.html

EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,

 public SSLTunnelSocketFactory(String proxyhost, String proxyport){
      tunnelHost = proxyhost;
      tunnelPort = Integer.parseInt(proxyport);
      dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
 }

 ...

 connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
 connection.setDefaultHostnameVerifier( new HostnameVerifier()
 {
    public boolean verify( String arg0, SSLSession arg1 )
    {
        return true;
    }
 }  );

EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,

http://bugs.sun.com/view_bug.do?bug_id=6614957

The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,

public class SSLContextTest {

    public static void main(String[] args) {

        System.setProperty("https.proxyHost", "proxy.xxx.com");
        System.setProperty("https.proxyPort", "8888");

        try {

            SSLContext sslContext = SSLContext.getInstance("SSL");

            // set up a TrustManager that trusts everything
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkServerTrusted =============");
                }
            } }, new SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(
                    sslContext.getSocketFactory());

            HttpsURLConnection
                    .setDefaultHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String arg0, SSLSession arg1) {
                            System.out.println("hostnameVerifier =============");
                            return true;
                        }
                    });

            URL url = new URL("https://www.verisign.net");
            URLConnection conn = url.openConnection();
            BufferedReader reader = 
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}

This is what I get when I run the program,

checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......

As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.

How to target only IE (any version) within a stylesheet?

Here's a collection of media queries that will allow you to do that for any version of Internet Explorer (from IE6 to IE11+), Firefox, Chrome & Safari (EDIT: also added Opera).

IE 6

* html .ie6 { property: value; }

or

.ie6 { _property: value; }

IE 7

*+html .ie7 { property: value; }

or

*:first-child+html .ie7 { property: value; }

IE 6 and 7

@media screen\9 { 
    .ie67 {
        property: value; 
    }
}

or

.ie67 { *property: value; }

or

.ie67 { #property: value; }

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {
        property: value;
    }
}

IE 8

html>/**/body .ie8 { property: value; }

or

@media \0screen {
    .ie8 {
        property: value;
    }
}

IE 8 Standards Mode

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {
        property: value;
    }
}

IE 9 only

@media screen and (min-width:0\0) and (min-resolution: .001dpcm) { 
    // IE9 CSS
    .ie9{
        property: value;
    }
}

IE 9 and above

@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
    // IE9+ CSS
    .ie9up { 
        property: value; 
    }
}

IE 9 and 10

@media screen and (min-width:0\0) {
    .ie910 {
        property: value\9;
    } /* backslash-9 removes ie11+ & old Safari 4 */
}

IE 10 only

_:-ms-lang(x), .ie10 { property: value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property: value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    .ie10up {
        property:value;
    }
}

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property: value; }

Firefox (any version)

@-moz-document url-prefix() {
    .ff {
        color: red;
    }
}

Firefox (Quantum Only / Stylo)

@-moz-document url-prefix() {
    @supports (animation: calc(0s)) {
        /* Stylo */
        .ffStylo {
            property: value;
        }
    }
}

Firefox Legacy (pre-Stylo)

@-moz-document url-prefix() {
    @supports not (animation: calc(0s)) {
        /* Gecko */
        .ffGecko {
            property: value;
        }
    }
}

Webkit (Chrome & Safari, any version)

@media screen and (-webkit-min-device-pixel-ratio:0) { 
    property: value;
}

Google Chrome (29+)

@media screen and (-webkit-min-device-pixel-ratio:0) and (min-resolution:.001dpcm) {
    .chrome {
        property: value;
    }
}

Safari (7.1+)

_::-webkit-full-page-media, _:future, :root .safari_only {
    property: value;
}

Safari (from 6.1 to 10.0)

@media screen and (min-color-index:0) and(-webkit-min-device-pixel-ratio:0) { 
    @media {
        .safari6 { 
            color:#0000FF; 
            background-color:#CCCCCC; 
        }
    }
}

Safari (10.1+)

@media not all and (min-resolution:.001dpcm) { 
    @media {
        .safari10 { 
            color:#0000FF; 
            background-color:#CCCCCC; 
        }
    }
}

Opera (12+)

@media (min-resolution: .001dpcm) {
    _:-o-prefocus, .selector {
        .opera12 {
            color:#0000FF; 
            background-color:#CCCCCC; 
        }
    } 
}

Opera (11 and lower)

@media all and (-webkit-min-device-pixel-ratio:10000), not all and (-webkit-min-device-pixel-ratio:0) {
    .opera11 {
        color:#0000FF; 
        background-color:#CCCCCC; 
    }
}

For further info or additional media queries, visit the browserhacks.com web site and/or check out this blog post that I wrote on this topic.

How does "make" app know default target to build if no target is specified?

By default, it begins by processing the first target that does not begin with a . aka the default goal; to do that, it may have to process other targets - specifically, ones the first target depends on.

The GNU Make Manual covers all this stuff, and is a surprisingly easy and informative read.

Detect if checkbox is checked or unchecked in Angular.js ng-change event

You could just use the bound ng-model (answers[item.questID]) value itself in your ng-change method to detect if it has been checked or not.

Example:-

<input type="checkbox" ng-model="answers[item.questID]" 
     ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->

and

$scope.stateChanged = function (qId) {
   if($scope.answers[qId]){ //If it is checked
       alert('test');
   }
}

Drop columns whose name contains a specific string from pandas DataFrame

Solution when dropping a list of column names containing regex. I prefer this approach because I'm frequently editing the drop list. Uses a negative filter regex for the drop list.

drop_column_names = ['A','B.+','C.*']
drop_columns_regex = '^(?!(?:'+'|'.join(drop_column_names)+')$)'
print('Dropping columns:',', '.join([c for c in df.columns if re.search(drop_columns_regex,c)]))
df = df.filter(regex=drop_columns_regex,axis=1)

What is the difference between explicit and implicit cursors in Oracle?

An explicit cursor is one you declare, like:

CURSOR my_cursor IS
  SELECT table_name FROM USER_TABLES

An implicit cursor is one created to support any in-line SQL you write (either static or dynamic).

What's the best way to determine which version of Oracle client I'm running?

You should put a semicolon at the end of select * from v$version;.

Like this you will get all info you need...

If you are looking just for Oracle for example you can do as:

SQL> select * from v$version where banner like 'Oracle%';

How do you convert a JavaScript date to UTC?

Date.prototype.toUTCArray= function(){
    var D= this;
    return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
    D.getUTCMinutes(), D.getUTCSeconds()];
}

Date.prototype.toISO= function(){
    var tem, A= this.toUTCArray(), i= 0;
    A[1]+= 1;
    while(i++<7){
        tem= A[i];
        if(tem<10) A[i]= '0'+tem;
    }
    return A.splice(0, 3).join('-')+'T'+A.join(':');    
}

What are -moz- and -webkit-?

What are -moz- and -webkit-?

CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes.


Why do different browsers add different prefixes for the same effect?

A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:

Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.

Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.

Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid.

The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.


UPDATE AS OF THE YEAR 2016

As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.

As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016,

Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.

For example, just a few years ago, to set a rounded corner on a box you had to write:

-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;

But now that browsers have come to fully support this feature, you really only need the standardized version:

border-radius: 10px 5px;

Finding the right rules for all browsers

As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.

You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.

Input:

a {
  column-count: 3;
  column-gap: 10px;
  column-fill: auto;
}

Output:

a {
  -webkit-column-count: 3;
     -moz-column-count: 3;
          column-count: 3;
  -webkit-column-gap: 10px;
     -moz-column-gap: 10px;
          column-gap: 10px;
  -webkit-column-fill: auto;
     -moz-column-fill: auto;
          column-fill: auto;
}

How can I commit a single file using SVN over a network?

You can use

cd /You folder name
svn commit 'your file path' -m "Commit message you want to give"

You can also drage you files to command promt instead to write cd [common in MAC OSx]

Override default Spring-Boot application.properties settings in Junit Test

Spring Boot automatically loads src/test/resources/application.properties, if following annotations are used

@RunWith(SpringRunner.class)
@SpringBootTest

So, rename test.properties to application.properties to utilize auto configuration.

If you only need to load the properties file (into the Environment) you can also use the following, as explained here

@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class) 

[Update: Overriding certain properties for testing]

  1. Add src/main/resources/application-test.properties.
  2. Annotate test class with @ActiveProfiles("test").

This loads application.properties and then application-test.properties properties into application context for the test case, as per rules defined here.

Demo - https://github.com/mohnish82/so-spring-boot-testprops

How to get the selected radio button’s value?

Try this

function findSelection(field) {
    var test = document.getElementsByName(field);
    var sizes = test.length;
    alert(sizes);
    for (i=0; i < sizes; i++) {
            if (test[i].checked==true) {
            alert(test[i].value + ' you got a value');     
            return test[i].value;
        }
    }
}


function submitForm() {

    var genderS =  findSelection("genderS");
    alert(genderS);
    return false;
}

A fiddle here.

Error C1083: Cannot open include file: 'stdafx.h'

Just running through a Visual Studio Code tutorial and came across a similiar issue.

Replace #include "stdafx.h" with #include "pch.h" which is the updated name for the precompiled headers.

Counting the number of occurences of characters in a string

You should be able to utilize the StringUtils class and the countMatches() method.

public static int countMatches(String str, String sub)

Counts how many times the substring appears in the larger String.

Try the following:

int count = StringUtils.countMatches("a.b.c.d", ".");

Selecting multiple columns in a Pandas dataframe

One different and easy approach: iterating rows

Using iterows

 df1 = pd.DataFrame() # Creating an empty dataframe
 for index,i in df.iterrows():
    df1.loc[index, 'A'] = df.loc[index, 'A']
    df1.loc[index, 'B'] = df.loc[index, 'B']
    df1.head()

How to get all subsets of a set? (powerset)

def powerset(some_set):
    res = [(a,b) for a in some_set for b in some_set]
    return res

How can I convert a .py to .exe for Python?

I've been using Nuitka and PyInstaller with my package, PySimpleGUI.

Nuitka There were issues getting tkinter to compile with Nuikta. One of the project contributors developed a script that fixed the problem.

If you're not using tkinter it may "just work" for you. If you are using tkinter say so and I'll try to get the script and instructions published.

PyInstaller I'm running 3.6 and PyInstaller is working great! The command I use to create my exe file is:

pyinstaller -wF myfile.py

The -wF will create a single EXE file. Because all of my programs have a GUI and I do not want to command window to show, the -w option will hide the command window.

This is as close to getting what looks like a Winforms program to run that was written in Python.

[Update 20-Jul-2019]

There is PySimpleGUI GUI based solution that uses PyInstaller. It uses PySimpleGUI. It's called pysimplegui-exemaker and can be pip installed.

pip install PySimpleGUI-exemaker

To run it after installing:

python -m pysimplegui-exemaker.pysimplegui-exemaker

java IO Exception: Stream Closed

You're calling writer.close(); after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.

public void writeToFile(){
    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;
    try {
        writer.write(file_text);
        writer.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And add a method cleanUp to close the stream.

public void cleanUp() {
     writer.close();
}

This means that you have the responsibility to make sure that you're calling cleanUp when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.

EDIT: You can create a new stream each time you want to write to the file, by moving writer into the writeToFile() method..

 public void writeToFile() {
    FileWriter writer = new FileWriter("status.txt", true);
    // ... Write to the file.

    writer.close();
 }

Split page vertically using CSS

Alternatively, you can also use a special function known as the linear-gradient() function to split browser screen into two equal halves. Check out the following code snippet:

body
{
  background-image:linear-gradient(90deg, lightblue 50%, skyblue 50%);
}

Here, linear-gradient() function accepts three arguments

  1. 90deg for vertical division of screen.( Similarly, you can use 180deg for horizontal division of screen)
  2. lightblue color is used to represent the left half of the screen.
  3. skyblue color has been used to represent the right half of the split screen. Here, 50% has been used for equal division of the browser screen. You can use any other value if you don't want an equal division of the screen. Hope this helps. :) Happy Coding!

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

How do you find out the caller function in JavaScript?

I'm attempting to address both the question and the current bounty with this question.

The bounty requires that the caller be obtained in strict mode, and the only way I can see this done is by referring to a function declared outside of strict mode.

For example, the following is non-standard but has been tested with previous (29/03/2016) and current (1st August 2018) versions of Chrome, Edge and Firefox.

_x000D_
_x000D_
function caller()_x000D_
{_x000D_
   return caller.caller.caller;_x000D_
}_x000D_
_x000D_
'use strict';_x000D_
function main()_x000D_
{_x000D_
   // Original question:_x000D_
   Hello();_x000D_
   // Bounty question:_x000D_
   (function() { console.log('Anonymous function called by ' + caller().name); })();_x000D_
}_x000D_
_x000D_
function Hello()_x000D_
{_x000D_
   // How do you find out the caller function is 'main'?_x000D_
   console.log('Hello called by ' + caller().name);_x000D_
}_x000D_
_x000D_
main();
_x000D_
_x000D_
_x000D_

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

get all keys set in memcached

If you have PHP & PHP-memcached installed, you can run

$ php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'

How do I compile a .c file on my Mac?

Use the gcc compiler. This assumes that you have the developer tools installed.

Return first N key:value pairs from dict

You can get dictionary items by calling .items() on the dictionary. then convert that to a list and from there get first N items as you would on any list.

below code prints first 3 items of the dictionary object

e.g.

d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

first_three_items = list(d.items())[:3]

print(first_three_items)

Outputs:

[('a', 3), ('b', 2), ('c', 3)]

Remove Rows From Data Frame where a Row matches a String

I had a column(A) in a data frame with 3 values in it (yes, no, unknown). I wanted to filter only those rows which had a value "yes" for which this is the code, hope this will help you guys as well --

df <- df [(!(df$A=="no") & !(df$A=="unknown")),]

Pass in an array of Deferreds to $.when()

To pass an array of values to any function that normally expects them to be separate parameters, use Function.prototype.apply, so in this case you need:

$.when.apply($, my_array).then( ___ );

See http://jsfiddle.net/YNGcm/21/

In ES6, you can use the ... spread operator instead:

$.when(...my_array).then( ___ );

In either case, since it's unlikely that you'll known in advance how many formal parameters the .then handler will require, that handler would need to process the arguments array in order to retrieve the result of each promise.

export html table to csv

(1)This is the native javascript solution for this issue. It works on most of modern browsers.

_x000D_
_x000D_
function export2csv() {_x000D_
  let data = "";_x000D_
  const tableData = [];_x000D_
  const rows = document.querySelectorAll("table tr");_x000D_
  for (const row of rows) {_x000D_
    const rowData = [];_x000D_
    for (const [index, column] of row.querySelectorAll("th, td").entries()) {_x000D_
      // To retain the commas in the "Description" column, we can enclose those fields in quotation marks._x000D_
      if ((index + 1) % 3 === 0) {_x000D_
        rowData.push('"' + column.innerText + '"');_x000D_
      } else {_x000D_
        rowData.push(column.innerText);_x000D_
      }_x000D_
    }_x000D_
    tableData.push(rowData.join(","));_x000D_
  }_x000D_
  data += tableData.join("\n");_x000D_
  const a = document.createElement("a");_x000D_
  a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));_x000D_
  a.setAttribute("download", "data.csv");_x000D_
  document.body.appendChild(a);_x000D_
  a.click();_x000D_
  document.body.removeChild(a);_x000D_
}
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td, th {_x000D_
  border: 1px solid #aaa;_x000D_
  padding: 0.5rem;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
  font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
  padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #000;_x000D_
  margin-top: 0.5rem;_x000D_
  border-radius: 3px;_x000D_
  padding: 0.5rem 1rem;_x000D_
  font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  cursor: pointer;_x000D_
  background-color: #000;_x000D_
  color: #fff;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Name</th>_x000D_
      <th>Author</th>_x000D_
      <th>Description</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>jQuery</td>_x000D_
      <td>John Resig</td>_x000D_
      <td>The Write Less, Do More, JavaScript Library.</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>React</td>_x000D_
      <td>Jordan Walke</td>_x000D_
      <td>React makes it painless to create interactive UIs.</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Vue.js</td>_x000D_
      <td>Yuxi You</td>_x000D_
      <td>The Progressive JavaScript Framework.</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button onclick="export2csv()">csv</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(2) If you want a pure javascript library, FileSaver.js could help you save the code snippets for triggering file download. Besides, FileSaver.js will not be responsible for constructing content for exporting. You have to construct the content by yourself in the format you want.

How do I add a reference to the MySQL connector for .NET?

In Visual Studio you can use nuget to download the latest version. Just right click on the project and click 'Manage NuGet Packages' then search online for MySql.Data and install.

Getting list of Facebook friends with latest API

I think this is what you want:

$friends = $facebook->api('/me/friends');

Warning: Failed propType: Invalid prop `component` supplied to `Route`

it is solved in react-router-dom 4.4.0 see: Route's proptypes fail

now it is beta, or just wait for final release.

npm install [email protected] --save

Can a java file have more than one class?

Yes, it can. However, there can only be one public top-level class per .java file, and public top-level classes must have the same name as the source file.

The purpose of including multiple classes in one source file is to bundle related support functionality (internal data structures, support classes, etc) together with the main public class. Note that it is always OK not to do this--the only effect is on the readability (or not) of your code.

Contain form within a bootstrap popover?

Or try this one

Second one including second hidden div content to hold the form working and test on fiddle http://jsfiddle.net/7e2XU/21/

<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
   <script src="http://twitter.github.com/bootstrap/assets/js/bootstrap-tooltip.js"></script>
    <script src="http://twitter.github.com/bootstrap/assets/js/bootstrap-popover.js"></script>


<div id="popover-content" style="display: none" >
    <div class="container" style="margin: 25px; ">
    <div class="row" style="padding-top: 240px;">
        <label id="sample">
            <form id="mainForm" name="mainForm" method="post" action="">
    <p>
        <label>Name :</label>
        <input type="text" id="txtName" name="txtName" />
    </p>
    <p>
        <label>Address 1 :</label>
        <input type="text" id="txtAddress" name="txtAddress" />
    </p>
    <p>
        <label>City :</label>
        <input type="text" id="txtCity" name="txtCity" />
    </p>
    <p>
        <input type="submit" name="Submit" value="Submit" />
    </p>
</form>

        </label>
    </div>
          </div> 
</div>

 <a href="#" style="margin: 40px 40px;" class="btn btn-large btn-primary" rel="popover" data-content='' data-placement="left" data-original-title="Fill in form">Open form</a>


<script>

$('a[rel=popover]').popover({
    html: 'true',
placement: 'right',
content : function() {
    return $('#popover-content').html();
}
})



</script>

pip install access denied on Windows

Try to delete the folder c:\\users\\bruno\\appdata\\local\\temp\\easy_install-0fme6u manually and then retry the pip command.

MySQL - sum column value(s) based on row from the same table

I think you're making this a bit more complicated than it needs to be.

SELECT
    ProductID,
    SUM(IF(PaymentMethod = 'Cash', Amount, 0)) AS 'Cash',
    -- snip
    SUM(Amount) AS Total
FROM
    Payments
WHERE
    SaleDate = '2012-02-10'
GROUP BY
    ProductID

How to get primary key column in Oracle?

Save the following script as something like findPK.sql.

set verify off
accept TABLE_NAME char prompt 'Table name>'

SELECT cols.column_name
FROM all_constraints cons NATURAL JOIN all_cons_columns cols
WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME');

It can then be called using

@findPK

How to overwrite styling in Twitter Bootstrap

Add your own class, ex: <div class="sidebar right"></div>, with the CSS as

.sidebar.right { 
    float:right
} 

How do I output text without a newline in PowerShell?

You can absolutely do this. Write-Output has a flag called "NoEnumerate" that is essentially the same thing.

Java - get index of key in HashMap?

Not sure if this is any "cleaner", but:

List keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++) {
    Object obj = keys.get(i);
    // do stuff here
}

Allow docker container to connect to a local/host postgres database

Simple solution

Just add --network=host to docker run. That's all!

This way container will use the host's network, so localhost and 127.0.0.1 will point to the host (by default they point to a container). Example:

docker run -d --network=host \
  -e "DB_DBNAME=your_db" \
  -e "DB_PORT=5432" \
  -e "DB_USER=your_db_user" \
  -e "DB_PASS=your_db_password" \
  -e "DB_HOST=127.0.0.1" \
  --name foobar foo/bar

serialize/deserialize java 8 java.time with Jackson JSON mapper

If any one having problem while using SpringBoot here is how I fixed the issue without adding new dependency.

In Spring 2.1.3 Jackson expects date string 2019-05-21T07:37:11.000 in this yyyy-MM-dd HH:mm:ss.SSS format to de-serialize in LocalDateTime. Make sure date string separates the date and time with T not with space. seconds (ss) and milliseconds(SSS) could be ommitted.

@JsonProperty("last_charge_date")
public LocalDateTime lastChargeDate;

Get folder up one level

The parent directory of an included file would be

dirname(getcwd())

e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php

then by calling /file/index.php

getcwd() is /var/www/html/folder  
__DIR__ is /var/www/html/folder/inc  
so dirname(__DIR__) is /var/www/html/folder

but what we want is /var/www/html which is dirname(getcwd())

SQL Query Where Date = Today Minus 7 Days

Use the built in functions:

SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
GROUP BY URLx
ORDER BY Count DESC; 

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

concatenate two strings

You can use concatenation operator and instead of declaring two variables only use one variable

String finalString =  cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

Zero-pad digits in string

Solution using str_pad:

str_pad($digit,2,'0',STR_PAD_LEFT);

Benchmark on php 5.3

Result str_pad : 0.286863088608

Result sprintf : 0.234171152115

Code:

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    str_pad(9,2,'0',STR_PAD_LEFT);
    str_pad(15,2,'0',STR_PAD_LEFT);
    str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";

$start = microtime(true);
for ($i=0;$i<100000;$i++) {
    sprintf("%02d", 9);
    sprintf("%02d", 15);
    sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";

UIView frame, bounds and center

This question already has a good answer, but I want to supplement it with some more pictures. My full answer is here.

To help me remember frame, I think of a picture frame on a wall. Just like a picture can be moved anywhere on the wall, the coordinate system of a view's frame is the superview. (wall=superview, frame=view)

To help me remember bounds, I think of the bounds of a basketball court. The basketball is somewhere within the court just like the coordinate system of the view's bounds is within the view itself. (court=view, basketball/players=content inside the view)

Like the frame, view.center is also in the coordinates of the superview.

Frame vs Bounds - Example 1

The yellow rectangle represents the view's frame. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds within their coordinate systems.

Frame
    origin = (0, 0)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 2

Frame
    origin = (40, 60)  // That is, x=40 and y=60
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 3

Frame
    origin = (20, 52)  // These are just rough estimates.
    width = 118
    height = 187

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 4

This is the same as example 2, except this time the whole content of the view is shown as it would look like if it weren't clipped to the bounds of the view.

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (0, 0)
    width = 80
    height = 130

enter image description here


Example 5

Frame
    origin = (40, 60)
    width = 80
    height = 130

Bounds 
    origin = (280, 70)
    width = 80
    height = 130

enter image description here

Again, see here for my answer with more details.

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

Bad Request - Invalid Hostname IIS7

This solved my problem (sorry for my bad English):

  1. open cmd as administrator and run command (Without the square brackets):
    netsh http add urlacl url=http://[ip adress]:[port]/ user=everyone

  2. in documents/iisexpress/config/applicationhost.config and in your root project folder in (hidden) folder: .vs/config/applicationhost.config you need add row to "site" tag:
    <binding protocol="http" bindingInformation="*:8080:192.xxx.xxx.xxx" />

  3. open "internet information services (iis) manager"
    (to find it: in search in taskbar write "Turn Window features on or off" and open result and then check the checkbox "internet information service" and install that):

    1. in left screen click: computer-name --> Sites --> Default Web Site and
    2. then click in right screen "Binding"
    3. click Add button
    4. write what you need and press "OK".
  4. open "Windows Firewall With Advanced Security",

    1. in left screen press "Inbound Rules" and then
    2. press in right screen "New Rule..."
    3. check port and press Next,
    4. check TCP and your port and press Next,
    5. check "Allow the connection" and press Next,
    6. check all checkbox and press Next,
    7. write name and press Finish.
  5. done.

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

How to type ":" ("colon") in regexp?

use \\: instead of \:.. the \ has special meaning in java strings.

How to make a smaller RatingBar?

<RatingBar
    android:id="@+id/rating_bar"
    style="@style/Widget.AppCompat.RatingBar.Small"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

I have a gradle project and when my build.gradle dependencies section looks like this:

dependencies {
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.8.1'

    testImplementation group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
    testImplementation 'junit:junit:4.12'
//    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.23.4'

    compileOnly 'org.projectlombok:lombok:1.18.4'
    apt 'org.projectlombok:lombok:1.18.4'
}

it leads to this exception:

java.lang.NoSuchMethodError: org.hamcrest.Matcher.describeMismatch(Ljava/lang/Object;Lorg/hamcrest/Description;)V

    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:18)
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)

to fix this issue, I've substituted "mockito-all" with "mockito-core".

dependencies {
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.8.1'

//    testImplementation group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
    testImplementation 'junit:junit:4.12'
    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.23.4'

    compileOnly 'org.projectlombok:lombok:1.18.4'
    apt 'org.projectlombok:lombok:1.18.4'
}

The explanation between mockito-all and mockito-core can be found here: https://solidsoft.wordpress.com/2012/09/11/beyond-the-mockito-refcard-part-3-mockito-core-vs-mockito-all-in-mavengradle-based-projects/

mockito-all.jar besides Mockito itself contains also (as of 1.9.5) two dependencies: Hamcrest and Objenesis (let’s omit repackaged ASM and CGLIB for a moment). The reason was to have everything what is needed inside an one JAR to just put it on a classpath. It can look strange, but please remember than Mockito development started in times when pure Ant (without dependency management) was the most popular build system for Java projects and the all external JARs required by a project (i.e. our project’s dependencies and their dependencies) had to be downloaded manually and specified in a build script.

On the other hand mockito-core.jar is just Mockito classes (also with repackaged ASM and CGLIB). When using it with Maven or Gradle required dependencies (Hamcrest and Objenesis) are managed by those tools (downloaded automatically and put on a test classpath). It allows to override used versions (for example if our projects uses never, but backward compatible version), but what is more important those dependencies are not hidden inside mockito-all.jar what allows to detected possible version incompatibility with dependency analyze tools. This is much better solution when dependency managed tool is used in a project.

Create two threads, one display odd & other even numbers

The Question should be: Print Odd-Even Numbers simultaneously Using Threads

public class EvenOdd1 {
        static boolean flag = true;
        public static void main(String[] args) {
            Runnable odd = () -> {
                for (int i = 1; i <= 10;) {
                    if (EvenOddPrinter.flag) {
                        System.out.println(Thread.currentThread().getName() + " " + i);
                        i += 2;
                        EvenOddPrinter.flag = !EvenOddPrinter.flag;
                    }//if
                }//for
            };

            Runnable even = () -> {
                for (int i = 2; i <= 10;) {
                    if (!EvenOddPrinter.flag) {
                        System.out.println(Thread.currentThread().getName() + " " + i);
                        i += 2;
                        EvenOddPrinter.flag = !EvenOddPrinter.flag;
                    }
                }
            };

            Thread t1 = new Thread(odd, "Odd");
            Thread t2 = new Thread(even, "Even");
            t1.start();
            t2.start();
        }
    }
/*The output => 
Odd 1
Even 2
Odd 3
Even 4
Odd 5
Even 6
Odd 7
Even 8
Odd 9
Even 10
*/

File upload from <input type="file">

just try (onclick)="this.value = null"

in your html page add onclick method to remove previous value so user can select same file again.

Execute the setInterval function without delay the first time

You could wrap setInterval() in a function that provides that behavior:

function instantGratification( fn, delay ) {
    fn();
    setInterval( fn, delay );
}

...then use it like this:

instantGratification( function() {
    console.log( 'invoked' );
}, 3000);

Regex: ignore case sensitivity

Just for the sake of completeness I wanted to add the solution for regular expressions in C++ with Unicode:

std::tr1::wregex pattern(szPattern, std::tr1::regex_constants::icase);

if (std::tr1::regex_match(szString, pattern))
{
...
}

How to use the pass statement?

Honestly, I think the official Python docs describe it quite well and provide some examples:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:

>>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ...

This is commonly used for creating minimal classes:

>>> class MyEmptyClass: ... pass ...

Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:

>>> def initlog(*args): ... pass # Remember to implement this! ...

Check if file exists and whether it contains a specific string

if test -e "$file_name";then
 ...
fi

if grep -q "poet" $file_name; then
  ..
fi

How do I set up a simple delegate to communicate between two view controllers?

Simple example...

Let's say the child view controller has a UISlider and we want to pass the value of the slider back to the parent via a delegate.

In the child view controller's header file, declare the delegate type and its methods:

ChildViewController.h

#import <UIKit/UIKit.h>

// 1. Forward declaration of ChildViewControllerDelegate - this just declares
// that a ChildViewControllerDelegate type exists so that we can use it
// later.
@protocol ChildViewControllerDelegate;

// 2. Declaration of the view controller class, as usual
@interface ChildViewController : UIViewController

// Delegate properties should always be weak references
// See http://stackoverflow.com/a/4796131/263871 for the rationale
// (Tip: If you're not using ARC, use `assign` instead of `weak`)
@property (nonatomic, weak) id<ChildViewControllerDelegate> delegate;

// A simple IBAction method that I'll associate with a close button in
// the UI. We'll call the delegate's childViewController:didChooseValue: 
// method inside this handler.
- (IBAction)handleCloseButton:(id)sender;

@end

// 3. Definition of the delegate's interface
@protocol ChildViewControllerDelegate <NSObject>

- (void)childViewController:(ChildViewController*)viewController 
             didChooseValue:(CGFloat)value;

@end

In the child view controller's implementation, call the delegate methods as required.

ChildViewController.m

#import "ChildViewController.h"

@implementation ChildViewController

- (void)handleCloseButton:(id)sender {
    // Xcode will complain if we access a weak property more than 
    // once here, since it could in theory be nilled between accesses
    // leading to unpredictable results. So we'll start by taking
    // a local, strong reference to the delegate.
    id<ChildViewControllerDelegate> strongDelegate = self.delegate;

    // Our delegate method is optional, so we should 
    // check that the delegate implements it
    if ([strongDelegate respondsToSelector:@selector(childViewController:didChooseValue:)]) {
        [strongDelegate childViewController:self didChooseValue:self.slider.value];
    }
}

@end

In the parent view controller's header file, declare that it implements the ChildViewControllerDelegate protocol.

RootViewController.h

#import <UIKit/UIKit.h>
#import "ChildViewController.h"

@interface RootViewController : UITableViewController <ChildViewControllerDelegate>

@end

In the parent view controller's implementation, implement the delegate methods appropriately.

RootViewController.m

#import "RootViewController.h"

@implementation RootViewController

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ChildViewController *detailViewController = [[ChildViewController alloc] init];
    // Assign self as the delegate for the child view controller
    detailViewController.delegate = self;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

// Implement the delegate methods for ChildViewControllerDelegate
- (void)childViewController:(ChildViewController *)viewController didChooseValue:(CGFloat)value {

    // Do something with value...

    // ...then dismiss the child view controller
    [self.navigationController popViewControllerAnimated:YES];
}

@end

Hope this helps!

nvarchar(max) vs NText

nvarchar(max) is what you want to be using. The biggest advantage is that you can use all the T-SQL string functions on this data type. This is not possible with ntext. I'm not aware of any real disadvantages.

How to convert 1 to true or 0 to false upon model fetch

Here's another option that's longer but may be more readable:

Boolean(Number("0")); // false
Boolean(Number("1")); // true

How do I install g++ for Fedora?

I had the same problem. At least I could solve it with this:

sudo yum install gcc gcc-c++

Hope it solves your problem too.

How to write LaTeX in IPython Notebook?

Use $$ if you want your math to appear in a single line, e.g.,

$$a = b + c$$ (line break after the equation)

If you don't need a line break after the math, use single dollar sign $, e.g.,

$a = b + c$   (no line break after the equation)

filemtime "warning stat failed for"

in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().

$filedate = date_create(date("Y-m-d", filectime($file)));

becomes

$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));

that worked for me.

Complete snippet for deleting files by number of days:

$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
    $extension      = substr($file, -3, 3); 
    if ($extension == 'jpg') // in case you only want specific files deleted
    {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        if ($days->days > 1) 
        { 
            unlink($directory.$file);
        }
    } 
}

JQuery: dynamic height() with window resize()

I feel like there should be a no javascript solution, but how is this?

http://jsfiddle.net/NfmX3/2/

$(window).resize(function() {
    $('#content').height($(window).height() - 46);
});

$(window).trigger('resize');

How to change status bar color to match app in Lollipop? [Android]

Another way to set the status bar color is through the style.xml.

To do that, create a style.xml file under res/values-v21 folder with this content:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="android:Theme.Material">
        <!--   darker variant for the status bar and contextual app bars -->
        <item name="android:colorPrimaryDark">@color/blue_dark</item>
    </style>
</resources>

Edit: as pointed out in comments, when using AppCompat the code is different. In file res/values/style.xml use instead:

<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">   
    <!-- Set AppCompat’s color theming attrs -->
    <item name="colorPrimary">@color/my_awesome_red</item>
    <item name="colorPrimaryDark">@color/my_awesome_darker_red</item>
    <!-- Other attributes -->
</style>

Python map object is not subscriptable

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)

Spring get current ApplicationContext

Simply inject it..

@Autowired
private ApplicationContext appContext;

or implement this interface: ApplicationContextAware

Google Chromecast sender error if Chromecast extension is not installed or using incognito

How about filtering these errors ?

With the regex filter bellow, we can dismiss cast_sender.js errors :

^((?!cast_sender).)*$

Do not forget to check Regex box.

enter image description here

Another quick solution is to "Hide network messages".

enter image description here

Java - Getting Data from MySQL database

This should work, I think...

ResultSet results = st.executeQuery(sql);

if(results.next()) { //there is a row
 int id = results.getInt(1); //ID if its 1st column
 String str1 = results.getString(2);
 ...
}

sscanf in Python

You can split on a range of characters using the re module.

>>> import re
>>> r = re.compile('[ \t\n\r:]+')
>>> r.split("abc:def  ghi")
['abc', 'def', 'ghi']

download csv file from web api in angular js

None of those worked for me in Chrome 42...

Instead my directive now uses this link function (base64 made it work):

  link: function(scope, element, attrs) {
    var downloadFile = function downloadFile() {
      var filename = scope.getFilename();
      var link = angular.element('<a/>');
      link.attr({
        href: 'data:attachment/csv;base64,' + encodeURI($window.btoa(scope.csv)),
        target: '_blank',
        download: filename
      })[0].click();
      $timeout(function(){
        link.remove();
      }, 50);
    };

    element.bind('click', function(e) {
      scope.buildCSV().then(function(csv) {
        downloadFile();
      });
      scope.$apply();
    });
  }

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

Reading CSV files using C#

I use this here:

http://www.codeproject.com/KB/database/GenericParser.aspx

Last time I was looking for something like this I found it as an answer to this question.

JavaScript isset() equivalent

window.isset = function(v_var) {
    if(typeof(v_var) == 'number'){ if(isNaN(v_var)){ return false; }}
    if(typeof(v_var) == 'undefined' || v_var === null){ return false;   } else { return true; }
};

plus Tests:

https://gist.github.com/daylik/24acc318b6abdcdd63b46607513ae073

Position absolute and overflow hidden

An absolutely positioned element is actually positioned regarding a relative parent, or the nearest found relative parent. So the element with overflow: hidden should be between relative and absolute positioned elements:

<div class="relative-parent">
  <div class="hiding-parent">
    <div class="child"></div>
  </div>
</div>

.relative-parent {
  position:relative;
}
.hiding-parent {
  overflow:hidden;
}
.child {
  position:absolute; 
}

Java: Multiple class declarations in one file

No. You can't. But it is very possible in Scala:

class Foo {val bar = "a"}
class Bar {val foo = "b"}

Convert utf8-characters to iso-88591 and back in PHP

Have a look at iconv() or mb_convert_encoding(). Just by the way: why don't utf8_encode() and utf8_decode() work for you?

utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

utf8_encode — Encodes an ISO-8859-1 string to UTF-8

So essentially

$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded
$iso88591_1 = utf8_decode($utf8);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8);
$iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');

$iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded
$utf8_1 = utf8_encode($iso88591);
$utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591);
$utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');

all should do the same - with utf8_en/decode() requiring no special extension, mb_convert_encoding() requiring ext/mbstring and iconv() requiring ext/iconv.

How to remove all click event handlers using jQuery?

$('#saveBtn').off('click').on('click',function(){
   saveQuestion(id)
});

Use jquery's off and on

How do I test a website using XAMPP?

Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80> and </VirtualHost>

After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs/www"
    ServerName example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Be sure to create the www folder under htdocs. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html or index.php file and place in the www folder, then go to your browser and test it out localhost/ ... Note: if your server is serving php files over html then remember to add localhost/index.html if the html file is the one you choose to use for this test.

Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs"
    ServerName htdocs.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

How to write LDAP query to test if user is member of a group?

You should be able to create a query with this filter here:

(&(objectClass=user)(sAMAccountName=yourUserName)
  (memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))

and when you run that against your LDAP server, if you get a result, your user "yourUserName" is indeed a member of the group "CN=YourGroup,OU=Users,DC=YourDomain,DC=com

Try and see if this works!

If you use C# / VB.Net and System.DirectoryServices, this snippet should do the trick:

DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=yourcompany,dc=com");

DirectorySearcher srch = new DirectorySearcher(rootEntry);
srch.SearchScope = SearchScope.Subtree;

srch.Filter = "(&(objectClass=user)(sAMAccountName=yourusername)(memberOf=CN=yourgroup,OU=yourOU,DC=yourcompany,DC=com))";

SearchResultCollection res = srch.FindAll();

if(res == null || res.Count <= 0) {
    Console.WriteLine("This user is *NOT* member of that group");
} else {
    Console.WriteLine("This user is INDEED a member of that group");
}

Word of caution: this will only test for immediate group memberships, and it will not test for membership in what is called the "primary group" (usually "cn=Users") in your domain. It does not handle nested memberships, e.g. User A is member of Group A which is member of Group B - that fact that User A is really a member of Group B as well doesn't get reflected here.

Marc

SOAP request to WebService with java

A SOAP request is an XML file consisting of the parameters you are sending to the server.

The SOAP response is equally an XML file, but now with everything the service wants to give you.

Basically the WSDL is a XML file that explains the structure of those two XML.


To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             http://www.webservicex.net/uszip.asmx?op=GetInfoByCity


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:GetInfoByCity>
                        <myNamespace:USCity>New York</myNamespace:USCity>
                    </myNamespace:GetInfoByCity>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

UPDATE multiple tables in MySQL using LEFT JOIN

The same can be applied to a scenario where the data has been normalized, but now you want a table to have values found in a third table. The following will allow you to update a table with information from a third table that is liked by a second table.

UPDATE t1
LEFT JOIN
 t2
ON 
 t2.some_id = t1.some_id
LEFT JOIN
 t3 
ON
 t2.t3_id = t3.id
SET 
 t1.new_column = t3.column;

This would be useful in a case where you had users and groups, and you wanted a user to be able to add their own variation of the group name, so originally you would want to import the existing group names into the field where the user is going to be able to modify it.

How to find out mySQL server ip address from phpmyadmin

select * from SHOW VARIABLES WHERE Variable_name = 'hostname';

Delete statement in SQL is very slow

It's possible that other tables have FK constraint to your [table]. So the DB needs to check these tables to maintain the referential integrity. Even if you have all needed indexes corresponding these FKs, check their amount.

I had the situation when NHibernate incorrectly created duplicated FKs on the same columns, but with different names (which is allowed by SQL Server). It has drastically slowed down running of the DELETE statement.

javascript regex - look behind alternative?

Let's suppose you want to find all int not preceded by unsigned:

With support for negative look-behind:

(?<!unsigned )int

Without support for negative look-behind:

((?!unsigned ).{9}|^.{0,8})int

Basically idea is to grab n preceding characters and exclude match with negative look-ahead, but also match the cases where there's no preceeding n characters. (where n is length of look-behind).

So the regex in question:

(?<!filename)\.js$

would translate to:

((?!filename).{8}|^.{0,7})\.js$

You might need to play with capturing groups to find exact spot of the string that interests you or you want't to replace specific part with something else.

Recursively find files with a specific extension

This q/a shows how to use find with regular expression: How to use regex with find command?

Pattern could be something like

'^Robert\\.\\(h|cgg\\)$'

jQuery remove all list items from an unordered list

If you have multiple ul and want to empty specific ul then use id eg:

<ul id="randomName">
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>


<script>
  $('#randomName').empty();
</script>

_x000D_
_x000D_
$('input').click(function() {_x000D_
  $('#randomName').empty()_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<ul id="randomName">_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
</ul>_x000D_
<input type="button" value="click me" />
_x000D_
_x000D_
_x000D_

Steps to send a https request to a rest service in Node js

just use the core https module with the https.request function. Example for a POST request (GET would be similar):

var https = require('https');

var options = {
  host: 'www.google.com',
  port: 443,
  path: '/upload',
  method: 'POST'
};

var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

How to uninstall a Windows Service when there is no executable for it left on the system?

Create a copy of executables of same service and paste it on the same path of the existing service and then uninstall.

c++ exception : throwing std::string

In addition to probably throwing something derived from std::exception you should throw anonymous temporaries and catch by reference:

void Foo::Bar(){
  if(!QueryPerformanceTimer(&m_baz)){
    throw std::string("it's the end of the world!");
  }
}

void Foo:Caller(){
  try{
    this->Bar();// should throw
  }catch(std::string& caught){ // not quite sure the syntax is ok here...
    std::cout<<"Got "<<caught<<std::endl;
  }
}
  • You should throw anonymous temporaries so the compiler deals with the object lifetime of whatever you're throwing - if you throw something new-ed off the heap, someone else needs to free the thing.
  • You should catch references to prevent object slicing

.

See Meyer's "Effective C++ - 3rd edition" for details or visit https://www.securecoding.cert.org/.../ERR02-A.+Throw+anonymous+temporaries+and+catch+by+reference

Regex pattern for checking if a string starts with a certain substring?

The StartsWith method will be faster, as there is no overhead of interpreting a regular expression, but here is how you do it:

if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...

The ^ mathes the start of the string. You can put any protocols between the parentheses separated by | characters.

edit:

Another approach that is much faster, is to get the start of the string and use in a switch. The switch sets up a hash table with the strings, so it's faster than comparing all the strings:

int index = theString.IndexOf(':');
if (index != -1) {
  switch (theString.Substring(0, index)) {
    case "mailto":
    case "ftp":
    case "joe":
      // do something
      break;
  }
}

ios app maximum memory budget

I think you've answered your own question: try not to go beyond the 70 Mb limit, however it really depends on many things: what iOS version you're using (not SDK), how many applications running in background, what exact memory you're using etc.

Just avoid the instant memory splashes (e.g. you're using 40 Mb of RAM, and then allocating 80 Mb's more for some short computation). In this case iOS would kill your application immediately.

You should also consider lazy loading of assets (load them only when you really need and not beforehand).

How to convert java.sql.timestamp to LocalDate (java8) java.time?

The accepted answer is not ideal, so I decided to add my 2 cents

timeStamp.toLocalDateTime().toLocalDate();

is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.

The good solution is

timestamp.toInstant().atZone(zoneId).toLocalDate()

Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC

The general approach should be

  1. Break free to the new java8 date classes using a class that is directly related, e.g. in our case java.time.Instant is directly related to java.sql.Timestamp, i.e. no timezone conversions are needed between them.
  2. Use the well-designed methods in this java8 class to do the right thing. In our case atZone(zoneId) made it explicit that we are doing a conversion and using a particular timezone for it.

Java logical operator short-circuiting

boolean a = (x < z) && (x == x);

This kind will short-circuit, meaning if (x < z) evaluates to false then the latter is not evaluated, a will be false, otherwise && will also evaluate (x == x).

& is a bitwise operator, but also a boolean AND operator which does not short-circuit.

You can test them by something as follows (see how many times the method is called in each case):

public static boolean getFalse() {
    System.out.println("Method");
    return false;
}

public static void main(String[] args) {
    if(getFalse() && getFalse()) { }        
    System.out.println("=============================");        
    if(getFalse() & getFalse()) { }
}

How do I access ViewBag from JS

<script type="text/javascript">
      $(document).ready(function() {
                showWarning('@ViewBag.Message');
      });

</script>

You can use ViewBag.PropertyName in javascript like this.

How to import keras from tf.keras in Tensorflow?

Update for everybody coming to check why tensorflow.keras is not visible in PyCharm.

Starting from TensorFlow 2.0, only PyCharm versions > 2019.3 are able to recognise tensorflow and keras inside tensorflow (tensorflow.keras) properly.

Also, it is recommended(by Francois Chollet) that everybody switches to tensorflow.keras in place of plain keras.

htaccess "order" Deny, Allow, Deny

In apache2, linux configuration

Require all granted

c# Image resizing to different size while preserving aspect ratio

Here's a less specific extension method that works with Image rather than doing the loading and saving for you. It also allows you to specify interpolation method and correctly renders edges when you use NearestNeighbour interpolation.

The image will be rendered within the bounds of the area you specify so you always know your output width and height. e.g:

Scaled within bounds

namespace YourApp
{
    #region Namespaces
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Drawing.Drawing2D;
    #endregion

    /// <summary>Generic helper functions related to graphics.</summary>
    public static class ImageExtensions
    {
        /// <summary>Resizes an image to a new width and height value.</summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="newWidth">The width of the new image.</param>
        /// <param name="newHeight">The height of the new image.</param>
        /// <param name="mode">Interpolation mode.</param>
        /// <param name="maintainAspectRatio">If true, the image is centered in the middle of the returned image, maintaining the aspect ratio of the original image.</param>
        /// <returns>The new image. The old image is unaffected.</returns>
        public static Image ResizeImage(this Image image, int newWidth, int newHeight, InterpolationMode mode = InterpolationMode.Default, bool maintainAspectRatio = false)
        {
            Bitmap output = new Bitmap(newWidth, newHeight, image.PixelFormat);

            using (Graphics gfx = Graphics.FromImage(output))
            {
                gfx.Clear(Color.FromArgb(0, 0, 0, 0));
                gfx.InterpolationMode = mode;
                if (mode == InterpolationMode.NearestNeighbor)
                {
                    gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    gfx.SmoothingMode = SmoothingMode.HighQuality;
                }

                double ratioW = (double)newWidth / (double)image.Width;
                double ratioH = (double)newHeight / (double)image.Height;
                double ratio = ratioW < ratioH ? ratioW : ratioH;
                int insideWidth = (int)(image.Width * ratio);
                int insideHeight = (int)(image.Height * ratio);

                gfx.DrawImage(image, new Rectangle((newWidth / 2) - (insideWidth / 2), (newHeight / 2) - (insideHeight / 2), insideWidth, insideHeight));
            }

            return output;
        }
    }
}

Is it possible to read from a InputStream with a timeout?

If your InputStream is backed by a Socket, you can set a Socket timeout (in milliseconds) using setSoTimeout. If the read() call doesn't unblock within the timeout specified, it will throw a SocketTimeoutException.

Just make sure that you call setSoTimeout on the Socket before making the read() call.

How to align the text middle of BUTTON

Sometime it is fixed by the Padding .. if you can play with that, then, it should fix your problem

<style type=text/css>

YourbuttonByID {Padding: 20px 80px; "for example" padding-left:50px; 
 padding-right:30px "to fix the text in the middle 
 without interfering with the text itself"}

</style>

It worked for me

How do I reformat HTML code using Sublime Text 2?

The only package I've been able to find is Tag.

You can install it using the package control. https://sublime.wbond.net

After installing package control. Go to package control (Preferences -> Package Control) then type install, hit enter. Then type tag and hit enter.

After installing Tag, highlight the text and press the shortcut Ctrl+Alt+F.

Set proxy through windows command line including login parameters

cmd

Tunnel all your internet traffic through a socks proxy:

netsh winhttp set proxy proxy-server="socks=localhost:9090" bypass-list="localhost"

View the current proxy settings:

netsh winhttp show proxy

Clear all proxy settings:

netsh winhttp reset proxy

How to use and style new AlertDialog from appCompat 22.1 and above

If you're like me you just want to modify some of the colors in AppCompat, and the only color you need to uniquely change in the dialog is the background. Then all you need to do is set a color for colorBackgroundFloating.

Here's my basic theme that simply modifies some colors with no nested themes:

    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/theme_colorPrimary</item>
        <item name="colorPrimaryDark">@color/theme_colorPrimaryDark</item>
        <item name="colorAccent">@color/theme_colorAccent</item>
        <item name="colorControlActivated">@color/theme_colorControlActivated</item>
        <item name="android:windowBackground">@color/theme_bg</item>
        <item name="colorBackgroundFloating">@color/theme_dialog_bg</item><!-- Dialog background color -->
        <item name="colorButtonNormal">@color/theme_colorPrimary</item>
        <item name="colorControlHighlight">@color/theme_colorAccent</item>
    </style>

select records from postgres where timestamp is in certain range

Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:

create index arrival_year on reservations ( extract(year from arrival) );

That will open PostgreSQL with the possibility to use an index for

select * 
FROM reservations 
WHERE extract(year from arrival) = 2012;

Note that the expression in the index must be exactly the same expression as used in the where clause to make this work.

What JSON library to use in Scala?

Here is a basic implementation of writing and then reading json file using json4s.

import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.JsonDSL._
import java.io._
import scala.io.Source


object MyObject { def main(args: Array[String]) {

  val myMap = Map("a" -> List(3,4), "b" -> List(7,8))

  // writing a file 
  val jsonString = pretty(render(myMap))

  val pw = new PrintWriter(new File("my_json.json"))
  pw.write(jsonString)
  pw.close()

  // reading a file 
  val myString = Source.fromFile("my_json.json").mkString
  println(myString)

  val myJSON = parse(myString)

  println(myJSON)

  // Converting from JOjbect to plain object
  implicit val formats = DefaultFormats
  val myOldMap = myJSON.extract[Map[String, List[Int]]]

  println(myOldMap)
 }
}

What does "fatal: bad revision" mean?

If you want to delete any commit then you might need to use git rebase command

git rebase -i HEAD~2

it will show you last 2 commit messages, if you delete the commit message and save that file deleted commit will automatically disappear...

Remove carriage return in Unix

Removing \r on any UNIX® system:

Most existing solutions in this question are GNU-specific, and wouldn't work on OS X or BSD; the solutions below should work on many more UNIX systems, and in any shell, from tcsh to sh, yet still work even on GNU/Linux, too.

Tested on OS X, OpenBSD and NetBSD in tcsh, and on Debian GNU/Linux in bash.


With sed:

In tcsh on an OS X, the following sed snippet could be used together with printf, as neither sed nor echo handle \r in the special way like the GNU does:

sed `printf 's/\r$//g'` input > output

With tr:

Another option is tr:

tr -d '\r' < input > output

Difference between sed and tr:

It would appear that tr preserves a lack of a trailing newline from the input file, whereas sed on OS X and NetBSD (but not on OpenBSD or GNU/Linux) inserts a trailing newline at the very end of the file even if the input is missing any trailing \r or \n at the very end of the file.


Testing:

Here's some sample testing that could be used to ensure this works on your system, using printf and hexdump -C; alternatively, od -c could also be used if your system is missing hexdump:

% printf 'a\r\nb\r\nc' | hexdump -C
00000000  61 0d 0a 62 0d 0a 63                              |a..b..c|
00000007
% printf 'a\r\nb\r\nc' | ( sed `printf 's/\r$//g'` /dev/stdin > /dev/stdout ) | hexdump -C
00000000  61 0a 62 0a 63 0a                                 |a.b.c.|
00000006
% printf 'a\r\nb\r\nc' | ( tr -d '\r' < /dev/stdin > /dev/stdout ) | hexdump -C
00000000  61 0a 62 0a 63                                    |a.b.c|
00000005
% 

Convert Bitmap to File

Most of the answers are too lengthy or too short not fulfilling the purpose. For those how are looking for Java or Kotlin code to Convert bitmap to File Object. Here is the detailed article I have written on the topic. Convert Bitmap to File in Android

public static File bitmapToFile(Context context,Bitmap bitmap, String fileNameToSave) { // File name like "image.png"
        //create a file to write bitmap data
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory() + File.separator + fileNameToSave);
            file.createNewFile();

//Convert bitmap to byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos); // YOU can also save it in JPEG
            byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bitmapdata);
            fos.flush();
            fos.close();
            return file;
        }catch (Exception e){
            e.printStackTrace();
            return file; // it will return null
        }
    }

Auto-scaling input[type=text] to width of value?

A SIMPLE BUT PIXEL PERFECT SOLUTION

I have seen several ways to do this but calculating the width of fonts isn't always 100% accurate, it's just an estimate.

I managed to create a pixel perfect way of adjusting the input width by having a hidden placeholder to measure from.


jQuery (Recommended)

_x000D_
_x000D_
$(function(){_x000D_
  $('#hide').text($('#txt').val());_x000D_
  $('#txt').width($('#hide').width());_x000D_
}).on('input', function () {_x000D_
  $('#hide').text($('#txt').val());_x000D_
  $('#txt').width($('#hide').width());_x000D_
});
_x000D_
body,_x000D_
#txt,_x000D_
#hide{_x000D_
  font:inherit;_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
}_x000D_
#txt{_x000D_
  border:none;_x000D_
  color:#888;_x000D_
  min-width:10px;_x000D_
}_x000D_
#hide{_x000D_
  display:none;_x000D_
  white-space:pre;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>Lorem ipsum _x000D_
  <span id="hide"></span><input id="txt" type="text" value="type here ...">_x000D_
  egestas arcu._x000D_
</p>
_x000D_
_x000D_
_x000D_


Pure JavaScript

I was unable to determine how jQuery calculates the width of hidden elements so a slight tweak to css was required to accomodate this solution.

_x000D_
_x000D_
var hide = document.getElementById('hide');_x000D_
var txt = document.getElementById('txt');_x000D_
resize();_x000D_
txt.addEventListener("input", resize);_x000D_
_x000D_
function resize() {_x000D_
  hide.textContent = txt.value;_x000D_
  txt.style.width = hide.offsetWidth + "px";_x000D_
}
_x000D_
body,_x000D_
#txt,_x000D_
#hide {_x000D_
  font: inherit;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#txt {_x000D_
  border: none;_x000D_
  color: #888;_x000D_
  min-width: 10px;_x000D_
}_x000D_
_x000D_
#hide {_x000D_
  position: absolute;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
  white-space: pre;_x000D_
}
_x000D_
<p>Lorem ipsum_x000D_
  <span id="hide"></span><input id="txt" type="text" value="type here ..."> egestas arcu._x000D_
</p>
_x000D_
_x000D_
_x000D_

Where can I find my Facebook application id and secret key?

Just simply click on your app name and look on your right, you app id should be there

For your app secret, u have to click show.

enter image description here

Hope that helps !

Finding Number of Cores in Java

int cores = Runtime.getRuntime().availableProcessors();

If cores is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.

Number of times a particular character appears in a string

You may do this completely in-line by replacing the desired character with an empty string, calling LENGTH function and substracting from the original string's length.

SELECT 
  CustomerName, 
  LENGTH(CustomerName) -
  LENGTH(REPLACE(CustomerName, ' ', '')) AS NumberOfSpaces
FROM Customers;

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

JavaScript module pattern with example

I thought i'd expand on the above answer by talking about how you'd fit modules together into an application. I'd read about this in the doug crockford book but being new to javascript it was all still a bit mysterious.

I come from a c# background so have added some terminology I find useful from there.

Html

You'll have some kindof top level html file. It helps to think of this as your project file. Every javascript file you add to the project wants to go into this, unfortunately you dont get tool support for this (I'm using IDEA).

You need add files to the project with script tags like this:

        <script type="text/javascript" src="app/native/MasterFile.js" /></script>
        <script type="text/javascript" src="app/native/SomeComponent.js" /></script>

It appears collapsing the tags causes things to fail - whilst it looks like xml it's really something with crazier rules!

Namespace file

MasterFile.js

myAppNamespace = {};

that's it. This is just for adding a single global variable for the rest of our code to live in. You could also declare nested namespaces here (or in their own files).

Module(s)

SomeComponent.js

myAppNamespace.messageCounter= (function(){

    var privateState = 0;

    var incrementCount = function () {
        privateState += 1;
    };

    return function (message) {
        incrementCount();
        //TODO something with the message! 
    }
})();

What we're doing here is assigning a message counter function to a variable in our application. It's a function which returns a function which we immediately execute.

Concepts

I think it helps to think of the top line in SomeComponent as being the namespace where you are declaring something. The only caveat to this is all your namespaces need to appear in some other file first - they are just objects rooted by our application variable.

I've only taken minor steps with this at the moment (i'm refactoring some normal javascript out of an extjs app so I can test it) but it seems quite nice as you can define little functional units whilst avoiding the quagmire of 'this'.

You can also use this style to define constructors by returning a function which returns an object with a collection of functions and not calling it immediately.

Add a link to an image in a css style sheet

You can not do that...

via css the URL you put on the background-image is just for the image.

Via HTML you have to add the href for your hyperlink in this way:

<a href="http://home.com" id="logo">Your logo</a>

With text-indent and some other css you can adjust your a element to show just the image and clicking on it you will go to your link.


EDIT:

I'm here again to show you and explain why my solution is much better:

<a href="http://home.com" id="logo">Your logo name</a>

This block of HTML is SEO friendly because you have some text inside your link!

How to style it with css:

#logo {
  background-image: url(images/logo.png);
  display: block;
  margin: 0 auto;
  text-indent: -9999px;
  width: 981px;
  height: 180px;
}

Then if you don't care about SEO good to choose the other answer.

How to do while loops with multiple conditions

Have you noticed that in the code you posted, condition2 is never set to False? This way, your loop body is never executed.

Also, note that in Python, not condition is preferred to condition == False; likewise, condition is preferred to condition == True.

Two versions of python on linux. how to make 2.7 the default

Verify current version of python by:

$ python --version

then check python is symbolic link to which file.

  $ ll /usr/bin/python

Output Ex:

 lrwxrwxrwx 1 root root 9 Jun 16  2014 /usr/bin/python -> python2.7*

Check other available versions of python:

$ ls /usr/bin/python*

Output Ex:

/usr/bin/python     /usr/bin/python2.7-config  /usr/bin/python3.4         /usr/bin/python3.4m-config  /usr/bin/python3.6m         /usr/bin/python3m
/usr/bin/python2    /usr/bin/python2-config    /usr/bin/python3.4-config  /usr/bin/python3.6          /usr/bin/python3.6m-config  /usr/bin/python3m-config
/usr/bin/python2.7  /usr/bin/python3           /usr/bin/python3.4m        /usr/bin/python3.6-config   /usr/bin/python3-config     /usr/bin/python-config

If want to change current version of python to 3.6 version edit file ~/.bashrc:

vim ~/.bashrc

add below line in the end of file and save:

alias python=/usr/local/bin/python3.6

To install pip for python 3.6

$ sudo apt-get install python3.6 python3.6-dev
$ sudo curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python3.6
$ sudo easy_install pip

On Success, check current version of pip:

$ pip3 -V

Output Ex:

pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.6)

Converting a PDF to PNG

For a PDF that ImageMagick was giving inaccurate colors I found that GraphicsMagick did a better job:

$ gm convert -quality 100 -thumbnail x300 -flatten journal.pdf\[0\] cover.jpg

Using Bootstrap Tooltip with AngularJS

In order to get the tooltips to work in the first place, you have to initialize them in your code. Ignoring AngularJS for a second, this is how you would get the tooltips to work in jQuery:

$(document).ready(function(){
    $('[data-toggle=tooltip]').hover(function(){
        // on mouseenter
        $(this).tooltip('show');
    }, function(){
        // on mouseleave
        $(this).tooltip('hide');
    });
});

This will also work in an AngularJS app so long as it's not content rendered by Angular (eg: ng-repeat). In that case, you need to write a directive to handle this. Here's a simple directive that worked for me:

app.directive('tooltip', function(){
    return {
        restrict: 'A',
        link: function(scope, element, attrs){
            element.hover(function(){
                // on mouseenter
                element.tooltip('show');
            }, function(){
                // on mouseleave
                element.tooltip('hide');
            });
        }
    };
});

Then all you have to do is include the "tooltip" attribute on the element you want the tooltip to appear on:

<a href="#0" title="My Tooltip!" data-toggle="tooltip" data-placement="top" tooltip>My Tooltip Link</a>

Hope that helps!

Time part of a DateTime Field in SQL

In SQL Server if you need only the hh:mi, you can use:

DECLARE @datetime datetime

SELECT @datetime = GETDATE()

SELECT RIGHT('0'+CAST(DATEPART(hour, @datetime) as varchar(2)),2) + ':' +
       RIGHT('0'+CAST(DATEPART(minute, @datetime)as varchar(2)),2)

How to find the size of an int[]?

int arr1[] = {8, 15, 3, 7};
int n = sizeof(arr1)/sizeof(arr1[0]);

So basically sizeof(arr1) is giving the size of the object being pointed to, each element maybe occupying multiple bits so dividing by the number of bits per element (sizeof(arr1[0]) gives you the actual number of elements you're looking for, i.e. 4 in my example.

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)