Programs & Examples On #Pellet

The Pellet reasoner is a Java based reasoning software that performs entailment tasks for OWL ontologies. This reasoner can be used with multiple frameworks such as Apache Jena, OWL-API and Protégé.

Password Strength Meter

Update: created a js fiddle here to see it live: http://jsfiddle.net/HFMvX/

I went through tons of google searches and didn't find anything satisfying. i like how passpack have done it so essentially reverse-engineered their approach, here we go:

function scorePassword(pass) {
    var score = 0;
    if (!pass)
        return score;

    // award every unique letter until 5 repetitions
    var letters = new Object();
    for (var i=0; i<pass.length; i++) {
        letters[pass[i]] = (letters[pass[i]] || 0) + 1;
        score += 5.0 / letters[pass[i]];
    }

    // bonus points for mixing it up
    var variations = {
        digits: /\d/.test(pass),
        lower: /[a-z]/.test(pass),
        upper: /[A-Z]/.test(pass),
        nonWords: /\W/.test(pass),
    }

    var variationCount = 0;
    for (var check in variations) {
        variationCount += (variations[check] == true) ? 1 : 0;
    }
    score += (variationCount - 1) * 10;

    return parseInt(score);
}

Good passwords start to score around 60 or so, here's function to translate that in words:

function checkPassStrength(pass) {
    var score = scorePassword(pass);
    if (score > 80)
        return "strong";
    if (score > 60)
        return "good";
    if (score >= 30)
        return "weak";

    return "";
}

you might want to tune this a bit but i found it working for me nicely

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

What are you doing: (I am using bytes instead of in for better reading)

You start with int *ap and so on, so your (your computers) memory looks like this:

-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory  --------
100: something          <- here is *ap
101: 41                 <- here starts a[] 
102: 42
103: 43
104: 44
105: 45
106: something          <- here waits x

lets take a look waht happens when (print short cut for ...print("$d", ...)

print a[0]  -> 41   //no surprise
print a     -> 101  // because a points to the start of the array
print *a    -> 41   // again the first element of array
print a+1   -> guess? 102
print *(a+1)    -> whats behind 102? 42 (we all love this number)

and so on, so a[0] is the same as *a, a[1] = *(a+1), ....

a[n] just reads easier.

now, what happens at line 9?

ap=a[4] // we know a[4]=*(a+4) somehow *105 ==>  45 
// warning! converting int to pointer!
-------------- your memory  --------
100: 45         <- here is *ap now 45

x = *ap;   // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang!      // dont touch neighbours garden

So the "warning" is not just a warning it's a severe error.

Finding the second highest number in array

If the first element which second_highest is set to initially is already the highest element, then it should be reassigned to a new element when the next element is found. That is, it's being initialized to 98, and should be set to 56. But, 56 isn't higher than 98, so it won't be set unless you do the check.

If the highest number appears twice, this will result in the second highest value as opposed to the second element that you would find if you sorted the array.

Parsing JSON giving "unexpected token o" error

The source of your error, however, is that you need to place the full JSON string in quotes. The following will fix your sample:

<!doctype HTML>
<html>
    <head>
    </head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
            var ques_list = JSON.parse(cur_ques_details);
            document.write(ques_list['ques_title']);
        </script>
    </body>
</html>

As the other respondents have mentioned, the object is already parsed into a JS object so you don't need to parse it. To demonstrate how to accomplish the same thing without parsing, you can do the following:

<!doctype HTML>
<html>
<head>
</head>
    <body>
        <script type="text/javascript">
            var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
            document.write(cur_ques_details.ques_title);
        </script>
    </body>
</html>

How to call a method defined in an AngularJS directive?

Assuming that the action button uses the same controller $scope as the directive, just define function updateMap on $scope inside the link function. Your controller can then call that function when the action button is clicked.

<div ng-controller="MyCtrl">
    <map></map>
    <button ng-click="updateMap()">call updateMap()</button>
</div>
app.directive('map', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function($scope, element, attrs) {
            $scope.updateMap = function() {
                alert('inside updateMap()');
            }
        }
    }
});

fiddle


As per @FlorianF's comment, if the directive uses an isolated scope, things are more complicated. Here's one way to make it work: add a set-fn attribute to the map directive which will register the directive function with the controller:

<map set-fn="setDirectiveFn(theDirFn)"></map>
<button ng-click="directiveFn()">call directive function</button>
scope: { setFn: '&' },
link: function(scope, element, attrs) {
    scope.updateMap = function() {
       alert('inside updateMap()');
    }
    scope.setFn({theDirFn: scope.updateMap});
}
function MyCtrl($scope) {
    $scope.setDirectiveFn = function(directiveFn) {
        $scope.directiveFn = directiveFn;
    };
}

fiddle

Difference between @click and v-on:click Vuejs

They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.

Source: official documentation.

Call a PHP function after onClick HTML event

 cell1.innerHTML="<?php echo $customerDESC; ?>";
 cell2.innerHTML="<?php echo $comm; ?>";
 cell3.innerHTML="<?php echo $expressFEE; ?>";
 cell4.innerHTML="<?php echo $totao_unit_price; ?>";

it is working like a charm, the javascript is inside a php while loop

How to trim white spaces of array values in php

simply you can use regex to trim all spaces or minify your array items

$array = array_map(function ($item) {
    return preg_replace('/\s+/', '', $item);
}, $array);

How to install Java SDK on CentOS?

Here is a detailed information on setting up Java and its paths on CentOS6.

Below steps are for the installation of latest Java version 8:

  1. Download java rpm package from Oracle site. (jdk-8-linux-x64.rpm)
  2. Install from the rpm. (rpm -Uvh jdk-8-linux-x64.rpm)
  3. Open /etc/profile, and set the java paths, save it.
  4. Check the java installation path, and java version, with the commands: which java, java -version

Now you can test the installation with a sample java program

C# getting the path of %AppData%

For ASP.NET, the Load User Profile setting needs to be set on the app pool but that's not enough. There is a hidden setting named setProfileEnvironment in \Windows\System32\inetsrv\Config\applicationHost.config, which for some reason is turned off by default, instead of on as described in the documentation. You can either change the default or set it on your app pool. All the methods on the Environment class will then return proper values.

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

What is "origin" in Git?

The best answer here:

https://www.git-tower.com/learn/git/glossary/origin

In Git, "origin" is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository's URL - and thereby makes referencing much easier.

Sending images using Http Post

I usually do this in the thread handling the json response:

try {
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.

Visual Studio 2015 Update 3 Offline Installer (ISO)

Its better to go through the Recommended Microsoft's Way to download Visual Studio 2015 Update 3 ISO (Community Edition).

The instructions below will help you to download any version of Visual Studio or even SQL Server etc provided by Microsoft in an easy to remember way. Though I recommend people using VS 2017 as there are not much big differences between 2015 and 2017.

Please follow the steps as mentioned below.

  1. Visit the standard URL www.visualstudio.com/downloads

  2. Scroll down and click on encircled below as shown in snapshot down Snapshot showing how to download older visual studio versions

  3. After that join Visual Studio Web Dev essentials for Free as shown below. Try loggin in with your microsoft account and see that if it works otherwise click on Joinenter image description here

  4. Click on Downloads ICON on the encircled as shown below. enter image description here

  5. Now Type Visual Studio Community in the Search Box as shown below in the snapshot enter image description here.
  6. From the drowdown select the DVD type and start downloading enter image description here

Transferring files over SSH

You need to scp something somewhere. You have scp ./styles/, so you're saying secure copy ./styles/, but not where to copy it to.

Generally, if you want to download, it will go:

# download: remote -> local
scp user@remote_host:remote_file local_file 

where local_file might actually be a directory to put the file you're copying in. To upload, it's the opposite:

# upload: local -> remote
scp local_file user@remote_host:remote_file

If you want to copy a whole directory, you will need -r. Think of scp as like cp, except you can specify a file with user@remote_host:file as well as just local files.

Edit: As noted in a comment, if the usernames on the local and remote hosts are the same, then the user can be omitted when specifying a remote file.

Removing "bullets" from unordered list <ul>

In your css file add following.

ul{
 list-style-type: none;
}

Using 'make' on OS X

There is now another way to install the gcc toolchain on OS X through the osx-gcc-installer this includes:

  • GCC
  • LLVM
  • Clang
  • Developer CLI Tools (purge, make, etc)
  • DevSDK (headers, etc)

The download is 282MB vs 3GB for Xcode.

sudo: npm: command not found

I had the same issue,the reason for it was npm package manager was not installed while installing node. This was caused because of the following mistake: In the installation process there is a step called "Custom Setup", here you have the option to choose one of the following: 1) Node.js runtime (This is selected by default). 2) npm package manager 3) Online documentation shortcuts. 4) Add to Path. If you proceed as it is npm package manager will not be installed and hence you will get the error.

Solution: Select npm package manager when you get these options. This worked for me.

Replace multiple characters in one replace call

Here is another version using String Prototype. Enjoy!

String.prototype.replaceAll = function(obj) {
    let finalString = '';
    let word = this;
    for (let each of word){
        for (const o in obj){
            const value = obj[o];
            if (each == o){
                each = value;
            }
        }
        finalString += each;
    }

    return finalString;
};

'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['auth_type'] = 'cookie';

should work.

From the manual:

auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.

How to get a value of an element by name instead of ID

To get the value, we can use multiple attributes, one of them being the name attribute. E.g

$("input[name='nameOfElement']").val();

We can also use other attributes to get values

HTML

<input type="text" id="demoText" demo="textValue" />

JS

$("[demo='textValue']").val();

How do I drop a MongoDB database from the command line?

In you command prompt, First connect to mongodb using following command:

mongo -h [host-name]:[port:number] -d [dbname] -u [username] -p [password]

you will be accessing db with <dbname>.

Run the following command to drop the whole database:

db.dropDatabase()

Creating a new dictionary in Python

d = dict()

or

d = {}

or

import types
d = types.DictType.__new__(types.DictType, (), {})

Pass table as parameter into sql server UDF

    create table Project (ProjectId int, Description varchar(50));
    insert into Project values (1, 'Chase tail, change directions');
    insert into Project values (2, 'ping-pong ball in clothes dryer');

    create table ProjectResource (ProjectId int, ResourceId int, Name varchar(15));
    insert into ProjectResource values (1, 1, 'Adam');
    insert into ProjectResource values (1, 2, 'Kerry');
    insert into ProjectResource values (1, 3, 'Tom');
    insert into ProjectResource values (2, 4, 'David');
    insert into ProjectResource values (2, 5, 'Jeff');


    SELECT *, 
      (SELECT Name + ' ' AS [text()] 
       FROM ProjectResource pr 
       WHERE pr.ProjectId = p.ProjectId 
       FOR XML PATH ('')) 
    AS ResourceList 
    FROM Project p

-- ProjectId    Description                        ResourceList
-- 1            Chase tail, change directions      Adam Kerry Tom 
-- 2            ping-pong ball in clothes dryer    David Jeff 

jQuery trigger event when click outside the element

The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:

$(".menuWrapper").click(function(e) {
  e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
  $(".menuWrapper").hide(); //click came from somewhere else
});

All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.

How to catch an Exception from a thread

You cannot do this, since it doesn't really make sense. If you hadn't called t.join() then you main thread could be anywhere in the code when the t thread throws an exception.

How to get string objects instead of Unicode from JSON?

With Python 3.6, sometimes I still run into this problem. For example, when getting response from a REST API and loading the response text to JSON, I still get the unicode strings. Found a simple solution using json.dumps().

response_message = json.loads(json.dumps(response.text))
print(response_message)

Batch file to split .csv file

I found this question while looking for a similar solution. I modified the answer that @Dale gave to suit my purposes. I wanted something that was a little more flexible and had some error trapping. Just thought I might put it here for anyone looking for the same thing.

@echo off
setLocal EnableDelayedExpansion
GOTO checkvars

:checkvars
    IF "%1"=="" GOTO syntaxerror
    IF NOT "%1"=="-f"  GOTO syntaxerror
    IF %2=="" GOTO syntaxerror
    IF NOT EXIST %2 GOTO nofile
    IF "%3"=="" GOTO syntaxerror
    IF NOT "%3"=="-n" GOTO syntaxerror
    IF "%4"==""  GOTO syntaxerror
    set param=%4
    echo %param%| findstr /xr "[1-9][0-9]* 0" >nul && (
        goto proceed
    ) || (
        echo %param% is NOT a valid number
        goto syntaxerror
    )

:proceed
    set limit=%4
    set file=%2
    set lineCounter=1+%limit%
    set filenameCounter=0

    set name=
    set extension=

    for %%a in (%file%) do (
        set "name=%%~na"
        set "extension=%%~xa"
    )

    for /f "usebackq tokens=*" %%a in (%file%) do (
        if !lineCounter! gtr !limit! (
            set splitFile=!name!_part!filenameCounter!!extension!
            set /a filenameCounter=!filenameCounter! + 1
            set lineCounter=1
            echo Created !splitFile!.
        )
        cls
        echo Adding Line !splitFile! - !lineCounter!
        echo %%a>> !splitFile!
        set /a lineCounter=!lineCounter! + 1
    )
    echo Done!
    goto end
:syntaxerror
    Echo Syntax: %0 -f Filename -n "Number Of Rows Per File"
    goto end
:nofile
    echo %2 does not exist
    goto end
:end

How to add Android Support Repository to Android Studio?

Gradle can work with the 18.0.+ notation, it however now depends on the new support repository which is now bundled with the SDK.

Open the SDK manager and immediately under Extras the first option is "Android Support Repository" and install it

What's the difference between Visual Studio Community and other, paid versions?

All these answers are partially wrong.

Microsoft has clarified that Community is for ANY USE as long as your revenue is under $1 Million US dollars. That is literally the only difference between Pro and Community. Corporate or free or not, irrelevant.

Even the lack of TFS support is not true. I can verify it is present and works perfectly.

EDIT: Here is an MSDN post regarding the $1M limit: MSDN (hint: it's in the VS 2017 license)

EDIT: Even over the revenue limit, open source is still free.

Converting JavaScript object with numeric keys into array

Try this:

var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    newArr.push([obj.value]);
});

Django - "no module named django.core.management"

This also happens if you change the directory structure of your python project (I did this, and then puzzled over the change in behavior). If you do so, you'll need to change a line in your /bin/activate file. So, say your project was at

/User/me/CodeProjects/coolApp/

and your activate file is at

/User/me/CodeProjects/coolApp/venv/bin/activate

when you set up your project, then you changed your project to

/User/me/CodeProjects/v1-coolApp/

or something. You would then need to open

/User/me/CodeProjects/v1-coolApp/venv/bin/activate

find the line where it says

VIRTUAL_ENV="/User/me/CodeProjects/coolApp"
export VIRTUAL_ENV

and change it to

VIRTUAL_ENV="/User/me/CodeProjects/v1-coolApp"

before reactivating

How can I INSERT data into two tables simultaneously in SQL Server?

Keep a look out for SQL Server to support the 'INSERT ALL' Statement. Oracle has it already, it looks like this (SQL Cookbook):

insert all
  when loc in ('NEW YORK', 'BOSTON') THEN
   into dept_east(deptno, dname, loc) values(deptno, dname, loc)
  when loc in ('CHICAGO') THEN
   into dept_mid(deptno, dname, loc) values(deptno, dname, loc)
  else
   into dept_west(deptno, dname, loc) values(deptno, dname, loc)
select deptno, dname, loc
  from dept

What does the Ellipsis object do?

As of Python 3.5 and PEP484, the literal ellipsis is used to denote certain types to a static type checker when using the typing module.

Example 1:

Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis, for example Tuple[int, ...]

Example 2:

It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis (three dots) for the list of arguments:

def partial(func: Callable[..., str], *args) -> Callable[..., str]:
    # Body

DateTime.MinValue and SqlDateTime overflow

Although it is an old question, another solution is to use datetime2 for the database column. MSDN Link

Json.NET serialize object with root name

Sorry, my english is not that good. But i like to improve the upvoted answers. I think that using Dictionary is more simple and clean.

class Program
    {
        static void Main(string[] args)
        {
            agencia ag1 = new agencia()
            {
                name = "Iquique",
                data = new object[] { new object[] {"Lucas", 20 }, new object[] {"Fernando", 15 } }
            };
            agencia ag2 = new agencia()
            {
                name = "Valparaiso",
                data = new object[] { new object[] { "Rems", 20 }, new object[] { "Perex", 15 } }
            };
            agencia agn = new agencia()
            {
                name = "Santiago",
                data = new object[] { new object[] { "Jhon", 20 }, new object[] { "Karma", 15 } }
            };


            Dictionary<string, agencia> dic = new Dictionary<string, agencia>
            {
                { "Iquique", ag1 },
                { "Valparaiso", ag2 },
                { "Santiago", agn }
            };

            string da = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            Console.WriteLine(da);
            Console.ReadLine();
        }


    }

    public class agencia
    {
        public string name { get; set; }
        public object[] data { get; set; }
    }

This code generate the following json (This is desired format)

{  
   "Iquique":{  
      "name":"Iquique",
      "data":[  
         [  
            "Lucas",
            20
         ],
         [  
            "Fernando",
            15
         ]
      ]
   },
   "Valparaiso":{  
      "name":"Valparaiso",
      "data":[  
         [  
            "Rems",
            20
         ],
         [  
            "Perex",
            15
         ]
      ]
   },
   "Santiago":{  
      "name":"Santiago",
      "data":[  
         [  
            "Jhon",
            20
         ],
         [  
            "Karma",
            15
         ]
      ]
   }
}

How to bind DataTable to Datagrid

In cs file:

    private DataTable _dataTable;

    public DataTable DataTable
    {
        get { return _dataTable; }
        set { _dataTable = value; }
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this._dataTable = new DataTable("table");

        this._dataTable.Columns.Add("col0");
        this._dataTable.Columns.Add("col1");
        this._dataTable.Columns.Add("col2");

        this._dataTable.Rows.Add("data00", "data01", "data02");
        this._dataTable.Rows.Add("data10", "data11", "data22");
        this._dataTable.Rows.Add("data20", "data21", "data22");

        this.grid1.DataContext = this;

    }

In Xaml file:

<DataGrid x:Name="grid1"
          Margin="10"
          AutoGenerateColumns="True"
          ItemsSource="{Binding Path=DataTable, Mode=TwoWay}" />

How to reference image resources in XAML?

  1. Add folders to your project and add images to these through "Existing Item".
  2. XAML similar to this: <Image Source="MyRessourceDir\images\addButton.png"/>
  3. F6 (Build)

Force table column widths to always be fixed regardless of contents

Make the table rock solid BEFORE the css. Figure your width of the table, then use a 'controlling' row whereby each td has an explicit width, all of which add up to the width in the table tag.

Having to do hundreds html emails to work everywhere, using the correct HTML first, then styling w/css will work around many issues in all IE's, webkit's and mozillas.

so:

<table width="300" cellspacing="0" cellpadding="0">
  <tr>
    <td width="50"></td>
    <td width="100"></td>
    <td width="150"></td>
  </tr>
  <tr>
    <td>your stuff</td>
    <td>your stuff</td>
    <td>your stuff</td>
  </tr>
</table>

Will keep a table at 300px wide. Watch images that are larger than the width by extremes

window.location.href doesn't redirect

From this answer,

window.location.href not working

you just need to add

return false;

at the bottom of your function

Java, How do I get current index/key in "for each" loop

You can't, you either need to keep the index separately:

int index = 0;
for(Element song : question) {
    System.out.println("Current index is: " + (index++));
}

or use a normal for loop:

for(int i = 0; i < question.length; i++) {
    System.out.println("Current index is: " + i);
}

The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"

CSS – why doesn’t percentage height work?

I think you just need to give it a parent container... even if that container's height is defined in percentage. This seams to work just fine: JSFiddle

html, body { 
    margin: 0; 
    padding: 0; 
    width: 100%; 
    height: 100%;
}
.wrapper { 
    width: 100%; 
    height: 100%; 
}
.container { 
    width: 100%; 
    height: 50%; 
}

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

I think the easiest solution is to set

Created DATETIME2 NOT NULL DEFAULT GETDATE()

in column declaration and in VS2010 EntityModel designer set corresponding column property StoreGeneratedPattern = Computed.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

How to handle an IF STATEMENT in a Mustache template?

In general, you use the # syntax:

{{#a_boolean}}
  I only show up if the boolean was true.
{{/a_boolean}}

The goal is to move as much logic as possible out of the template (which makes sense).

How to change the height of a <br>?

you can apply line-height on that <p> element, so lines become larger.

How do I compare strings in GoLang?

The content inside strings in Golang can be compared using == operator. If the results are not as expected there may be some hidden characters like \n, \r, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings package in golang.

For Instance, spaces can be removed using strings.TrimSpace function. You can also define a custom function to remove any character you need. strings.TrimFunc function can give you more power.

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

EasyPHP is very good :

  • lightweight & portable : no windows service (like wamp)
  • easy to configure (all configuration files in the same folder : httpd.conf, php.ini & my.ini)
  • auto restarts apache when you edit httpd.conf

WAMP or UWAMP are good choices if you need to test with multiples versions of PHP and Apache.

But you can also use multiple versions of PHP with EasyPHP (by downloading the PHP version you need on php.net, and loading this version by editing httpd.conf) :

LoadModule php4_module "${path}/php4/php4apache2_2.dll"

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

How are environment variables used in Jenkins with Windows Batch Command?

I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.

If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE

echo %WORKSPACE%

If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.

setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
  set WORKSPACE=AFTER
  echo Normal Expansion = %WORKSPACE%
  echo Delayed Expansion = !WORKSPACE!
)

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.

Convert a String representation of a Dictionary to a dictionary?

To OP's example:

s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"

We can use Yaml to deal with this kind of non-standard json in string:

>>> import yaml
>>> s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
>>> s
"{'muffin' : 'lolz', 'foo' : 'kitty'}"
>>> yaml.load(s)
{'muffin': 'lolz', 'foo': 'kitty'}

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Same problem, none of anything related to "memory_limit" worked, but..

composer self-update --2

..solved my problem. (upgrade: 1.10.17 -> 2.0.4)

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

If you're looking to paginate results, use the integrated paginator, it works great!

$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages

Messages Using Command prompt in Windows 7

"net send" is a command using a background service called "messenger". This service has been removed from Windows 7. ie You cannot use 'net send' on Vista nor Win7 / Win8.

Pity though , I loved using it.

There is alternatives, but that requires you to download and install software on each pc you want to use, this software runs as background services, and i would advise one to be very very very very careful of using these kind of software as they can potentially cause seriously damage one's system or impair the systems securities.

winsent innocenti / winsent messenger

****This command is risky because of what is stated above***

Is it possible to move/rename files in Git and maintain their history?

Git detects renames rather than persisting the operation with the commit, so whether you use git mv or mv doesn't matter.

The log command takes a --follow argument that continues history before a rename operation, i.e., it searches for similar content using the heuristics:

http://git-scm.com/docs/git-log

To lookup the full history, use the following command:

git log --follow ./path/to/file

QComboBox - set selected item based on the item's data

You lookup the value of the data with findData() and then use setCurrentIndex()

QComboBox* combo = new QComboBox;
combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
combo->addItem .....

float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
   combo->setCurrentIndex(index);
}

How to call a PHP file from HTML or Javascript

I just want to have a button on my website make a PHP file run

<form action="my.php" method="post">
    <input type="submit">
</form>

Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.

<a href="my.php">run php</a>

(Although you should use link text that describes what happens from the user's point of view, not the servers)


I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

This is tricker.

First, you do need to use a form and POST (since you are sending data to be stored).

Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.

Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.

<a href="showBlogEntry.php?entry_id=123">...</a>

Make sure you also read up on SQL injection and XSS.

How to set iPhone UIView z index?

Within the view you want to bring to the top... (in swift)

superview?.bringSubviewToFront(self)

Locate the nginx.conf file my nginx is actually using

Both nginx -t and nginx -V would print out the default nginx config file path.

$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

$ nginx -V
nginx version: nginx/1.11.1
built by gcc 4.9.2 (Debian 4.9.2-10)
built with OpenSSL 1.0.1k 8 Jan 2015
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf ...

If you want, you can get the config file by:

$ nginx -V 2>&1 | grep -o '\-\-conf-path=\(.*conf\)' | cut -d '=' -f2
/etc/nginx/nginx.conf

Even if you have loaded some other config file, they would still print out the default value.


ps aux would show you the current loaded nginx config file.

$ ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root        11  0.0  0.2  31720  2212 ?        Ss   Jul23   0:00 nginx: master process nginx -c /app/nginx.conf

So that you could actually get the config file by for example:

$ ps aux | grep "[c]onf" | awk '{print $(NF)}'
/app/nginx.conf

Difference between .keystore file and .jks file

Ultimately, .keystore and .jks are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).

In Java, the word keystore can have either of the following meanings, depending on the context:

When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.

Java uses its KeyStore class and related API to make use of a keystore (whether it's file based or not). JKS is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:

  • .jks for type "JKS",
  • .p12 or .pfx for type "PKCS12" (the specification name is PKCS#12, but the # is not used in the Java keystore type name).

In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks extension), which is frequently used for Android applications.

Android studio: emulator is running but not showing up in Run App "choose a running device"

Had similar issue with my emulator. Solved by Wiping Data of emulator

Tool > ABD Manager > Down arrow under Action Wipe Data

Note : This is remove all data inside emulator.

Get Client Machine Name in PHP

In opposite to the most comments, I think it is possible to get the client's hostname (machine name) in plain PHP, but it's a little bit "dirty".

By requesting "NTLM" authorization via HTTP header...

if (!isset($headers['AUTHORIZATION']) || substr($headers['AUTHORIZATION'],0,4) !== 'NTLM'){
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: NTLM');
    exit;
}

You can force the client to send authorization credentials via NTLM format. The NTLM hash sent by the client to server contains, besides the login credtials, the clients machine name. This works cross-browser and PHP only.

$auth = $headers['AUTHORIZATION'];

if (substr($auth,0,5) == 'NTLM ') {
    $msg = base64_decode(substr($auth, 5));
    if (substr($msg, 0, 8) != "NTLMSSPx00")
            die('error header not recognised');

    if ($msg[8] == "x01") {
            $msg2 = "NTLMSSPx00x02"."x00x00x00x00".
                    "x00x00x00x00".
                    "x01x02x81x01".
                    "x00x00x00x00x00x00x00x00".
                    "x00x00x00x00x00x00x00x00".
                    "x00x00x00x00x30x00x00x00";

            header('HTTP/1.1 401 Unauthorized');
            header('WWW-Authenticate: NTLM '.trim(base64_encode($msg2)));
            exit;
    }
    else if ($msg[8] == "x03") {
            function get_msg_str($msg, $start, $unicode = true) {
                    $len = (ord($msg[$start+1]) * 256) + ord($msg[$start]);
                    $off = (ord($msg[$start+5]) * 256) + ord($msg[$start+4]);
                    if ($unicode)
                            return str_replace("\0", '', substr($msg, $off, $len));
                    else
                            return substr($msg, $off, $len);
            }
            $user = get_msg_str($msg, 36);
            $domain = get_msg_str($msg, 28);
            $workstation = get_msg_str($msg, 44);
            print "You are $user from $workstation.$domain";
    }
}

And yes, it's not a plain and easy "read the machine name function", because the user is prompted with an dialog, but it's an example, that it is indeed possible (against the other statements here).

Full code can be found here: https://en.code-bude.net/2017/05/07/how-to-read-client-hostname-in-php/

How to fix Invalid AES key length?

You can verify the key length limit:

int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
System.out.println("MaxAllowedKeyLength=[" + maxKeyLen + "].");

How to subscribe to an event on a service in Angular2?

Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945

Also, the Angular docs now have a cookbook example that uses a Subject.


Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.

nav.service.ts

import {EventEmitter} from 'angular2/core';
export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emitNavChangeEvent(number) {
    this.navchange.emit(number);
  }
  getNavChangeEmitter() {
    return this.navchange;
  }
}

components.ts

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number = 0;
  subscription: any;
  constructor(private navService:NavService) {}
  ngOnInit() {
    this.subscription = this.navService.getNavChangeEmitter()
      .subscribe(item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item = 1;
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emitNavChangeEvent(item);
  }
}

Plunker

Find IP address of directly connected device

Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.

Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.

For example, you have ip 192.168.1.1 and subnet 255.255.255.0

  1. ping 192.168.1.255
  2. stop the ping after 5 seconds
  3. watch the devices replies : arp -a

Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.

Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.

Is it the only one device attached to your pc ? Is it a router or another simple pc ?

Fastest way to tell if two files have the same contents in Unix/Linux?

I like @Alex Howansky have used 'cmp --silent' for this. But I need both positive and negative response so I use:

cmp --silent file1 file2 && echo '### SUCCESS: Files Are Identical! ###' || echo '### WARNING: Files Are Different! ###'

I can then run this in the terminal or with a ssh to check files against a constant file.

How to import a CSS file in a React Component

In cases where you just want to inject some styles from a stylesheet into a component without bundling in the whole stylesheet I recommend https://github.com/glortho/styled-import. For example:

const btnStyle = styledImport.react('../App.css', '.button')

// btnStyle is now { color: 'blue' } or whatever other rules you have in `.button`.

NOTE: I am the author of this lib, and I built it for cases where mass imports of styles and CSS modules are not the best or most viable solution.

Calculating Distance between two Latitude and Longitude GeoCoordinates

You can use System.device.Location:

System.device.Location.GeoCoordinate gc = new System.device.Location.GeoCoordinate(){
Latitude = yourLatitudePt1,
Longitude = yourLongitudePt1
};

System.device.Location.GeoCoordinate gc2 = new System.device.Location.GeoCoordinate(){
Latitude = yourLatitudePt2,
Longitude = yourLongitudePt2
};

Double distance = gc2.getDistanceTo(gc);

good luck

How do you stop tracking a remote branch in Git?

Here's a one-liner to remove all remote-tracking branches matching a pattern:

git branch -rd $(git branch -a | grep '{pattern}' | cut -d'/' -f2-10 | xargs)

Test if executable exists in Python?

There is a which.py script in a standard Python distribution (e.g. on Windows '\PythonXX\Tools\Scripts\which.py').

EDIT: which.py depends on ls therefore it is not cross-platform.

Javascript: 'window' is not defined

It is from an external js file and it is the only file linked to the page.

OK.

When I double click this file I get the following error

Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:

Windows Script Host Error: 'window' is not defined Code: 800A1391

... not an error you'll see in a browser. And of course, the browser is what supplies the window object.

ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload definition is simply being hit after the browser fires the window.onload event.

Convert a hexadecimal string to an integer efficiently in C?

For AVR Microcontrollers I wrote the following function, including relevant comments to make it easy to understand:

/**
 * hex2int
 * take a hex string and convert it to a 32bit number (max 8 hex digits)
 */
uint32_t hex2int(char *hex) {
    uint32_t val = 0;
    while (*hex) {
        // get current character then increment
        char byte = *hex++; 
        // transform hex character to the 4bit equivalent number, using the ascii table indexes
        if (byte >= '0' && byte <= '9') byte = byte - '0';
        else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
        else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;    
        // shift 4 to make space for new digit, and add the 4 bits of the new digit 
        val = (val << 4) | (byte & 0xF);
    }
    return val;
}

Example:

char *z ="82ABC1EF";
uint32_t x = hex2int(z);
printf("Number is [%X]\n", x);

Will output: enter image description here

Can I inject a service into a directive in AngularJS?

You can also use the $inject service to get whatever service you like. I find that useful if I don't know the service name ahead of time but know the service interface. For example a directive that will plug a table into an ngResource end point or a generic delete-record button which interacts with any api end point. You don't want to re-implement the table directive for every controller or data-source.

template.html

<div my-directive api-service='ServiceName'></div>

my-directive.directive.coffee

angular.module 'my.module'
  .factory 'myDirective', ($injector) ->
    directive = 
      restrict: 'A'
      link: (scope, element, attributes) ->
        scope.apiService = $injector.get(attributes.apiService)

now your 'anonymous' service is fully available. If it is ngResource for example you can then use the standard ngResource interface to get your data

For example:

scope.apiService.query((response) ->
  scope.data = response
, (errorResponse) ->
  console.log "ERROR fetching data for service: #{attributes.apiService}"
  console.log errorResponse.data
)

I have found this technique to be very useful when making elements that interact with API endpoints especially.

inserting characters at the start and end of a string

Let's say we have a string called yourstring:

for x in range(0, [howmanytimes you want it at the beginning]):
    yourstring = "L" + yourstring
for x in range(0, [howmanytimes you want it at the end]):
    yourstring += "L"

Python: TypeError: cannot concatenate 'str' and 'int' objects

You can convert int into str using string function:

user = "mohan"

line = str(50)

print(user + "typed" + line + "lines")

Return array from function

Your BlockID function uses the undefined variable images, which will lead to an error. Also, you should not use an Array here - JavaScripts key-value-maps are plain objects:

function BlockID() {
    return {
        "s": "Images/Block_01.png",
        "g": "Images/Block_02.png",
        "C": "Images/Block_03.png",
        "d": "Images/Block_04.png"
    };
}

Run a Java Application as a Service on Linux

Here is a sample shell script (make sure you replace the MATH name with the name of the your application):

#!/bin/bash

### BEGIN INIT INFO
# Provides:                 MATH
# Required-Start:           $java
# Required-Stop:            $java
# Short-Description:        Start and stop MATH service.
# Description:              -
# Date-Creation:            -
# Date-Last-Modification:   -
# Author:                   -
### END INIT INFO

# Variables
PGREP=/usr/bin/pgrep
JAVA=/usr/bin/java
ZERO=0

# Start the MATH
start() {
    echo "Starting MATH..."
    #Verify if the service is running
    $PGREP -f MATH > /dev/null
    VERIFIER=$?
    if [ $ZERO = $VERIFIER ]
    then
        echo "The service is already running"
    else
        #Run the jar file MATH service
        $JAVA -jar /opt/MATH/MATH.jar > /dev/null 2>&1 &
        #sleep time before the service verification
        sleep 10
        #Verify if the service is running
        $PGREP -f MATH  > /dev/null
        VERIFIER=$?
        if [ $ZERO = $VERIFIER ]
        then
            echo "Service was successfully started"
        else
            echo "Failed to start service"
        fi
    fi
    echo
}

# Stop the MATH
stop() {
    echo "Stopping MATH..."
    #Verify if the service is running
    $PGREP -f MATH > /dev/null
    VERIFIER=$?
    if [ $ZERO = $VERIFIER ]
    then
        #Kill the pid of java with the service name
        kill -9 $($PGREP -f MATH)
        #Sleep time before the service verification
        sleep 10
        #Verify if the service is running
        $PGREP -f MATH  > /dev/null
        VERIFIER=$?
        if [ $ZERO = $VERIFIER ]
        then
            echo "Failed to stop service"
        else
            echo "Service was successfully stopped"
        fi
    else
        echo "The service is already stopped"
    fi
    echo
}

# Verify the status of MATH
status() {
    echo "Checking status of MATH..."
    #Verify if the service is running
    $PGREP -f MATH > /dev/null
    VERIFIER=$?
    if [ $ZERO = $VERIFIER ]
    then
        echo "Service is running"
    else
        echo "Service is stopped"
    fi
    echo
}

# Main logic
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart|reload)
        stop
        start
        ;;
  *)
    echo $"Usage: $0 {start|stop|status|restart|reload}"
    exit 1
esac
exit 0

Database development mistakes made by application developers

This has been said before, but: indexes, indexes, indexes. I've seen so many cases of poorly performing enterprise web apps that were fixed by simply doing a little profiling (to see which tables were being hit a lot), and then adding an index on those tables. This doesn't even require much in the way of SQL writing knowledge, and the payoff is huge.

Avoid data duplication like the plague. Some people advocate that a little duplication won't hurt, and will improve performance. Hey, I'm not saying that you have to torture your schema into Third Normal Form, until it's so abstract that not even the DBA's know what's going on. Just understand that whenever you duplicate a set of names, or zipcodes, or shipping codes, the copies WILL fall out of synch with each other eventually. It WILL happen. And then you'll be kicking yourself as you run the weekly maintenance script.

And lastly: use a clear, consistent, intuitive naming convention. In the same way that a well written piece of code should be readable, a good SQL schema or query should be readable and practically tell you what it's doing, even without comments. You'll thank yourself in six months, when you have to to maintenance on the tables. "SELECT account_number, billing_date FROM national_accounts" is infinitely easier to work with than "SELECT ACCNTNBR, BILLDAT FROM NTNLACCTS".

How to show progress dialog in Android?

Step 1:Creata a XML File

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <Button
        android:id="@+id/btnProgress"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Progress Dialog"/>
</LinearLayout>

Step 2:Create a SampleActivity.java

package com.scancode.acutesoft.telephonymanagerapp;


import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SampleActivity extends Activity implements View.OnClickListener {
    Button btnProgress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnProgress = (Button) findViewById(R.id.btnProgress);
        btnProgress.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        final ProgressDialog progressDialog = new ProgressDialog(SampleActivity.this);
        progressDialog.setMessage("Please wait data is Processing");
        progressDialog.show();

//        After 2 Seconds i dismiss progress Dialog

        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(2000);
                    if (progressDialog.isShowing())
                        progressDialog.dismiss();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

VBA Excel - Insert row below with same format including borders and frames

well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)

lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents

(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )

Scale Image to fill ImageView width and keep aspect ratio

I had a similar problem once. I solved it by making a custom ImageView.

public class CustomImageView extends ImageView

Then override the onMeasure method of the imageview. I did something like this I believe:

    @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    try {
        Drawable drawable = getDrawable();

        if (drawable == null) {
            setMeasuredDimension(0, 0);
        } else {
            float imageSideRatio = (float)drawable.getIntrinsicWidth() / (float)drawable.getIntrinsicHeight();
            float viewSideRatio = (float)MeasureSpec.getSize(widthMeasureSpec) / (float)MeasureSpec.getSize(heightMeasureSpec);
            if (imageSideRatio >= viewSideRatio) {
                // Image is wider than the display (ratio)
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = (int)(width / imageSideRatio);
                setMeasuredDimension(width, height);
            } else {
                // Image is taller than the display (ratio)
                int height = MeasureSpec.getSize(heightMeasureSpec);
                int width = (int)(height * imageSideRatio);
                setMeasuredDimension(width, height);
            }
        }
    } catch (Exception e) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

This will stretch the image to fit the screen while maintaining the aspect ratio.

Magento Product Attribute Get Value

You could write a method that would do it directly via sql I suppose.

Would look something like this:

Variables:

$store_id = 1;
$product_id = 1234;
$attribute_code = 'manufacturer';

Query:

SELECT value FROM eav_attribute_option_value WHERE option_id IN (
    SELECT option_id FROM eav_attribute_option WHERE FIND_IN_SET(
        option_id, 
        (SELECT value FROM catalog_product_entity_varchar WHERE
            entity_id = '$product_id' AND 
            attribute_id = (SELECT attribute_id FROM eav_attribute WHERE
                attribute_code='$attribute_code')
        )
    ) > 0) AND
    store_id='$store_id';

You would have to get the value from the correct table based on the attribute's backend_type (field in eav_attribute) though so it takes at least 1 additional query.

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

this is a common question here.

Here's a link to a similar question. You can see my answer there. Why POST['submit'] is set when I reload?

The basic answer is to look into post/redirect/get, but since it is easier to see by example, just check the link above.

Tensorflow import error: No module named 'tensorflow'

In Windows 64, if you did this sequence correctly:

Anaconda prompt:

conda create -n tensorflow python=3.5
activate tensorflow
pip install --ignore-installed --upgrade tensorflow

Be sure you still are in tensorflow environment. The best way to make Spyder recognize your tensorflow environment is to do this:

conda install spyder

This will install a new instance of Spyder inside Tensorflow environment. Then you must install scipy, matplotlib, pandas, sklearn and other libraries. Also works for OpenCV.

Always prefer to install these libraries with "conda install" instead of "pip".

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

In my case, the warning occurred because of just the regular type of boolean indexing -- because the series had only np.nan. Demonstration (pandas 1.0.3):

>>> import pandas as pd
>>> import numpy as np
>>> pd.Series([np.nan, 'Hi']) == 'Hi'
0    False
1     True
>>> pd.Series([np.nan, np.nan]) == 'Hi'
~/anaconda3/envs/ms3/lib/python3.7/site-packages/pandas/core/ops/array_ops.py:255: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  res_values = method(rvalues)
0    False
1    False

I think with pandas 1.0 they really want you to use the new 'string' datatype which allows for pd.NA values:

>>> pd.Series([pd.NA, pd.NA]) == 'Hi'
0    False
1    False
>>> pd.Series([np.nan, np.nan], dtype='string') == 'Hi'
0    <NA>
1    <NA>
>>> (pd.Series([np.nan, np.nan], dtype='string') == 'Hi').fillna(False)
0    False
1    False

Don't love at which point they tinkered with every-day functionality such as boolean indexing.

Differences between contentType and dataType in jQuery ajax function

From the documentation:

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

Type: String

When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

and:

dataType (default: Intelligent Guess (xml, json, script, or html))

Type: String

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

They're essentially the opposite of what you thought they were.

How do I change the background color of a plot made with ggplot2

Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.

library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

mytheme = list(
    theme_classic()+
        theme(panel.background = element_blank(),strip.background = element_rect(colour=NA, fill=NA),panel.border = element_rect(fill = NA, color = "black"),
              legend.title = element_blank(),legend.position="bottom", strip.text = element_text(face="bold", size=9),
              axis.text=element_text(face="bold"),axis.title = element_text(face="bold"),plot.title = element_text(face = "bold", hjust = 0.5,size=13))
)

ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + mytheme + geom_line()

custom ggplot theme

How to read single Excel cell value

using Microsoft.Office.Interop.Excel;

string path = "C:\\Projects\\ExcelSingleValue\\Test.xlsx ";

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.ActiveSheet;

//Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();

wb.Close();

This example used the 'Microsoft Excel 15.0 Object Library' but may be compatible with earlier versions of Interop and other libraries.

iOS detect if user is on an iPad

Many ways to do that in Swift:

We check the model below (we can only do a case sensitive search here):

class func isUserUsingAnIpad() -> Bool {
    let deviceModel = UIDevice.currentDevice().model
    let result: Bool = NSString(string: deviceModel).containsString("iPad")
    return result
}

We check the model below (we can do a case sensitive/insensitive search here):

    class func isUserUsingAnIpad() -> Bool {
        let deviceModel = UIDevice.currentDevice().model
        let deviceModelNumberOfCharacters: Int = count(deviceModel)
        if deviceModel.rangeOfString("iPad",
                                     options: NSStringCompareOptions.LiteralSearch,
                                     range: Range<String.Index>(start: deviceModel.startIndex,
                                                                end: advance(deviceModel.startIndex, deviceModelNumberOfCharacters)),
                                     locale: nil) != nil {
            return true
        } else {
            return false
        }
   }

UIDevice.currentDevice().userInterfaceIdiom below only returns iPad if the app is for iPad or Universal. If it is an iPhone app being ran on an iPad then it won't. So you should instead check the model. :

    class func isUserUsingAnIpad() -> Bool {
        if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
            return true
        } else {
            return false
        }
   }

This snippet below does not compile if the class does not inherit of an UIViewController, otherwise it works just fine. Regardless UI_USER_INTERFACE_IDIOM() only returns iPad if the app is for iPad or Universal. If it is an iPhone app being ran on an iPad then it won't. So you should instead check the model. :

class func isUserUsingAnIpad() -> Bool {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad) {
        return true
    } else {
        return false
    }
}

How to show math equations in general github's markdown(not github's blog)

While GitHub won't interpret the MathJax formulas, you can automatically generate a new Markdown document with the formulae replaced by images.

I suggest you look at the GitHub app TeXify:

GitHub App that looks in your pushes for files with extension *.tex.md and renders it's TeX expressions as SVG images

How it works (from the source repository):

Whenever you push TeXify will run and seach for *.tex.md files in your last commit. For each one of those it'll run readme2tex which will take LaTeX expressions enclosed between dollar signs, convert it to plain SVG images, and then save the output into a .md extension file (That means that a file named README.tex.md will be processed and the output will be saved as README.md). After that, the output file and the new SVG images are then commited and pushed back to your repo.

How to remove ASP.Net MVC Default HTTP Headers?

.NET Core

To remove the Server header, within the Program.cs file, add the following option:

.UseKestrel(opt => opt.AddServerHeader = false)

For dot net core 1, put add the option inside the .UseKestrel() call. For dot net core 2, add the line after UseStartup().

To remove X-Powered-By header, if deployed to IIS, edit your web.config and add the following section inside the system.webServer tag:

<httpProtocol>
    <customHeaders>
        <remove name="X-Powered-By" />
    </customHeaders>
</httpProtocol>

.NET 4.5.2

To remove the Server header, within your global.asax file add the following:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        string[] headers = { "Server", "X-AspNet-Version" };

        if (!Response.HeadersWritten)
        {
            Response.AddOnSendingHeaders((c) =>
            {
                if (c != null && c.Response != null && c.Response.Headers != null)
                {
                    foreach (string header in headers)
                    {
                        if (c.Response.Headers[header] != null)
                        {
                            c.Response.Headers.Remove(header);
                        }
                    }
                }
            });
        }

    }

Pre .NET 4.5.2

Add the following c# class to your project:

public class RemoveServerHeaderModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += OnPreSendRequestHeaders;
    }

    public void Dispose() { }

    void OnPreSendRequestHeaders(object sender, EventArgs e)
    {
        HttpContext.Current.Response.Headers.Remove("Server");
    }
}

and then within your web.config add the following <modules> section:

<system.webServer>
    ....
 <modules>
    <add name="RemoveServerHeaderModule" type="MyNamespace.RemoveServerHeaderModule" />
 </modules>

However I had a problem where sub-projects couldn't find this module. Not fun.

Removing X-AspNetMvc-Version header

To remove the ''X-AspNetMvc-Version'' tag, for any version of .NET, modify your ''web.config'' file to include:

<system.web>
...
   <httpRuntime enableVersionHeader="false" />
...
</system.web>

Thanks Microsoft for making this unbelievably difficult. Or maybe that was your intention so that you could track IIS and MVC installs across the world ...

How do I change UIView Size?

You can do this in Interface Builder:

1) Control-drag from a frame view (e.g. questionFrame) to main View, in the pop-up select "Equal heights".

2)Then go to size inspector of the frame, click edit "Equal height to Superview" constraint, set the multiplier to 0.7 and hit return.

You'll see that constraint has changed from "Equal height to..." to "Proportional height to...".

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

Since the question mentions VirtualBox, this one works currently:

VBoxManage convertfromraw imagefile.dd vmdkname.vmdk --format VMDK

Run it without arguments for a few interesting details (notably the --variant flag):

VBoxManage convertfromraw

How can I find where Python is installed on Windows?

If you use anaconda navigator on windows, you can go too enviornments and scroll over the enviornments, the root enviorment will indicate where it is installed. It can help if you want to use this enviorment when you need to connect this to other applications, where you want to integrate some python code.

Radio Buttons ng-checked with ng-model

Please explain why same ng-model is used? And what value is passed through ng- model and how it is passed? To be more specific, if I use console.log(color) what would be the output?

Jackson Vs. Gson

Jackson and Gson are the most complete Java JSON packages regarding actual data binding support; many other packages only provide primitive Map/List (or equivalent tree model) binding. Both have complete support for generic types, as well, as enough configurability for many common use cases.

Since I am more familiar with Jackson, here are some aspects where I think Jackson has more complete support than Gson (apologies if I miss a Gson feature):

  • Extensive annotation support; including full inheritance, and advanced "mix-in" annotations (associate annotations with a class for cases where you can not directly add them)
  • Streaming (incremental) reading, writing, for ultra-high performance (or memory-limited) use cases; can mix with data binding (bind sub-trees) -- EDIT: latest versions of Gson also include streaming reader
  • Tree model (DOM-like access); can convert between various models (tree <-> java object <-> stream)
  • Can use any constructors (or static factory methods), not just default constructor
  • Field and getter/setter access (earlier gson versions only used fields, this may have changed)
  • Out-of-box JAX-RS support
  • Interoperability: can also use JAXB annotations, has support/work-arounds for common packages (joda, ibatis, cglib), JVM languages (groovy, clojure, scala)
  • Ability to force static (declared) type handling for output
  • Support for deserializing polymorphic types (Jackson 1.5) -- can serialize AND deserialize things like List correctly (with additional type information)
  • Integrated support for binary content (base64 to/from JSON Strings)

How do I link to Google Maps with a particular longitude and latitude?

If you want to open Google Maps in a browser:

http://maps.google.com/?q=<lat>,<lng>

To open the Google Maps app on an iOS mobile device, use the Google Maps URL Scheme:

comgooglemaps://?q=<lat>,<lng>

To open the Google Maps app on Android, use the geo: intent:

geo:<lat>,<lng>?z=<zoom>

Switch between two frames in tkinter

Here is another simple answer, but without using classes.

from tkinter import *


def raise_frame(frame):
    frame.tkraise()

root = Tk()

f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)

for frame in (f1, f2, f3, f4):
    frame.grid(row=0, column=0, sticky='news')

Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()

Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()

Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')

Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()

raise_frame(f1)
root.mainloop()

Create GUI using Eclipse (Java)

Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

What's the difference between “mod” and “remainder”?

In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.

 7 modulo  3 -->  1  
 7 modulo -3 --> -2 
-7 modulo  3 -->  2  
-7 modulo -3 --> -1 

Telling Python to save a .txt file to a certain directory on Windows and Mac

Another simple way without using import OS is,

outFileName="F:\\folder\\folder\\filename.txt"
outFile=open(outFileName, "w")
outFile.write("""Hello my name is ABCD""")
outFile.close()

How to split long commands over multiple lines in PowerShell

You can use the backtick operator:

& "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" `
    -verb:sync `
    -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" `
    -dest:contentPath="c:\websites\xxx\wwwroot\,computerName=192.168.1.1,username=administrator,password=xxx"

That's still a little too long for my taste, so I'd use some well-named variables:

$msdeployPath = "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe"
$verbArg = '-verb:sync'
$sourceArg = '-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web"'
$destArg = '-dest:contentPath="c:\websites\xxx\wwwroot\,computerName=192.168.1.1,username=administrator,password=xxx"'

& $msdeployPath $verbArg $sourceArg $destArg

In SQL, is UPDATE always faster than DELETE+INSERT?

Delete + Insert is almost always faster because an Update has way more steps involved.

Update:

  1. Look for the row using PK.
  2. Read the row from disk.
  3. Check for which values have changed
  4. Raise the onUpdate Trigger with populated :NEW and :OLD variables
  5. Write New variables to disk (The entire row)

    (This repeats for every row you're updating)

Delete + Insert:

  1. Mark rows as deleted (Only in the PK).
  2. Insert new rows at the end of the table.
  3. Update PK Index with locations of new records.

    (This doesn't repeat, all can be perfomed in a single block of operation).

Using Insert + Delete will fragment your File System, but not that fast. Doing a lazy optimization on the background will allways free unused blocks and pack the table altogether.

Installing PDO driver on MySQL Linux server

On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql

There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.

How to redirect on another page and pass parameter in url from table?

Do this :

<script type="text/javascript">
function showDetails(username)
{
   window.location = '/player_detail?username='+username;
}
</script>

<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">

Bogus foreign key constraint fail

i found an easy solution, export the database, edit it what you want to edit in a text editor, then import it. Done

Looping through array and removing items, without breaking for loop

Auction.auctions = Auction.auctions.filter(function(el) {
  return --el["seconds"] > 0;
});

paint() and repaint() in Java

Difference between Paint() and Repaint() method

Paint():

This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.

Repaint():

This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.

How to avoid "Permission denied" when using pip with virtualenv

Solution:

If you created the virtualenv as root, run the following command:

sudo chown -R your_username:your_username path/to/virtuaelenv/

This will probably fix your problem.

Cheers

Get week number (in the year) from a date PHP

$date_string = "2012-10-18";
echo "Weeknummer: " . date("W", strtotime($date_string));

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

Delete %LocalAppData%\Microsoft\VisualStudio\14.0\ComponentModelCache and restart Visual Studio.

Alternatively, use the Clear MEF Component Cache extension.

How to generate access token using refresh token through google drive API?

If you want to implement that yourself, the OAuth 2.0 flow for Web Server Applications is documented at https://developers.google.com/accounts/docs/OAuth2WebServer, in particular you should check the section about using a refresh token:

https://developers.google.com/accounts/docs/OAuth2WebServer#refresh

Laravel, sync() - how to sync an array and also pass additional pivot fields?

In order to sync multiple models along with custom pivot data, you need this:

$user->roles()->sync([ 
    1 => ['expires' => true],
    2 => ['expires' => false],
    ...
]);

Ie.

sync([
    related_id => ['pivot_field' => value],
    ...
]);

edit

Answering the comment:

$speakers  = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData  = array_combine($speakers, $pivotData);

$user->roles()->sync($syncData);

Converting cv::Mat to IplImage*

Here is the recent fix for dlib users link

cv::Mat img = ...
IplImage iplImage = cvIplImage(img);

JavaScript require() on client side

Some answers already - but I would like to point you to YUI3 and its on-demand module loading. It works on both server (node.js) and client, too - I have a demo website using the exact same JS code running on either client or server to build the pages, but that's another topic.

YUI3: http://developer.yahoo.com/yui/3/

Videos: http://developer.yahoo.com/yui/theater/

Example:

(precondition: the basic YUI3 functions in 7k yui.js have been loaded)

YUI({
    //configuration for the loader
}).use('node','io','own-app-module1', function (Y) {
    //sandboxed application code
    //...

    //If you already have a "Y" instance you can use that instead
    //of creating a new (sandbox) Y:
    //  Y.use('moduleX','moduleY', function (Y) {
    //  });
    //difference to YUI().use(): uses the existing "Y"-sandbox
}

This code loads the YUI3 modules "node" and "io", and the module "own-app-module1", and then the callback function is run. A new sandbox "Y" with all the YUI3 and own-app-module1 functions is created. Nothing appears in the global namespace. The loading of the modules (.js files) is handled by the YUI3 loader. It also uses (optional, not show here) configuration to select a -debug or -min(ified) version of the modules to load.

See last changes in svn

svn log -r {2009-09-17}:HEAD

where 2009-09-17 is the date you went on holiday. To see the changed files as well as the summary, add a -v option:

svn log -r {2009-09-17}:HEAD -v

I haven't used WebSVN but there will be a log viewer somewhere that does the equivalent of these commands under the hood.

How do I find out what License has been applied to my SQL Server installation?

SELECT SERVERPROPERTY('LicenseType') as Licensetype, 
       SERVERPROPERTY('NumLicenses') as LicenseNumber,
       SERVERPROPERTY('productversion') as Productverion, 
       SERVERPROPERTY ('productlevel')as ProductLevel, 
       SERVERPROPERTY ('edition') as SQLEdition,@@VERSION as SQLversion

I had installed evaluation edition.Refer screenshot enter image description here

Hide Show content-list with only CSS, no javascript used

This is what I've used recently.

CSS

div#tabs p{display:none;}

div#tabs p.tab1:target {display:block;}
div#tabs p.tab2:target {display:block;}
div#tabs p.tab3:target {display:block;}

HTML

<div id='tabs'>
  <h2 class="nav-tab-wrapper">
    <a href="#tab1" class="nav-tab tab1">Pages</a>
    <a href="#tab2" class="nav-tab nav-tab-active tab2">Email</a>
    <a href="#tab3" class="nav-tab tab3">Support</a>
  </h2>

  <p id='tab1' class='tab1'>Awesome tab1 stuff</p>
  <p id='tab2' class='tab2'>Tab2 stuff</p>
  <p id='tab3' class='tab3'>Tab3 stuff</p>

</div>

https://jsfiddle.net/hoq0djwc/1/

Hope it helps somewhere.

How to create a custom scrollbar on a div (Facebook style)

Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:

The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.

Feel free to use my plugin for your project: :)

https://github.com/leoselig/jsFancyScroll/

I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!

What does %w(array) mean?

I was given a bunch of columns from a CSV spreadsheet of full names of users and I needed to keep the formatting, with spaces. The easiest way I found to get them in while using ruby was to do:

names = %( Porter Smith
Jimmy Jones
Ronald Jackson).split('\n')

This highlights that %() creates a string like "Porter Smith\nJimmyJones\nRonald Jackson" and to get the array you split the string on the "\n" ["Porter Smith", "Jimmy Jones", "Ronald Jackson"]

So to answer the OP's original question too, they could have wrote %(cgi\ spaeinfilename.rb;complex.rb;date.rb).split(';') if there happened to be space when you want the space to exist in the final array output.

Cannot import keras after installation

Firstly checked the list of installed Python packages by:

pip list | grep -i keras

If there is keras shown then install it by:

pip install keras --upgrade --log ./pip-keras.log

now check the log, if there is any pending dependencies are present, it will affect your installation. So remove dependencies and then again install it.

Error: Unfortunately you can't have non-Gradle Java modules and > Android-Gradle modules in one project

  1. Close the project
  2. Just delete the modules.xml in .idea folder.
  3. Open the project again.

Automating the InvokeRequired code pattern

You could write an extension method:

public static void InvokeIfRequired(this Control c, Action<Control> action)
{
    if(c.InvokeRequired)
    {
        c.Invoke(new Action(() => action(c)));
    }
    else
    {
        action(c);
    }
}

And use it like this:

object1.InvokeIfRequired(c => { c.Visible = true; });

EDIT: As Simpzon points out in the comments you could also change the signature to:

public static void InvokeIfRequired<T>(this T c, Action<T> action) 
    where T : Control

Use of alloc init instead of new

Frequently, you are going to need to pass arguments to init and so you will be using a different method, such as [[SomeObject alloc] initWithString: @"Foo"]. If you're used to writing this, you get in the habit of doing it this way and so [[SomeObject alloc] init] may come more naturally that [SomeObject new].

How to get jQuery to wait until an effect is finished?

You can specify a callback function:

$(selector).fadeOut('slow', function() {
    // will be called when the element finishes fading out
    // if selector matches multiple elements it will be called once for each
});

Documentation here.

Skip download if files exist in wget?

The -nc, --no-clobber option isn't the best solution as newer files will not be downloaded. One should use -N instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:

wget -N http://www.example.com/images/misc/pic.png

Then running Wget with -N, with or without -r or -p, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file. -nc may not be specified at the same time as -N.

-N, --timestamping: Turn on time-stamping.

Concatenating strings in C, which method is more efficient?

Don't worry about efficiency: make your code readable and maintainable. I doubt the difference between these methods is going to matter in your program.

Twitter Bootstrap 3, vertically center content

You can use display:inline-block instead of float and vertical-align:middle with this CSS:

.col-lg-4, .col-lg-8 {
    float:none;
    display:inline-block;
    vertical-align:middle;
    margin-right:-4px;
}

The demo http://bootply.com/94402

JBoss default password

The default credentials are:

login: admin
password: admin

But if you use EAP these credentials are turned off by default and there is no active user (security reasons :)). If you want to turn on these users, you have to edit the following file in your current profile: ./deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-users.properties. It should be enough to remove the # sign from the line with the user.

If you want to create a new user, don't forget to set up the correct groups in web-console-roles.properties file.

You can easily find information where these information are stored: just open the ./conf/login-config.xml file and find the proper security domain definition. In the case of the Web Console application, it will be web-console policy.

Also if you want to have access to JMX, you have unlock JMX Console. Just check the following files in the conf/props/ directory (in your profile): jmx-console-users.properties and jmx-console-roles.properties.

how to refresh my datagridview after I add new data

this.tablenameTableAdapter.Fill(this.databasenameDataSet.tablename)

How to convert array values to lowercase in PHP?

If you wish to lowercase all values in an nested array, use the following code:

function nestedLowercase($value) {
    if (is_array($value)) {
        return array_map('nestedLowercase', $value);
    }
    return strtolower($value);
}

So:

[ 'A', 'B', ['C-1', 'C-2'], 'D']

would return:

[ 'a', 'b', ['c-1', 'c-2'], 'd']   

What are the advantages and disadvantages of recursion?

To start:

Pros:

  • It is the unique way of implementing a variable number of nested loops (and the only elegant way of implementing a big constant number of nested loops).

Cons:

  • Recursive methods will often throw a StackOverflowException when processing big sets. Recursive loops don't have this problem though.

Bootstrap Navbar toggle button not working

Demo: http://jsfiddle.net/u1s62Lj8/1/

You need the jQuery and Boostrap Javascript files included in your HTML page for the toggle to work. (Make sure you include jQuery before Bootstrap.)

<html>
   <head>
       // stylesheets here
       <link rel="stylesheet" href=""/> 
   </head>
   <body>
      //your html code here

      // js scripts here
      // note jquery tag has to go before boostrap
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
   </body>
</html>

Quickest way to clear all sheet contents VBA

Try this one:

Sub clear_sht
  Dim sht As Worksheet
  Set sht = Worksheets(GENERATOR_SHT_NAME)
  col_cnt = sht.UsedRange.Columns.count
  If col_cnt = 0 Then
    col_cnt = 1
  End If

  sht.Range(sht.Cells(1, 1), sht.Cells(sht.UsedRange.Rows.count, col_cnt)).Clear
End Sub

Can I set variables to undefined or pass undefined as an argument?

I'm a bit confused about Javascript undefined & null.

null generally behaves similarly to other scripting languages' concepts of the out-of-band ‘null’, ‘nil’ or ‘None’ objects.

undefined, on the other hand, is a weird JavaScript quirk. It's a singleton object that represents out-of-band values, essentially a second similar-but-different null. It comes up:

  1. When you call a function with fewer arguments than the arguments list in the function statement lists, the unpassed arguments are set to undefined. You can test for that with eg.:

    function dosomething(arg1, arg2) {
        if (arg2===undefined)
        arg2= DEFAULT_VALUE_FOR_ARG2;
        ...
    }
    

    With this method you can't tell the difference between dosomething(1) and dosomething(1, undefined); arg2 will be the same value in both. If you need to tell the difference you can look at arguments.length, but doing optional arguments like that isn't generally very readable.

  2. When a function has no return value;, it returns undefined. There's generally no need to use such a return result.

  3. When you declare a variable by having a var a statement in a block, but haven't yet assigned a value to it, it is undefined. Again, you shouldn't really ever need to rely on that.

  4. The spooky typeof operator returns 'undefined' when its operand is a simple variable that does not exist, instead of throwing an error as would normally happen if you tried to refer to it. (You can also give it a simple variable wrapped in parentheses, but not a full expression involving a non-existant variable.) Not much use for that, either.

  5. This is the controversial one. When you access a property of an object which doesn't exist, you don't immediately get an error like in every other language. Instead you get an undefined object. (And then when you try to use that undefined object later on in the script it'll go wrong in a weird way that's much more difficult to track down than if JavaScript had just thrown an error straight away.)

    This is often used to check for the existence of properties:

    if (o.prop!==undefined) // or often as truthiness test, if (o.prop)
       ...do something...
    

    However, because you can assign undefined like any other value:

    o.prop= undefined;
    

    that doesn't actually detect whether the property is there reliably. Better to use the in operator, which wasn't in the original Netscape version of JavaScript, but is available everywhere now:

    if ('prop' in o)
        ...
    

In summary, undefined is a JavaScript-specific mess, which confuses everyone. Apart from optional function arguments, where JS has no other more elegant mechanism, undefined should be avoided. It should never have been part of the language; null would have worked just fine for (2) and (3), and (4) is a misfeature that only exists because in the beginning JavaScript had no exceptions.

what does if (!testvar) actually do? Does it test for undefined and null or just undefined?

Such a ‘truthiness’ test checks against false, undefined, null, 0, NaN and empty strings. But in this case, yes, it is really undefined it is concerned with. IMO, it should be more explicit about that and say if (testvar!==undefined).

once a variable is defined can I clear it back to undefined (therefore deleting the variable).

You can certainly assign undefined to it, but that won't delete the variable. Only the delete object.property operator really removes things.

delete is really meant for properties rather than variables as such. Browsers will let you get away with straight delete variable, but it's not a good idea and won't work in ECMAScript Fifth Edition's strict mode. If you want to free up a reference to something so it can be garbage-collected, it would be more usual to say variable= null.

can I pass undefined as a parameter?

Yes.

Where can I get a list of Ansible pre-defined variables?

Argh! From the FAQ:

How do I see a list of all of the ansible_ variables? Ansible by default gathers “facts” about the machines under management, and these facts can be accessed in Playbooks and in templates. To see a list of all of the facts that are available about a machine, you can run the “setup” module as an ad-hoc action:

ansible -m setup hostname

This will print out a dictionary of all of the facts that are available for that particular host.

Here is the output for my vagrant virtual machine called scdev:

scdev | success >> {
    "ansible_facts": {                                                                                                 
        "ansible_all_ipv4_addresses": [                                                                                
            "10.0.2.15",                                                                                               
            "192.168.10.10"                                                                                            
        ],                                                                                                             
        "ansible_all_ipv6_addresses": [                                                                                
            "fe80::a00:27ff:fe12:9698",                                                                                
            "fe80::a00:27ff:fe74:1330"                                                                                 
        ],                                                                                                             
        "ansible_architecture": "i386",                                                                                
        "ansible_bios_date": "12/01/2006",                                                                             
        "ansible_bios_version": "VirtualBox",                                                                          
        "ansible_cmdline": {                                                                                           
            "BOOT_IMAGE": "/vmlinuz-3.2.0-23-generic-pae",                                                             
            "quiet": true,                                                                                             
            "ro": true,                                                                                                
            "root": "/dev/mapper/precise32-root"                                                                       
        },                                                                                                             
        "ansible_date_time": {                                                                                         
            "date": "2013-09-17",                                                                                      
            "day": "17",                                                                                               
            "epoch": "1379378304",                                                                                     
            "hour": "00",                                                                                              
            "iso8601": "2013-09-17T00:38:24Z",                                                                         
            "iso8601_micro": "2013-09-17T00:38:24.425092Z",                                                            
            "minute": "38",                                                                                            
            "month": "09",                                                                                             
            "second": "24",                                                                                            
            "time": "00:38:24",                                                                                        
            "tz": "UTC",                                                                                               
            "year": "2013"                                                                                             
        },                                                                                                             
        "ansible_default_ipv4": {                                                                                      
            "address": "10.0.2.15",                                                                                    
            "alias": "eth0",                                                                                           
            "gateway": "10.0.2.2",                                                                                     
            "interface": "eth0",                                                                                       
            "macaddress": "08:00:27:12:96:98",                                                                         
            "mtu": 1500,                                                                                               
            "netmask": "255.255.255.0",                                                                                
            "network": "10.0.2.0",                                                                                     
            "type": "ether"                                                                                            
        },                                                                                                             
        "ansible_default_ipv6": {},                                                                                    
        "ansible_devices": {                                                                                           
            "sda": {                                                                                                   
                "holders": [],                                                                                         
                "host": "SATA controller: Intel Corporation 82801HM/HEM (ICH8M/ICH8M-E) SATA Controller [AHCI mode] (rev 02)",                                                                                                                
                "model": "VBOX HARDDISK",                                                                              
                "partitions": {                                                                                        
                    "sda1": {                                                                                          
                        "sectors": "497664",                                                                           
                        "sectorsize": 512,                                                                             
                        "size": "243.00 MB",                                                                           
                        "start": "2048"                                                                                
                    },                                                                                                 
                    "sda2": {                                                                                          
                        "sectors": "2",                                                                                
                        "sectorsize": 512,                                                                             
                        "size": "1.00 KB",                                                                             
                        "start": "501758"                                                                              
                    },                                                                                                 
                },                                                                                                     
                "removable": "0",                                                                                      
                "rotational": "1",                                                                                     
                "scheduler_mode": "cfq",                                                                               
                "sectors": "167772160",                                                                                
                "sectorsize": "512",                                                                                   
                "size": "80.00 GB",                                                                                    
                "support_discard": "0",                                                                                
                "vendor": "ATA"                                                                                        
            },                                                                                                         
            "sr0": {                                                                                                   
                "holders": [],                                                                                         
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",                           
                "model": "CD-ROM",                                                                                     
                "partitions": {},                                                                                      
                "removable": "1",                                                                                      
                "rotational": "1",                                                                                     
                "scheduler_mode": "cfq",                                                                               
                "sectors": "2097151",                                                                                  
                "sectorsize": "512",                                                                                   
                "size": "1024.00 MB",                                                                                  
                "support_discard": "0",                                                                                
                "vendor": "VBOX"                                                                                       
            },                                                                                                         
            "sr1": {                                                                                                   
                "holders": [],                                                                                         
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",                           
                "model": "CD-ROM",                                                                                     
                "partitions": {},                                                                                      
                "removable": "1",                                                                                      
                "rotational": "1",                                                                                     
                "scheduler_mode": "cfq",                                                                               
                "sectors": "2097151",                                                                                  
                "sectorsize": "512",                                                                                   
                "size": "1024.00 MB",                                                                                  
                "support_discard": "0",                                                                                
                "vendor": "VBOX"                                                                                       
            }                                                                                                          
        },                                                                                                             
        "ansible_distribution": "Ubuntu",                                                                              
        "ansible_distribution_release": "precise",                                                                     
        "ansible_distribution_version": "12.04",                                                                       
        "ansible_domain": "",                                                                                          
        "ansible_eth0": {                                                                                              
            "active": true,                                                                                            
            "device": "eth0",                                                                                          
            "ipv4": {                                                                                                  
                "address": "10.0.2.15",                                                                                
                "netmask": "255.255.255.0",                                                                            
                "network": "10.0.2.0"                                                                                  
            },                                                                                                         
            "ipv6": [                                                                                                  
                {                                                                                                      
                    "address": "fe80::a00:27ff:fe12:9698",                                                             
                    "prefix": "64",                                                                                    
                    "scope": "link"                                                                                    
                }                                                                                                      
            ],                                                                                                         
            "macaddress": "08:00:27:12:96:98",                                                                         
            "module": "e1000",                                                                                         
            "mtu": 1500,                                                                                               
            "type": "ether"                                                                                            
        },                                                                                                             
        "ansible_eth1": {                                                                                              
            "active": true,                                                                                            
            "device": "eth1",                                                                                          
            "ipv4": {                                                                                                  
                "address": "192.168.10.10",                                                                            
                "netmask": "255.255.255.0",                                                                            
                "network": "192.168.10.0"                                                                              
            },                                                                                                         
            "ipv6": [                                                                                                  
                {                                                                                                      
                    "address": "fe80::a00:27ff:fe74:1330",                                                             
                    "prefix": "64",                                                                                    
                    "scope": "link"                                                                                    
                }                                                                                                      
            ],                                                                                                         
            "macaddress": "08:00:27:74:13:30",                                                                         
            "module": "e1000",                                                                                         
            "mtu": 1500,                                                                                               
            "type": "ether"                                                                                            
        },                                                                                                             
        "ansible_form_factor": "Other",                                                                                
        "ansible_fqdn": "scdev",                                                                                       
        "ansible_hostname": "scdev",                                                                                   
        "ansible_interfaces": [                                                                                        
            "lo",                                                                                                      
            "eth1",                                                                                                    
            "eth0"                                                                                                     
        ],                                                                                                             
        "ansible_kernel": "3.2.0-23-generic-pae",                                                                      
        "ansible_lo": {                                                                                                
            "active": true,                                                                                            
            "device": "lo",                                                                                            
            "ipv4": {                                                                                                  
                "address": "127.0.0.1",                                                                                
                "netmask": "255.0.0.0",                                                                                
                "network": "127.0.0.0"                                                                                 
            },                                                                                                         
            "ipv6": [                                                                                                  
                {                                                                                                      
                    "address": "::1",                                                                                  
                    "prefix": "128",                                                                                   
                    "scope": "host"                                                                                    
                }                                                                                                      
            ],                                                                                                         
            "mtu": 16436,                                                                                              
            "type": "loopback"                                                                                         
        },                                                                                                             
        "ansible_lsb": {                                                                                               
            "codename": "precise",                                                                                     
            "description": "Ubuntu 12.04 LTS",                                                                         
            "id": "Ubuntu",                                                                                            
            "major_release": "12",                                                                                     
            "release": "12.04"                                                                                         
        },                                                                                                             
        "ansible_machine": "i686",                                                                                     
        "ansible_memfree_mb": 23,                                                                                      
        "ansible_memtotal_mb": 369,                                                                                    
        "ansible_mounts": [                                                                                            
            {                                                                                                          
                "device": "/dev/mapper/precise32-root",                                                                
                "fstype": "ext4",                                                                                      
                "mount": "/",                                                                                          
                "options": "rw,errors=remount-ro",                                                                     
                "size_available": 77685088256,                                                                         
                "size_total": 84696281088                                                                              
            },                                                                                                         
            {                                                                                                          
                "device": "/dev/sda1",                                                                                 
                "fstype": "ext2",                                                                                      
                "mount": "/boot",                                                                                      
                "options": "rw",                                                                                       
                "size_available": 201044992,                                                                           
                "size_total": 238787584                                                                                
            },                                                                                                         
            {                                                                                                          
                "device": "/vagrant",                                                                                  
                "fstype": "vboxsf",                                                                                    
                "mount": "/vagrant",                                                                                   
                "options": "uid=1000,gid=1000,rw",                                                                     
                "size_available": 42013151232,                                                                         
                "size_total": 484145360896                                                                             
            }                                                                                                          
        ],                                                                                                             
        "ansible_os_family": "Debian",                                                                                 
        "ansible_pkg_mgr": "apt",                                                                                      
        "ansible_processor": [                                                                                         
            "Pentium(R) Dual-Core  CPU      E5300  @ 2.60GHz"                                                          
        ],                                                                                                             
        "ansible_processor_cores": "NA",                                                                               
        "ansible_processor_count": 1,                                                                                  
        "ansible_product_name": "VirtualBox",                                                                          
        "ansible_product_serial": "NA",                                                                                
        "ansible_product_uuid": "NA",                                                                                  
        "ansible_product_version": "1.2",                                                                              
        "ansible_python_version": "2.7.3", 
        "ansible_selinux": false, 
        "ansible_swapfree_mb": 766, 
        "ansible_swaptotal_mb": 767, 
        "ansible_system": "Linux", 
        "ansible_system_vendor": "innotek GmbH", 
        "ansible_user_id": "neves", 
        "ansible_userspace_architecture": "i386", 
        "ansible_userspace_bits": "32", 
        "ansible_virtualization_role": "guest", 
        "ansible_virtualization_type": "virtualbox"
    }, 
    "changed": false
}

The current documentation now has a complete chapter listing all Variables and Facts

Found conflicts between different versions of the same dependent assembly that could not be resolved

VS 2017, MVC project

I don't know why, but for me, the solution for this issue was to remove an out parameter from a model method signature that was called from the controller action method. that is very strange behaviour but that was the solution to my problem.

Easiest way to rotate by 90 degrees an image using OpenCV?

Here's my EmguCV (a C# port of OpenCV) solution:

public static Image<TColor, TDepth> Rotate90<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static Image<TColor, TDepth> Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = img.CopyBlank();
    rot = img.Flip(FLIP.VERTICAL);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static void _Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    img._Flip(FLIP.VERTICAL);
    img._Flip(FLIP.HORIZONTAL);
}

public static Image<TColor, TDepth> Rotate270<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.VERTICAL);
    return rot;
}

Shouldn't be too hard to translate it back into C++.

How to change to an older version of Node.js

Another good library for managing multiple versions of Node is N: https://github.com/visionmedia/n

Remove insignificant trailing zeros from a number?

I had the basically the same requirement, and found that there is no built-in mechanism for this functionality.

In addition to trimming the trailing zeros, I also had the need to round off and format the output for the user's current locale (i.e. 123,456.789).

All of my work on this has been included as prettyFloat.js (MIT Licensed) on GitHub: https://github.com/dperish/prettyFloat.js


Usage Examples:

prettyFloat(1.111001, 3) // "1.111"
prettyFloat(1.111001, 4) // "1.111"
prettyFloat(1.1111001, 5) // "1.1111"
prettyFloat(1234.5678, 2) // "1234.57"
prettyFloat(1234.5678, 2, true) // "1,234.57" (en-us)


Updated - August, 2018


All modern browsers now support the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.

let formatters = {
    default: new Intl.NumberFormat(),
    currency: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    whole: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    oneDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 1, maximumFractionDigits: 1 }),
    twoDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 })
};

formatters.twoDecimal.format(1234.5678);  // result: "1,234.57"
formatters.currency.format(28761232.291); // result: "$28,761,232"

For older browsers, you can use this polyfill: https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en

How to output HTML from JSP <%! ... %> block?

You can do something like this:

<%

out.print("<p>Hey!</p>");    
out.print("<p>How are you?</p>");

%>

How do I test if a recordSet is empty? isNull?

If temp_rst1.BOF and temp_rst1.EOF then the recordset is empty. This will always be true for an empty recordset, linked or local.

How to get longitude and latitude of any address?

You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.

How to enable NSZombie in Xcode?

It's a simple matter of setting an environment variable on your executable (NSZombieEnabled = YES), and then running/debugging your app as normal.If you message a zombie, your app will crash/break to debugger and NSLog a message for you.

For more information, check out this CocoaDev page: http://www.cocoadev.com/index.pl?NSZombieEnabled

Also, this process will become much easier with the release of 10.6 and the next versions of Xcode and Instruments. Just saying'. =)

Copying PostgreSQL database to another server

Let me share a Linux shell script to copy your table data from one server to another PostgreSQL server.

Reference taken from this blog:

Linux Bash Shell Script for data migration between PostgreSQL Servers:

#!/bin/bash
psql \
    -X \
    -U user_name \
    -h host_name1 \
    -d database_name \
    -c "\\copy tbl_Students to stdout" \
| \
psql \
    -X \
    -U user_name \
    -h host_name2 \
    -d database_name \
    -c "\\copy tbl_Students from stdin"

I am just migrating the data; please create a blank table at your destination/second database server.

This is a utility script. Further, you can modify the script for generic use something like by adding parameters for host_name, database_name, table_name and others

Notice: Array to string conversion in

Even simpler:

$get = @mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");

note the quotes around username in the $_SESSION reference.

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

Apply CSS to jQuery Dialog Buttons

Select the div which has role dialog then get the appropriate buttons in it and set the CSS.

$("div[role=dialog] button:contains('Save')").css("color", "green");
$("div[role=dialog] button:contains('Cancel')").css("color", "red"); 

How do I enable --enable-soap in php on linux?

In case that you have Ubuntu in your machine, the following steps will help you:

  1. Check first in your php testing file if you have soap (client / server)or not by using phpinfo(); and check results in the browser. In case that you have it, it will seems like the following image ( If not go to step 2 ):

enter image description here

  1. Open your terminal and paste: sudo apt-get install php-soap.

  2. Restart your apache2 server in terminal : service apache2 restart.

  3. To check use your php test file again to be seems like mine in step 1.

How do I add an element to array in reducer of React native redux?

push does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:

import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {

    arr:[]
}

export default function userState(state = initialUserState, action){
     console.log(arr);
     switch (action.type){
        case ADD_ITEM :
          return { 
             ...state,
             arr:[...state.arr, action.newItem]
        }

        default:return state
     }
}

How to set maximum height for table-cell?

In css you can't set table-cells max height, and if you white-space nowrap then you can't break it with max width, so the solution is javascript working in all browsers.

So, this can work for you.

For Limiting max-height of all cells or rows in table with Javascript:

This script is good for horizontal overflow tables.

This script increase the table width 300px each time, maximum 4000px until rows shrinks to max-height(160px) , and you can also edit numbers as your need.

var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
while (row = table.rows[i++]) {
    while (row.offsetHeight > 160 && j < 4000) {
        j += 300;
        table.style.width = j + 'px';
    }
}

Source: HTML Table Solution Max Height Limit For Rows Or Cells By Increasing Table Width, Javascript

Accessing certain pixel RGB value in openCV

const double pi = boost::math::constants::pi<double>();

cv::Mat distance2ellipse(cv::Mat image, cv::RotatedRect ellipse){
    float distance = 2.0f;
    float angle = ellipse.angle;
    cv::Point ellipse_center = ellipse.center;
    float major_axis = ellipse.size.width/2;
    float minor_axis = ellipse.size.height/2;
    cv::Point pixel;
    float a,b,c,d;

    for(int x = 0; x < image.cols; x++)
    {
        for(int y = 0; y < image.rows; y++) 
        {
        auto u =  cos(angle*pi/180)*(x-ellipse_center.x) + sin(angle*pi/180)*(y-ellipse_center.y);
        auto v = -sin(angle*pi/180)*(x-ellipse_center.x) + cos(angle*pi/180)*(y-ellipse_center.y);

        distance = (u/major_axis)*(u/major_axis) + (v/minor_axis)*(v/minor_axis);  

        if(distance<=1)
        {
            image.at<cv::Vec3b>(y,x)[1] = 255;
        }
      }
  }
  return image;  
}

Get unicode value of a character

char c = 'a';
String a = Integer.toHexString(c); // gives you---> a = "61"

Moving Panel in Visual Studio Code to right side

I don't know since which version it change but the 1.11.2 has an option in View tab which can change the left bar to the right and vice versa

ComboBox.SelectedText doesn't give me the SelectedText

All of the previous answers explain what the OP 'should' do. I am explaining what the .SelectedText property is.

The .SelectedText property is not the text in the combobox. It is the text that is highlighted. It is the same as .SelectedText property for a textbox.

The following picture shows that the .SelectedText property would be equal to "ort".

enter image description here

How do I make bootstrap table rows clickable?

<tr height="70" onclick="location.href='<%=site_adres2 & urun_adres%>'"
    style="cursor:pointer;">

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

Short answer (asked version): (format 3.33.20150710.182906)

Please, simple use a makefile with:

MAJOR = 3
MINOR = 33
BUILD = $(shell date +"%Y%m%d.%H%M%S")
VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
CPPFLAGS = -DVERSION=$(VERSION)

program.x : source.c
       gcc $(CPPFLAGS) source.c -o program.x

and if you don't want a makefile, shorter yet, just compile with:

gcc source.c -o program.x -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Short answer (suggested version): (format 150710.182906)

Use a double for version number:

MakeFile:

VERSION = $(shell date +"%g%m%d.%H%M%S")
CPPFLAGS = -DVERSION=$(VERSION)
program.x : source.c
      gcc $(CPPFLAGS) source.c -o program.x

Or a simple bash command:

$ gcc source.c -o program.x -DVERSION=$(date +"%g%m%d.%H%M%S")

Tip: Still don't like makefile or is it just for a not-so-small test program? Add this line:

 export CPPFLAGS='-DVERSION='$(date +"%g%m%d.%H%M%S")

to your ~/.profile, and remember compile with gcc $CPPFLAGS ...


Long answer:

I know this question is older, but I have a small contribution to make. Best practice is always automatize what otherwise can became a source of error (or oblivion).

I was used to a function that created the version number for me. But I prefer this function to return a float. My version number can be printed by: printf("%13.6f\n", version()); which issues something like: 150710.150411 (being Year (2 digits) month day DOT hour minute seconds).

But, well, the question is yours. If you prefer "major.minor.date.time", it will have to be a string. (Trust me, double is better. If you insist in a major, you can still use double if you set the major and let the decimals to be date+time, like: major.datetime = 1.150710150411

Lets get to business. The example bellow will work if you compile as usual, forgetting to set it, or use -DVERSION to set the version directly from shell, but better of all, I recommend the third option: use a makefile.


Three forms of compiling and the results:

Using make:

beco> make program.x
gcc -Wall -Wextra -g -O0 -ansi -pedantic-errors -c -DVERSION="\"3.33.20150710.045829\"" program.c -o program.o
gcc  program.o -o program.x

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:29'
VERSION: '3.33.20150710.045829'

Using -DVERSION:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:37'
VERSION: '2.22.20150710.045837'

Using the build-in function:

beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors

Running:

__DATE__: 'Jul 10 2015'
__TIME__: '04:58:43'
VERSION(): '1.11.20150710.045843'

Source code

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 
  5 #define FUNC_VERSION (0)
  6 #ifndef VERSION
  7   #define MAJOR 1
  8   #define MINOR 11
  9   #define VERSION version()
 10   #undef FUNC_VERSION
 11   #define FUNC_VERSION (1)
 12   char sversion[]="9999.9999.20150710.045535";
 13 #endif
 14 
 15 #if(FUNC_VERSION)
 16 char *version(void);
 17 #endif
 18 
 19 int main(void)
 20 {
 21 
 22   printf("__DATE__: '%s'\n", __DATE__);
 23   printf("__TIME__: '%s'\n", __TIME__);
 24 
 25   printf("VERSION%s: '%s'\n", (FUNC_VERSION?"()":""), VERSION);
 26   return 0;
 27 }
 28 
 29 /* String format: */
 30 /* __DATE__="Oct  8 2013" */
 31 /*  __TIME__="00:13:39" */
 32
 33 /* Version Function: returns the version string */
 34 #if(FUNC_VERSION)
 35 char *version(void)
 36 {
 37   const char data[]=__DATE__;
 38   const char tempo[]=__TIME__;
 39   const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
 40   char omes[4];
 41   int ano, mes, dia, hora, min, seg;
 42 
 43   if(strcmp(sversion,"9999.9999.20150710.045535"))
 44     return sversion;
 45 
 46   if(strlen(data)!=11||strlen(tempo)!=8)
 47     return NULL;
 48 
 49   sscanf(data, "%s %d %d", omes, &dia, &ano);
 50   sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
 51   mes=(strstr(nomes, omes)-nomes)/3+1;
 52   sprintf(sversion,"%d.%d.%04d%02d%02d.%02d%02d%02d", MAJOR, MINOR, ano, mes, dia, hora, min, seg);
 53 
 54   return sversion;
 55 }
 56 #endif

Please note that the string is limited by MAJOR<=9999 and MINOR<=9999. Of course, I set this high value that will hopefully never overflow. But using double is still better (plus, it's completely automatic, no need to set MAJOR and MINOR by hand).

Now, the program above is a bit too much. Better is to remove the function completely, and guarantee that the macro VERSION is defined, either by -DVERSION directly into GCC command line (or an alias that automatically add it so you can't forget), or the recommended solution, to include this process into a makefile.

Here it is the makefile I use:


MakeFile source:

  1   MAJOR = 3
  2   MINOR = 33
  3   BUILD = $(shell date +"%Y%m%d.%H%M%S")
  4   VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
  5   CC = gcc
  6   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors
  7   CPPFLAGS = -DVERSION=$(VERSION)
  8   LDLIBS =
  9   
 10    %.x : %.c
 11          $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

A better version with DOUBLE

Now that I presented you "your" preferred solution, here it is my solution:

Compile with (a) makefile or (b) gcc directly:

(a) MakeFile:

   VERSION = $(shell date +"%g%m%d.%H%M%S")
   CC = gcc
   CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors 
   CPPFLAGS = -DVERSION=$(VERSION)
   LDLIBS =
   %.x : %.c
         $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@

(b) Or a simple bash command:

 $ gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=$(date +"%g%m%d.%H%M%S")

Source code (double version):

#ifndef VERSION
  #define VERSION version()
#endif

double version(void);

int main(void)
{
  printf("VERSION%s: '%13.6f'\n", (FUNC_VERSION?"()":""), VERSION);
  return 0;
}

double version(void)
{
  const char data[]=__DATE__;
  const char tempo[]=__TIME__;
  const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
  char omes[4];
  int ano, mes, dia, hora, min, seg;
  char sversion[]="130910.001339";
  double fv;

  if(strlen(data)!=11||strlen(tempo)!=8)
    return -1.0;

  sscanf(data, "%s %d %d", omes, &dia, &ano);
  sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
  mes=(strstr(nomes, omes)-nomes)/3+1;
  sprintf(sversion,"%04d%02d%02d.%02d%02d%02d", ano, mes, dia, hora, min, seg);
  fv=atof(sversion);

  return fv;
}

Note: this double function is there only in case you forget to define macro VERSION. If you use a makefile or set an alias gcc gcc -DVERSION=$(date +"%g%m%d.%H%M%S"), you can safely delete this function completely.


Well, that's it. A very neat and easy way to setup your version control and never worry about it again!

From ND to 1D arrays

I wanted to see a benchmark result of functions mentioned in answers including unutbu's.

Also want to point out that numpy doc recommend to use arr.reshape(-1) in case view is preferable. (even though ravel is tad faster in the following result)


TL;DR: np.ravel is the most performant (by very small amount).

Benchmark

Functions:

numpy version: '1.18.0'

Execution times on different ndarray sizes

+-------------+----------+-----------+-----------+-------------+
|  function   |   10x10  |  100x100  | 1000x1000 | 10000x10000 |
+-------------+----------+-----------+-----------+-------------+
| ravel       | 0.002073 |  0.002123 |  0.002153 |    0.002077 |
| reshape(-1) | 0.002612 |  0.002635 |  0.002674 |    0.002701 |
| flatten     | 0.000810 |  0.007467 |  0.587538 |  107.321913 |
| flat        | 0.000337 |  0.000255 |  0.000227 |    0.000216 |
+-------------+----------+-----------+-----------+-------------+

Conclusion

ravel and reshape(-1)'s execution time was consistent and independent from ndarray size. However, ravel is tad faster, but reshape provides flexibility in reshaping size. (maybe that's why numpy doc recommend to use it instead. Or there could be some cases where reshape returns view and ravel doesn't).
If you are dealing with large size ndarray, using flatten can cause a performance issue. Recommend not to use it. Unless you need a copy of the data to do something else.

Used code

import timeit
setup = '''
import numpy as np
nd = np.random.randint(10, size=(10, 10))
'''

timeit.timeit('nd = np.reshape(nd, -1)', setup=setup, number=1000)
timeit.timeit('nd = np.ravel(nd)', setup=setup, number=1000)
timeit.timeit('nd = nd.flatten()', setup=setup, number=1000)
timeit.timeit('nd.flat', setup=setup, number=1000)

Cleanest way to toggle a boolean variable in Java?

If you use Boolean NULL values and consider them false, try this:

static public boolean toggle(Boolean aBoolean) {
    if (aBoolean == null) return true;
    else return !aBoolean;
}

If you are not handing Boolean NULL values, try this:

static public boolean toggle(boolean aBoolean) {
   return !aBoolean;
}

These are the cleanest because they show the intent in the method signature, are easier to read compared to the ! operator, and can be easily debugged.

Usage

boolean bTrue = true
boolean bFalse = false
boolean bNull = null

toggle(bTrue) // == false
toggle(bFalse) // == true
toggle(bNull) // == true

Of course, if you use Groovy or a language that allows extension methods, you can register an extension and simply do:

Boolean b = false
b = b.toggle() // == true

How to modify memory contents using GDB?

As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20

This should work for any valid pointer, and can be cast to any appropriate data type.

Align Div at bottom on main Div

Modify your CSS like this:

_x000D_
_x000D_
.vertical_banner {_x000D_
    border: 1px solid #E9E3DD;_x000D_
    float: left;_x000D_
    height: 210px;_x000D_
    margin: 2px;_x000D_
    padding: 4px 2px 10px 10px;_x000D_
    text-align: left;_x000D_
    width: 117px;_x000D_
    position:relative;_x000D_
}_x000D_
_x000D_
#bottom_link{_x000D_
   position:absolute;                  /* added */_x000D_
   bottom:0;                           /* added */_x000D_
   left:0;                           /* added */_x000D_
}
_x000D_
<div class="vertical_banner">_x000D_
    <div id="bottom_link">_x000D_
         <input type="submit" value="Continue">_x000D_
       </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check the version of GitLab?

The easiest way is to paste the following command:

cat /opt/gitlab/version-manifest.txt | head -n 1

and there you get the version installed. :)

Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

How to execute a Ruby script in Terminal?

Assuming ruby interpreter is in your PATH (it should be), you simply run

ruby your_file.rb

Activity transition in Android

IN GALAXY Devices :

You need to make sure that you havn't turned it off in the device using the Settings > Developer Options:

two muppets

docker cannot start on windows

If none of the other answers work for you, try this: Open up a terminal and run:

wsl -l -v 

If you notice that there's a docker-desktop left hanging in the 'Installing' state, close Docker, run powershell as adminstrator and unregister docker-desktop:

PS C:\WINDOWS\system32> .\wslconfig.exe /u docker-desktop

Restart docker and hopefully it works. If it doesn't, try uninstalling docker first, then unregistering docker-desktop, and re-installing Docker.

Source: https://github.com/docker/for-win/issues/7295#issuecomment-645989416

What's the difference between '$(this)' and 'this'?

$() is the jQuery constructor function.

this is a reference to the DOM element of invocation.

So basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

Spring boot: Unable to start embedded Tomcat servlet container

For me, the problem was in XML migrations. I deleted all tables and sequences and it works on next bootRun

Eclipse/Java code completion not working

If you're experiencing this in an enum, or when initializing an array with anonymous classes, it's a known bug in Eclipse. See Eclipse content assist not working in enum constant parameter list.

Delete directories recursively in Java

One-liner solution (Java8) to delete all files and directories recursively including starting directory:

Files.walk(Paths.get("c:/dir_to_delete/"))
                .map(Path::toFile)
                .sorted((o1, o2) -> -o1.compareTo(o2))
                .forEach(File::delete);

We use a comparator for reversed order, otherwise File::delete won't be able to delete possibly non-empty directory. So, if you want to keep directories and only delete files just remove the comparator in sorted() or remove sorting completely and add files filter:

Files.walk(Paths.get("c:/dir_to_delete/"))
                .filter(Files::isRegularFile)
                .map(Path::toFile)
                .forEach(File::delete);

A long bigger than Long.MAX_VALUE

You can't. If you have a method called isBiggerThanMaxLong(long) it should always return false.

If you were to increment the bits of Long.MAX_VALUE, the next value should be Long.MIN_VALUE. Read up on twos-complement and that should tell you why.

How to use std::sort to sort an array in C++

It is as simple as that ... C++ is providing you a function in STL (Standard Template Library) called sort which runs 20% to 50% faster than the hand-coded quick-sort.

Here is the sample code for it's usage:

std::sort(arr, arr + size);

How do I upload a file to an SFTP server in C# (.NET)?

For another un-free option try edtFTPnet/PRO. It has comprehensive support for SFTP, and also supports FTPS (and of course FTP) if required.

How to get the home directory in Python?

I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

Code:

import os
print(os.path.expanduser("~"))

Output Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

Output Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

I also tested it on Python 2.7.17 and that works too.

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

How do I convert from stringstream to string in C++?

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...

Pycharm and sys.argv arguments

It works in the edu version for me. It was not necessary for me to specify a -s option in the interpreter options.

Pycharm parameters for running with command line

How to call an async method from a getter or setter?

I review all answer but all have a performance issue.

for example in :

string _Title;
public string Title
{
    get
    {
        if (_Title == null)
        {   
            Deployment.Current.Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });
        }
        return _Title;
    }
    set
    {
        if (value != _Title)
        {
            _Title = value;
            RaisePropertyChanged("Title");
        }
    }
}

Deployment.Current.Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });

use dispatcher which is not a good answer.

but there is a simple solution, just do it:

string _Title;
    public string Title
    {
        get
        {
            if (_Title == null)
            {   
                Task.Run(()=> 
                {
                    _Title = getTitle();
                    RaisePropertyChanged("Title");
                });        
                return;
            }
            return _Title;
        }
        set
        {
            if (value != _Title)
            {
                _Title = value;
                RaisePropertyChanged("Title");
            }
        }
    }

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

I had a similar issue, also seeing "Failed to load resource: net::ERR_CONTENT_DECODING_FAILED" and "ILLEGAL TOKEN" errors when loading JS files locally. Pressing CTRL+SHIFT+DEL and deleting all "Cookies and other site and plugin data" and "Cached images and files" fixed it.

How to open my files in data_folder with pandas using relative path?

Try

import pandas as pd
pd.read_csv("../data_folder/data.csv")

"Permission Denied" trying to run Python on Windows 10

For me, I tried manage app execution aliases and got an error that python3 is not a command so for that, I used py instead of python3 and it worked

I don't know why this is happening but It worked for me

Android Color Picker

We have just uploaded AmbilWarna color picker to Maven:

https://github.com/yukuku/ambilwarna

It can be used either as a dialog or as a Preference entry.

enter image description here

Capture event onclose browser

Events onunload or onbeforeunload you can't use directly - they do not differ between window close, page refresh, form submit, link click or url change.

The only working solution is How to capture the browser window close event?

Check whether a cell contains a substring

For those who would like to do this using a single function inside the IF statement, I use

=IF(COUNTIF(A1,"*TEXT*"),TrueValue,FalseValue)

to see if the substring TEXT is in cell A1

[NOTE: TEXT needs to have asterisks around it]

What is WebKit and how is it related to CSS?

A good documentation about WebEngines especially webKit and its developers you can read at: WebKit

Unable to connect to any of the specified mysql hosts. C# MySQL

Sometime the problem could be on your windows firewall, make sure your server allow access to all port associated with your mysql database.

How to decode JWT Token?

Using .net core jwt packages, the Claims are available:

[Route("api/[controller]")]
[ApiController]
[Authorize(Policy = "Bearer")]
public class AbstractController: ControllerBase
{
    protected string UserId()
    {
        var principal = HttpContext.User;
        if (principal?.Claims != null)
        {
            foreach (var claim in principal.Claims)
            {
               log.Debug($"CLAIM TYPE: {claim.Type}; CLAIM VALUE: {claim.Value}");
            }

        }
        return principal?.Claims?.SingleOrDefault(p => p.Type == "username")?.Value;
    }
}

Finding diff between current and last version

I use Bitbucket with the Eclipse IDE with the Eclipse EGit plugin installed.

I compare a file from any version of its history (like SVN).

Menu Project Explorer → File → right click → TeamShow in history.

This will bring the history of all changes on that file. Now Ctrl click and select any two versions→ "Compare with each other".

What is the backslash character (\\)?

It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.

e.g.

System.out.println("printing \"this\" in quotes");

outputs

printing "this" in quotes

Multipart forms from C# client

Below is the code which I'm using

    //This URL not exist, it's only an example.
    string url = "http://myBox.s3.amazonaws.com/";
    //Instantiate new CustomWebRequest class
    CustomWebRequest wr = new CustomWebRequest(url);
    //Set values for parameters
    wr.ParamsCollection.Add(new ParamsStruct("key", "${filename}"));
    wr.ParamsCollection.Add(new ParamsStruct("acl", "public-read"));
    wr.ParamsCollection.Add(new ParamsStruct("success_action_redirect", "http://www.yahoo.com"));
    wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-uuid", "14365123651274"));
    wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-tag", ""));
    wr.ParamsCollection.Add(new ParamsStruct("AWSAccessKeyId", "zzzz"));            
    wr.ParamsCollection.Add(new ParamsStruct("Policy", "adsfadsf"));
    wr.ParamsCollection.Add(new ParamsStruct("Signature", "hH6lK6cA="));
    //For file type, send the inputstream of selected file
    StreamReader sr = new StreamReader(@"file.txt");
    wr.ParamsCollection.Add(new ParamsStruct("file", sr, ParamsStruct.ParamType.File, "file.txt"));

    wr.PostData();

from the following link I've downloaded the same code http://www.codeproject.com/KB/cs/multipart_request_C_.aspx

Any Help

Find Java classes implementing an interface

If you were asking from the perspective of working this out with a running program then you need to look to the java.lang.* package. If you get a Class object, you can use the isAssignableFrom method to check if it is an interface of another Class.

There isn't a simple built in way of searching for these, tools like Eclipse build an index of this information.

If you don't have a specific list of Class objects to test you can look to the ClassLoader object, use the getPackages() method and build your own package hierarchy iterator.

Just a warning though that these methods and classes can be quite slow.

Count the number occurrences of a character in a string

I know the ask is to count a particular letter. I am writing here generic code without using any method.

sentence1 =" Mary had a little lamb"
count = {}
for i in sentence1:
    if i in count:
        count[i.lower()] = count[i.lower()] + 1
    else:
        count[i.lower()] = 1
print(count)

output

{' ': 5, 'm': 2, 'a': 4, 'r': 1, 'y': 1, 'h': 1, 'd': 1, 'l': 3, 'i': 1, 't': 2, 'e': 1, 'b': 1}

Now if you want any particular letter frequency, you can print like below.

print(count['m'])
2

Generating statistics from Git repository

Beside GitStats (git history statistics generator) mentioned by xyld, written in Python and requiring Gnuplot for graphs, there is also

Creating a random string with A-Z and 0-9 in Java

Here you can use my method for generating Random String

protected String getSaltString() {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();
        while (salt.length() < 18) { // length of the random string.
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        String saltStr = salt.toString();
        return saltStr;

    }

The above method from my bag using to generate a salt string for login purpose.