Programs & Examples On #Scalatest

The Scala testing framework

ScalaTest in sbt: is there a way to run a single test without tags?

I don't see a way to run a single untagged test within a test class but I am providing my workflow since it seems to be useful for anyone who runs into this question.

From within a sbt session:

test:testOnly *YourTestClass

(The asterisk is a wildcard, you could specify the full path com.example.specs.YourTestClass.)

All tests within that test class will be executed. Presumably you're most concerned with failing tests, so correct any failing implementations and then run:

test:testQuick

... which will only execute tests that failed. (Repeating the most recently executed test:testOnly command will be the same as test:testQuick in this case, but if you break up your test methods into appropriate test classes you can use a wildcard to make test:testQuick a more efficient way to re-run failing tests.)

Note that the nomenclature for test in ScalaTest is a test class, not a specific test method, so all untagged methods are executed.

If you have too many test methods in a test class break them up into separate classes or tag them appropriately. (This could be a signal that the class under test is in violation of single responsibility principle and could use a refactoring.)

What is the hamburger menu icon called and the three vertical dots icon called?

For the 3 vertical dot icon, these are the most popular names

  • Kebab menu
  • More options icon

For the remaining, here is the list.

Picture Credit- @MichaelBabich

What does CultureInfo.InvariantCulture mean?

When numbers, dates and times are formatted into strings or parsed from strings a culture is used to determine how it is done. E.g. in the dominant en-US culture you have these string representations:

  • 1,000,000.00 - one million with a two digit fraction
  • 1/29/2013 - date of this posting

In my culture (da-DK) the values have this string representation:

  • 1.000.000,00 - one million with a two digit fraction
  • 29-01-2013 - date of this posting

In the Windows operating system the user may even customize how numbers and date/times are formatted and may also choose another culture than the culture of his operating system. The formatting used is the choice of the user which is how it should be.

So when you format a value to be displayed to the user using for instance ToString or String.Format or parsed from a string using DateTime.Parse or Decimal.Parse the default is to use the CultureInfo.CurrentCulture. This allows the user to control the formatting.

However, a lot of string formatting and parsing is actually not strings exchanged between the application and the user but between the application and some data format (e.g. an XML or CSV file). In that case you don't want to use CultureInfo.CurrentCulture because if formatting and parsing is done with different cultures it can break. In that case you want to use CultureInfo.InvariantCulture (which is based on the en-US culture). This ensures that the values can roundtrip without problems.

The reason that ReSharper gives you the warning is that some application writers are unaware of this distinction which may lead to unintended results but they never discover this because their CultureInfo.CurrentCulture is en-US which has the same behavior as CultureInfo.InvariantCulture. However, as soon as the application is used in another culture where there is a chance of using one culture for formatting and another for parsing the application may break.

So to sum it up:

  • Use CultureInfo.CurrentCulture (the default) if you are formatting or parsing a user string.
  • Use CultureInfo.InvariantCulture if you are formatting or parsing a string that should be parseable by a piece of software.
  • Rarely use a specific national culture because the user is unable to control how formatting and parsing is done.

Dynamic Web Module 3.0 -- 3.1

I had similar troubles in eclipse and the only way to fix it for me was to

  • Remove the web module
  • Apply
  • Change the module version
  • Add the module
  • Configure (Further configuration available link at the bottom of the dialog)
  • Apply

Just make sure you configure the web module before applying it as by default it will look for your web files in /WebContent/ and this is not what Maven project structure should be.

EDIT:

Here is a second way in case nothing else helps

  • Exit eclipse, go to your project in the file system, then to .settings folder.
  • Open the org.eclipse.wst.common.project.facet.core.xml , make backup, and remove the web module entry.
  • You can also modify the web module version there, but again, no guarantees.

How to find all occurrences of an element in a list

If you are using Python 2, you can achieve the same functionality with this:

f = lambda my_list, value:filter(lambda x: my_list[x] == value, range(len(my_list)))

Where my_list is the list you want to get the indexes of, and value is the value searched. Usage:

f(some_list, some_element)

Scrollbar without fixed height/Dynamic height with scrollbar

Flexbox is a modern alternative that lets you do this without fixed heights or JavaScript.

Setting display: flex; flex-direction: column; on the container and flex-shrink: 0; on the header and footer divs does the trick:

HTML:

<div id="body">
    <div id="head">
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>  
    </div>
    <div id="content">
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
    </div>
    <div id="foot">
        <p>Fixed size without scrollbar</p>
        <p>Fixed size without scrollbar</p>
    </div>  
</div>

CSS:

#body {
    position: absolute;
    top: 150px;
    left: 150px;
    height: 300px;
    width: 500px;
    border: black dashed 2px;
    display: flex;
    flex-direction: column;
}

#head {
    border: green solid 1px;
    flex-shrink: 0;
}

#content{
    border: red solid 1px;
    overflow-y: auto;
    /*height: 100%;*/
}

#foot {
    border: blue solid 1px;
    height: 50px;
    flex-shrink: 0;
}

How to query for today's date and 7 days before data?

Try this way:

select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE() 

How to Specify "Vary: Accept-Encoding" header in .htaccess

To gzip up your font files as well!

add "x-font/otf x-font/ttf x-font/eot"

as in:

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml x-font/otf x-font/ttf x-font/eot

'IF' in 'SELECT' statement - choose output value based on column values

You can try this also

 SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table

Git: How configure KDiff3 as merge tool and diff tool

I needed to add the command line parameters or KDiff3 would only open without files and prompt me for base, local and remote. I used the version supplied with TortoiseHg.

Additionally, I needed to resort to the good old DOS 8.3 file names.

[merge]
    tool = kdiff3

[mergetool "kdiff3"]
    cmd = /c/Progra~1/TortoiseHg/lib/kdiff3.exe $BASE $LOCAL $REMOTE -o $MERGED

However, it works correctly now.

Differences in string compare methods in C#

Using .Equals is also a lot easier to read.

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

This is clearly a classpath problem. Take into consideration that the classpath must change a bit when you run your program outside the IDE. This is because the IDE loads the other JARs relative to the root folder of your project, while in the case of the final JAR this is usually not true.

What I like to do in these situations is build the JAR manually. It takes me at most 5 minutes and it always solves the problem. I do not suggest you do this. Find a way to use Maven, that's its purpose.

Find size of Git repository

UPDATE git 1.8.3 introduced a more efficient way to get a rough size: git count-objects -vH (see answer by @VonC)

For different ideas of "complete size" you could use:

git bundle create tmp.bundle --all
du -sh tmp.bundle

Close (but not exact:)

git gc
du -sh .git/

With the latter, you would also be counting:

  • hooks
  • config (remotes, push branches, settings (whitespace, merge, aliases, user details etc.)
  • stashes (see Can I fetch a stash from a remote repo into a local branch? also)
  • rerere cache (which can get considerable)
  • reflogs
  • backups (from filter-branch, e.g.) and various other things (intermediate state from rebase, bisect etc.)

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

Using SELECT result in another SELECT

NewScores is an alias to Scores table - it looks like you can combine the queries as follows:

SELECT 
    ROW_NUMBER() OVER( ORDER BY NETT) AS Rank, 
    Name, 
    FlagImg, 
    Nett, 
    Rounds 
FROM (
    SELECT 
        Members.FirstName + ' ' + Members.LastName AS Name, 
        CASE 
            WHEN MenuCountry.ImgURL IS NULL THEN 
                '~/images/flags/ismygolf.png' 
            ELSE 
                MenuCountry.ImgURL 
        END AS FlagImg, 
        AVG(CAST(NewScores.NetScore AS DECIMAL(18, 4))) AS Nett, 
        COUNT(Score.ScoreID) AS Rounds 
    FROM 
        Members 
        INNER JOIN 
        Score NewScores
            ON Members.MemberID = NewScores.MemberID 
        LEFT OUTER JOIN MenuCountry 
            ON Members.Country = MenuCountry.ID 
    WHERE 
        Members.Status = 1 
        AND NewScores.InsertedDate >= DATEADD(mm, -3, GETDATE())
    GROUP BY 
        Members.FirstName + ' ' + Members.LastName, 
        MenuCountry.ImgURL
    ) AS Dertbl 
ORDER BY;

How to store the hostname in a variable in a .bat file?

Why not so?:

set host=%COMPUTERNAME%
echo %host%

remove attribute display:none; so the item will be visible

You should remove "style" attribute instead of "display" property :

$("span").removeAttr("style");

MySQL Join Where Not Exists

There are three possible ways to do that.

  1. Option

    SELECT  lt.* FROM    table_left lt
    LEFT JOIN
        table_right rt
    ON      rt.value = lt.value
    WHERE   rt.value IS NULL
    
  2. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   lt.value NOT IN
    (
    SELECT  value
    FROM    table_right rt
    )
    
  3. Option

    SELECT  lt.* FROM    table_left lt
    WHERE   NOT EXISTS
    (
    SELECT  NULL
    FROM    table_right rt
    WHERE   rt.value = lt.value
    )
    

How to write the Fibonacci Sequence?

Why not simply do the following?

x = [1,1]
for i in range(2, 10):  
    x.append(x[-1] + x[-2]) 
print(', '.join(str(y) for y in x))

Putty: Getting Server refused our key Error

In my case, I had to disable SELinux on Centos6.6 to get it working :)

Edit /etc/selinux/config and set the following and then reboot the host.

selinux=disabled

BTW...forgot to mention that I had to set the LogLevel=DEBUG3 to identify the issue.

The executable was signed with invalid entitlements

Sorry that this is very late, but I just was looking at this question and found something that worked for me. I went to PROJECT->Build Settings and found the Code Signing section. Beside debug, my distribution profile that said Iphone Distribution: MY NAME was selected. I instead selected Iphone Developer: MY NAME on the drop-down list under IpodProfile (for bundle identifiers com.myName.myApp which was the provisioning Profile for my device. Hope this helps!

UNC path to a folder on my local computer

If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:

\\localhost\c$\my_dir

... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.

How can I time a code segment for testing performance with Pythons timeit?

If you are profiling your code and can use IPython, it has the magic function %timeit.

%%timeit operates on cells.

In [2]: %timeit cos(3.14)
10000000 loops, best of 3: 160 ns per loop

In [3]: %%timeit
   ...: cos(3.14)
   ...: x = 2 + 3
   ...: 
10000000 loops, best of 3: 196 ns per loop

How to delete parent element using jQuery

Delete parent:

$(document).on("click", ".remove", function() {
       $(this).parent().remove(); 
});

Delete all parents:

$(document).on("click", ".remove", function() { 
       $(this).parents().remove();
});

How to render html with AngularJS templates

You shoud follow the Angular docs and use $sce - $sce is a service that provides Strict Contextual Escaping services to AngularJS. Here is a docs: http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe

Let's take an example with asynchroniously loading Eventbrite login button

In your controller:

someAppControllers.controller('SomeCtrl', ['$scope', '$sce', 'eventbriteLogin', 
  function($scope, $sce, eventbriteLogin) {

    eventbriteLogin.fetchButton(function(data){
      $scope.buttonLogin = $sce.trustAsHtml(data);
    });
  }]);

In your view just add:

<span ng-bind-html="buttonLogin"></span>

In your services:

someAppServices.factory('eventbriteLogin', function($resource){
   return {
        fetchButton: function(callback){
            Eventbrite.prototype.widget.login({'app_key': 'YOUR_API_KEY'}, function(widget_html){
                callback(widget_html);
            })
      }
    }
});

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Getting title and meta tags from external website

We use Apache Tika via php (command line utility) with -j for json :

http://tika.apache.org/

<?php
    shell_exec( 'java -jar tika-app-1.4.jar -j http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying' );
?>

This is a sample output from a random guardian article :

{
   "Content-Encoding":"UTF-8",
   "Content-Length":205599,
   "Content-Type":"text/html; charset\u003dUTF-8",
   "DC.date.issued":"2013-07-21",
   "X-UA-Compatible":"IE\u003dEdge,chrome\u003d1",
   "application-name":"The Guardian",
   "article:author":"http://www.guardian.co.uk/profile/nicholaswatt",
   "article:modified_time":"2013-07-21T22:42:21+01:00",
   "article:published_time":"2013-07-21T22:00:03+01:00",
   "article:section":"Politics",
   "article:tag":[
      "Lynton Crosby",
      "Health policy",
      "NHS",
      "Health",
      "Healthcare industry",
      "Society",
      "Public services policy",
      "Lobbying",
      "Conservatives",
      "David Cameron",
      "Politics",
      "UK news",
      "Business"
   ],
   "content-id":"/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
   "dc:title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
   "description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
   "fb:app_id":180444840287,
   "keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
   "msapplication-TileColor":"#004983",
   "msapplication-TileImage":"http://static.guim.co.uk/static/a314d63c616d4a06f5ec28ab4fa878a11a692a2a/common/images/favicons/windows_tile_144_b.png",
   "news_keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
   "og:description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
   "og:image":"https://static-secure.guim.co.uk/sys-images/Guardian/Pix/pixies/2013/7/21/1374433351329/Lynton-Crosby-008.jpg",
   "og:site_name":"the Guardian",
   "og:title":"Tory strategist Lynton Crosby in new lobbying row",
   "og:type":"article",
   "og:url":"http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
   "resourceName":"tory-strategist-lynton-crosby-lobbying",
   "title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
   "twitter:app:id:googleplay":"com.guardian",
   "twitter:app:id:iphone":409128287,
   "twitter:app:name:googleplay":"The Guardian",
   "twitter:app:name:iphone":"The Guardian",
   "twitter:app:url:googleplay":"guardian://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
   "twitter:card":"summary_large_image",
   "twitter:site":"@guardian"
}

How can I connect to Android with ADB over TCP?

To switch between TCP and USB modes with just one command, you can add this to /init.rc:

on property:service.adb.tcp.port=*
    restart adbd

on property:service.adb.tcp.enable=1
    setprop service.adb.tcp.port 5555

on property:service.adb.tcp.enable=0
    setprop service.adb.tcp.port -1

And now you can use property service.adb.tcp.enable to enable or disable listening on port 5555. Run netstat to check whether it's listening. As you can see it will also trigger if you do wish to change service.adb.tcp.port manually.

Spring MVC: Complex object as GET @RequestParam

Yes, You can do it in a simple way. See below code of lines.

URL - http://localhost:8080/get/request/multiple/param/by/map?name='abc' & id='123'

 @GetMapping(path = "/get/request/header/by/map")
    public ResponseEntity<String> getRequestParamInMap(@RequestParam Map<String,String> map){
        // Do your business here 
        return new ResponseEntity<String>(map.toString(),HttpStatus.OK);
    } 

AngularJS : Difference between the $observe and $watch methods

Why is $observe different than $watch?

The watchExpression is evaluated and compared to the previous value each digest() cycle, if there's a change in the watchExpression value, the watch function is called.

$observe is specific to watching for interpolated values. If a directive's attribute value is interpolated, eg dir-attr="{{ scopeVar }}", the observe function will only be called when the interpolated value is set (and therefore when $digest has already determined updates need to be made). Basically there's already a watcher for the interpolation, and the $observe function piggybacks off that.

See $observe & $set in compile.js

How to output JavaScript with PHP

You are using " instead of ' It is mixing up php syntax with javascript. PHP is going to print javascript with echo function, but it is taking the js codes as wrong php syntax. so try this,

<html>
<body>
<?php

echo "<script type='text/javascript'>";
echo "document.write('Hello World!')";
echo "</script>";

?>
</body>
</html>

How can I stop redis-server?

On MacOSX,

This is what worked for me

/etc/init.d/redis restart

/etc/init.d/redis stop

/etc/init.d/redis start

How can I Remove .DS_Store files from a Git repository?

The best solution to tackle this issue is to Globally ignore these files from all the git repos on your system. This can be done by creating a global gitignore file like:

vi ~/.gitignore_global

Adding Rules for ignoring files like:

# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so

# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip

# Logs and databases #
######################
*.log
*.sql
*.sqlite

# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

Now, add this file to your global git config:

git config --global core.excludesfile ~/.gitignore_global

Edit:

Removed Icons as they might need to be committed as application assets.

Why use @PostConstruct?

Also constructor based initialisation will not work as intended whenever some kind of proxying or remoting is involved.

The ct will get called whenever an EJB gets deserialized, and whenever a new proxy gets created for it...

Getting 404 Not Found error while trying to use ErrorDocument

When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,

 ErrorDocument 404 /yourfoldernames/errors/404.html

Conditional replacement of values in a data.frame

Since you are conditionally indexing df$est, you also need to conditionally index the replacement vector df$a:

index <- df$b == 0
df$est[index] <- (df$a[index] - 5)/2.533 

Of course, the variable index is just temporary, and I use it to make the code a bit more readible. You can write it in one step:

df$est[df$b == 0] <- (df$a[df$b == 0] - 5)/2.533 

For even better readibility, you can use within:

df <- within(df, est[b==0] <- (a[b==0]-5)/2.533)

The results, regardless of which method you choose:

df
          a b      est
1  11.77000 2 0.000000
2  10.90000 3 0.000000
3  10.32000 2 0.000000
4  10.96000 0 2.352941
5   9.90600 0 1.936834
6  10.70000 0 2.250296
7  11.43000 1 0.000000
8  11.41000 2 0.000000
9  10.48512 4 0.000000
10 11.19000 0 2.443743

As others have pointed out, an alternative solution in your example is to use ifelse.

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

DataRow: Select cell value by a given column name

On top of what Jimmy said, you can also make the select generic by using Convert.ChangeType along with the necessary null checks:

public T GetColumnValue<T>(DataRow row, string columnName)
  {
        T value = default(T);
        if (row.Table.Columns.Contains(columnName) && row[columnName] != null && !String.IsNullOrWhiteSpace(row[columnName].ToString()))
        {
            value = (T)Convert.ChangeType(row[columnName].ToString(), typeof(T));
        }

        return value;
  }

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

How to uninstall Jenkins?

Run the following commands to completely uninstall Jenkins from MacOS Sierra. You don't need to change anything, just run these commands.

sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins '/Library/Application Support/Jenkins' /Library/Documentation/Jenkins
sudo rm -rf /Users/Shared/Jenkins
sudo rm -rf /var/log/jenkins
sudo rm -f /etc/newsyslog.d/jenkins.conf
sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins
pkgutil --pkgs
grep 'org\.jenkins-ci\.'
xargs -n 1 sudo pkgutil --forget

Salam

Shah

How do I make an auto increment integer field in Django?

You can create an autofield. Here is the documentation for the same

Please remember Django won't allow to have more than one AutoField in a model, In your model you already have one for your primary key (which is default). So you'll have to override model's save method and will probably fetch the last inserted record from the table and accordingly increment the counter and add the new record.

Please make that code thread safe because in case of multiple requests you might end up trying to insert same value for different new records.

Run PHP Task Asynchronously

I've used the queuing approach, and it works well as you can defer that processing until your server load is idle, letting you manage your load quite effectively if you can partition off "tasks which aren't urgent" easily.

Rolling your own isn't too tricky, here's a few other options to check out:

  • GearMan - this answer was written in 2009, and since then GearMan looks a popular option, see comments below.
  • ActiveMQ if you want a full blown open source message queue.
  • ZeroMQ - this is a pretty cool socket library which makes it easy to write distributed code without having to worry too much about the socket programming itself. You could use it for message queuing on a single host - you would simply have your webapp push something to a queue that a continuously running console app would consume at the next suitable opportunity
  • beanstalkd - only found this one while writing this answer, but looks interesting
  • dropr is a PHP based message queue project, but hasn't been actively maintained since Sep 2010
  • php-enqueue is a recently (2017) maintained wrapper around a variety of queue systems
  • Finally, a blog post about using memcached for message queuing

Another, perhaps simpler, approach is to use ignore_user_abort - once you've sent the page to the user, you can do your final processing without fear of premature termination, though this does have the effect of appearing to prolong the page load from the user perspective.

C++ compile time error: expected identifier before numeric constant

You cannot do this:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5,0)};
};

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

get keys of json-object in JavaScript

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).

Object.keys(jsonData).forEach(function(key) {
    var value = jsonData[key];
    // ...
});

The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).

Here's the rest of the answer from 2011:

Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
    (function() {
        var hasOwn = Object.prototype.hasOwnProperty;
        Object.keys = Object_keys;
        function Object_keys(obj) {
            var keys = [], name;
            for (name in obj) {
                if (hasOwn.call(obj, name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}

That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)

Purpose of a constructor in Java?

A Java constructor has the same name as the name of the class to which it belongs.

Constructor’s syntax does not include a return type, since constructors never return a value.

Constructor is always called when object is created. example:- Default constructor

class Student3{  
    int id;  
    String name;  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student3 s1=new Student3();  
        Student3 s2=new Student3();  
        s1.display();  
        s2.display();  
    }  
} 

Output:

0 null
0 null

Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

class Student4{  
    int id;  
    String name;  
    Student4(int i,String n){  
        id = i;  
        name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student4 s1 = new Student4(111,"Karan");  
        Student4 s2 = new Student4(222,"Aryan");  
        s1.display();  
        s2.display();  
    }  
}  

Output:

111 Karan
222 Aryan

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

Java 8 stream map to list of keys sorted by values

You can use this as an example of your problem

    Map<Integer, String> map = new HashMap<>();
    map.put(10, "apple");
    map.put(20, "orange");
    map.put(30, "banana");
    map.put(40, "watermelon");
    map.put(50, "dragonfruit");

    // split a map into 2 List
    List<Integer> resultSortedKey = new ArrayList<>();
    List<String> resultValues = map.entrySet().stream()
            //sort a Map by key and stored in resultSortedKey
            .sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
            .peek(e -> resultSortedKey.add(e.getKey()))
            .map(x -> x.getValue())
            // filter banana and return it to resultValues
            .filter(x -> !"banana".equalsIgnoreCase(x))
            .collect(Collectors.toList());

    resultSortedKey.forEach(System.out::println);
    resultValues.forEach(System.out::println);

Multiple files upload (Array) with CodeIgniter 2.0

For CodeIgniter 3

<form action="<?php echo base_url('index.php/TestingController/insertdata') ?>" method="POST"
      enctype="multipart/form-data">
    <div class="form-group">
        <label for="">title</label>
        <input type="text" name="title" id="title" class="form-control">
    </div>
    <div class="form-group">
        <label for="">File</label>
        <input type="file" name="files" id="files" class="form-control">
    </div>
    <input type="submit" value="Submit" class="btn btn-primary">
</form>


public function insertdatanew()
{
    $this->load->library('upload');
    $files = $_FILES;
    $cpt = count($_FILES['filesdua']['name']);

    for ($i = 0; $i < $cpt; $i++) {
        $_FILES['filesdua']['name'] = $files['filesdua']['name'][$i];
        $_FILES['filesdua']['type'] = $files['filesdua']['type'][$i];
        $_FILES['filesdua']['tmp_name'] = $files['filesdua']['tmp_name'][$i];
        $_FILES['filesdua']['error'] = $files['filesdua']['error'][$i];
        $_FILES['filesdua']['size'] = $files['filesdua']['size'][$i];

        // fungsi uploud
        $config['upload_path']          = './uploads/testing/';
        $config['allowed_types']        = '*';
        $config['max_size']             = 0;
        $config['max_width']            = 0;
        $config['max_height']           = 0;
        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if (!$this->upload->do_upload('filesdua')) {
            $error = array('error' => $this->upload->display_errors());
            var_dump($error);

            // $this->load->view('welcome_message', $error);
        } else {

            // menambil nilai value yang di upload  
            $data = array('upload_data' => $this->upload->data());
            $nilai = $data['upload_data']; 
            $filename = $nilai['file_name'];
            var_dump($filename);

            // $this->load->view('upload_success', $data);
        }
    }
    // var_dump($cpt);
}

Force flushing of output to a file while bash script is still running

well like it or not this is how redirection works.

In your case the output (meaning your script has finished) of your script redirected to that file.

What you want to do is add those redirections in your script.

How to test if parameters exist in rails

Here's what I do,

before_action :validate_presence

and then following methods:

    def check_presence
  params[:param1].present? && params[:param2].present?
 end

 def validate_presence
  if !check_presence
    render json:  {
                      error:  {
                                message: "Bad Request, parameters missing.",
                                status: 500
                              }
                    }
  end
 end

How can I use querySelector on to pick an input element by name?

1- you need to close the block of the function with '}', which is missing.

2- the argument of querySelector may not be an empty string '' or ' '... Use '*' for all.

3- those arguments will return the needed value:

querySelector('*')

querySelector('input')

querySelector('input[name="pwd"]')

querySelector('[name="pwd"]')

Calculate difference between two dates (number of days)?

First declare a class that will return later:

public void date()
{
    Datetime startdate;
    Datetime enddate;
    Timespan remaindate;

    startdate = DateTime.Parse(txtstartdate.Text).Date;
    enddate = DateTime.Parse(txtenddate.Text).Date;

    remaindate = enddate - startdate;

    if (remaindate != null)
    {
        lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
    }
    else
    {
        lblmsg.Text = "correct your code again.";
    }
}

protected void btncal_Click(object sender, EventArgs e)
{
    date();
}

Use a button control to call the above class. Here is an example:

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

Making Enter key on an HTML form submit instead of activating button

You don't need JavaScript to choose your default submit button or input. You just need to mark it up with type="submit", and the other buttons mark them with type="button". In your example:

<button type="button" onclick="return myFunc1()">Button 1</button>
<input type="submit" name="go" value="Submit"/>

Thread-safe List<T> property

You can also use the more primitive

Monitor.Enter(lock);
Monitor.Exit(lock);

which lock uses (see this post C# Locking an object that is reassigned in lock block).

If you are expecting exceptions in the code this is not safe but it allows you to do something like the following:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;

public class Something
{
    private readonly object _lock;
    private readonly List<string> _contents;

    public Something()
    {
        _lock = new object();

        _contents = new List<string>();
    }

    public Modifier StartModifying()
    {
        return new Modifier(this);
    }

    public class Modifier : IDisposable
    {
        private readonly Something _thing;

        public Modifier(Something thing)
        {
            _thing = thing;

            Monitor.Enter(Lock);
        }

        public void OneOfLotsOfDifferentOperations(string input)
        {
            DoSomethingWith(input);
        }

        private void DoSomethingWith(string input)
        {
            Contents.Add(input);
        }

        private List<string> Contents
        {
            get { return _thing._contents; }
        }

        private object Lock
        {
            get { return _thing._lock; }
        }

        public void Dispose()
        {
            Monitor.Exit(Lock);
        }
    }
}

public class Caller
{
    public void Use(Something thing)
    {
        using (var modifier = thing.StartModifying())
        {
            modifier.OneOfLotsOfDifferentOperations("A");
            modifier.OneOfLotsOfDifferentOperations("B");

            modifier.OneOfLotsOfDifferentOperations("A");
            modifier.OneOfLotsOfDifferentOperations("A");
            modifier.OneOfLotsOfDifferentOperations("A");
        }
    }
}

One of the nice things about this is you'll get the lock for the duration of the series of operations (rather than locking in each operation). Which means that the output should come out in the right chunks (my usage of this was getting some output onto screen from an external process)

I do really like the simplicity + transparency of the ThreadSafeList + that does the important bit in stopping crashes

How to change the default message of the required field in the popover of form-control in bootstrap?

Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"
 oninput="setCustomValidity('')"></input>

Here,

this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field

oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.

How to check if $_GET is empty?

if (!$_GET) echo "empty";

why do you need such a checking?

lol
you guys too direct-minded.
don't take as offense but sometimes not-minded at all
$_GET is very special variable, not like others.
it is supposed to be always set. no need to treat it as other variables. when $_GET is not set and it's expected - it is emergency case and that's what "Undefined variable" notice invented for

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Trim leading and trailing spaces from a string in awk

If you want to trim all spaces, only in lines that have a comma, and use awk, then the following will work for you:

awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt

If you only want to remove spaces in the second column, change the expression to

awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt

Note that gsub substitutes the character in // with the second expression, in the variable that is the third parameter - and does so in-place - in other words, when it's done, the $0 (or $2) has been modified.

Full explanation:

-F,            use comma as field separator 
               (so the thing before the first comma is $1, etc)
/,/            operate only on lines with a comma 
               (this means empty lines are skipped)
gsub(a,b,c)    match the regular expression a, replace it with b, 
               and do all this with the contents of c
print$1","$2   print the contents of field 1, a comma, then field 2
input.txt      use input.txt as the source of lines to process

EDIT I want to point out that @BMW's solution is better, as it actually trims only leading and trailing spaces with two successive gsub commands. Whilst giving credit I will give an explanation of how it works.

gsub(/^[ \t]+/,"",$2);    - starting at the beginning (^) replace all (+ = zero or more, greedy)
                             consecutive tabs and spaces with an empty string
gsub(/[ \t]+$/,"",$2)}    - do the same, but now for all space up to the end of string ($)
1                         - ="true". Shorthand for "use default action", which is print $0
                          - that is, print the entire (modified) line

Get list of Excel files in a folder using VBA

Sub test()
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set folder1 = FSO.GetFolder(FromPath).Files
    FolderPath_1 = "D:\Arun\Macro Files\UK Marco\External Sales Tool for Au\Example Files\"
    Workbooks.Add
    Set Movenamelist = ActiveWorkbook
    For Each fil In folder1
        Movenamelist.Activate
        Range("A100000").End(xlUp).Offset(1, 0).Value = fil
        ActiveCell.Offset(1, 0).Select
    Next
End Sub

How to access JSON Object name/value?

You might want to try this approach:

var  str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);     
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);     
console.log(jsonData[0].name)

Getting raw SQL query string from PDO prepared statements

I know this question is a bit old, but, I'm using this code since lot time ago (I've used response from @chris-go), and now, these code are obsolete with PHP 7.2

I'll post an updated version of these code (Credit for the main code are from @bigwebguy, @mike and @chris-go, all of them answers of this question):

/**
 * Replaces any parameter placeholders in a query with the value of that
 * parameter. Useful for debugging. Assumes anonymous parameters from 
 * $params are are in the same order as specified in $query
 *
 * @param string $query The sql query with parameter placeholders
 * @param array $params The array of substitution parameters
 * @return string The interpolated query
 */
public function interpolateQuery($query, $params) {
    $keys = array();
    $values = $params;

    # build a regular expression for each parameter
    foreach ($params as $key => $value) {
        if (is_string($key)) {
            $keys[] = '/:'.$key.'/';
        } else {
            $keys[] = '/[?]/';
        }

        if (is_array($value))
            $values[$key] = implode(',', $value);

        if (is_null($value))
            $values[$key] = 'NULL';
    }
    // Walk the array to see if we can add single-quotes to strings
    array_walk($values, function(&$v, $k) { if (!is_numeric($v) && $v != "NULL") $v = "\'" . $v . "\'"; });

    $query = preg_replace($keys, $values, $query, 1, $count);

    return $query;
}

Note the change on the code are on array_walk() function, replacing create_function by an anonymous function. This make these good piece of code functional and compatible with PHP 7.2 (and hope future versions too).

Is it possible to get all arguments of a function as single object inside that function?

In ES6 you can do something like this:

_x000D_
_x000D_
function foo(...args) _x000D_
{_x000D_
   let [a,b,...c] = args;_x000D_
_x000D_
   console.log(a,b,c);_x000D_
}_x000D_
_x000D_
_x000D_
foo(1, null,"x",true, undefined);
_x000D_
_x000D_
_x000D_

Which JRE am I using?

The Java system property System.getProperty(...) to consult is "java.runtime.name". This will distinguish between "OpenJDK Runtime Environment" and "Java(TM) SE Runtime Environment". They both have the same vendor - "Oracle Corporation".

This property is also included in the output for java -version.

Cannot set content-type to 'application/json' in jQuery.ajax

Hi These two lines worked for me.

contentType:"application/json; charset=utf-8", dataType:"json"

 $.ajax({
            type: "POST",
            url: "/v1/candidates",
            data: obj,
            **contentType:"application/json; charset=utf-8",
            dataType:"json",**
            success: function (data) {
                table.row.add([
                    data.name, data.title
                ]).draw(false);
            }

Thanks, Prashant

How to embed PDF file with responsive width

_x000D_
_x000D_
<embed src="your.pdf" type="application/pdf#view=FitH" width="actual-width.px" height="actual-height.px"></embed>
_x000D_
_x000D_
_x000D_

Check this link for all PDF Parameters: https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=7

Chrome has its own PDF reader & all parameter don't work on chrome. Mozilla is worst for handling PDFs.

Updating PartialView mvc 4

Controller :

public ActionResult Refresh(string ID)
    {
        DetailsViewModel vm = new DetailsViewModel();  // Model
        vm.productDetails = _product.GetproductDetails(ID); 
        /* "productDetails " is a property in "DetailsViewModel"
        "GetProductDetails" is a method in "Product" class
        "_product" is an interface of "Product" class */

        return PartialView("_Details", vm); // Details is a partial view
    }

In yore index page you should to have refresh link :

     <a href="#" id="refreshItem">Refresh</a>

This Script should be also in your index page:

<script type="text/javascript">

    $(function () {
    $('a[id=refreshItem]:last').click(function (e) {
        e.preventDefault();

        var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name

        $.ajax({
            type: 'GET',
            url: url,
            cache: false,
            success: function (grid) {
                $('#tabItemDetails').html(grid);
                clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
            }
        });
    });
});

Finding rows that don't contain numeric data in Oracle

I was thinking you could use a regexp_like condition and use the regular expression to find any non-numerics. I hope this might help?!

SELECT * FROM table_with_column_to_search WHERE REGEXP_LIKE(varchar_col_with_non_numerics, '[^0-9]+');

How to break out of nested loops?

A different approach is to refactor the code from two for loops into a for loop and one manual loop. That way the break in the manual loop applies to the outer loop. I used this once in a Gauss-Jordan Elimination which required three nested loops to process.

for (int i = 0; i < 1000; i++)
{
    int j = 0;

MANUAL_LOOP:;

    if (j < 1000)
    {
       if (condition)
       {
           break;
       }

       j++;
       goto MANUAL_LOOP;
    }
}

Failed to open/create the internal network Vagrant on Windows10

I have worked around for a while, all you need to do is open VirtualBox,

File > Preferences / Network > Host-Only Networks

You will see VirtualBox Host-Only Ethernet Adapter

click on it, and edit.

My IP settings for vagrant VM was 192.168.10.10, you should edit up to your VM IP

Here is my adapter settings;

Adapter Settings

DHCP Server Settings

How to force a component's re-rendering in Angular 2?

I force reload my component using *ngIf.

All the components inside my container goes back to the full lifecycle hooks .

In the template :

<ng-container *ngIf="_reload">
    components here 
</ng-container>

Then in the ts file :

public _reload = true;

private reload() {
    setTimeout(() => this._reload = false);
    setTimeout(() => this._reload = true);
}

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

Just want to post for those not finding the answers here solved their problem.

When running your application, make sure the solution platform drop down is correctly set. mine was on x86 which in turn caused me this problem.

Wrapping a react-router Link in an html button

If you are using react-router-dom and material-ui you can use ...

import { Link } from 'react-router-dom'
import Button from '@material-ui/core/Button';

<Button component={Link} to="/open-collective">
  Link
</Button>

You can read more here.

How to pass props to {this.props.children}

For any one who has a single child element this should do it.

{React.isValidElement(this.props.children)
                  ? React.cloneElement(this.props.children, {
                      ...prop_you_want_to_pass
                    })
                  : null}

How can I get the full/absolute URL (with domain) in Django?

You can either pass request reverse('view-name', request=request) or enclose reverse() with build_absolute_uri request.build_absolute_uri(reverse('view-name'))

ASP.NET MVC Ajax Error handling

I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.

I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:

    [HttpPut]
    public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave) 
    {
        if (!ModelState.IsValid)
        {
            return new JsonResult
            {
                Data = new { ErrorMessage = "Model is not valid", Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }
        try
        {
            MyDbContext db = new MyDbContext();

            db.Entry(employeToSave).State = EntityState.Modified;
            db.SaveChanges();

            DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];

            if (employeToSave.Id == user.Id)
            {
                user.Company = employeToSave.Company;
                user.Language = employeToSave.Language;
                user.Money = employeToSave.Money;
                user.CostCenter = employeToSave.CostCenter;

                Session["EmployeLoggin"] = user;
            }
        }
        catch (Exception ex) 
        {
            return new JsonResult
            {
                Data = new { ErrorMessage = ex.Message, Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }

        return new JsonResult() { Data = new { Success = true }, };
    }

Later in the ajax call I just asked for this property to know if I had an exception:

$.ajax({
    url: 'UpdateEmployeeConfig',
    type: 'PUT',
    data: JSON.stringify(EmployeConfig),
    contentType: "application/json;charset=utf-8",
    success: function (data) {
        if (data.Success) {
            //This is for the example. Please do something prettier for the user, :)
            alert('All was really ok');                                           
        }
        else {
            alert('Oups.. we had errors: ' + data.ErrorMessage);
        }
    },
    error: function (request, status, error) {
       alert('oh, errors here. The call to the server is not working.')
    }
});

Hope this helps. Happy code! :P

How to copy files from host to Docker container?

Another workaround is using the good old scp. This is useful in the case you need to copy a directory.

From your host run:

scp FILE_PATH_ON_YOUR_HOST IP_CONTAINER:DESTINATION_PATH
scp foo.txt 172.17.0.2:foo.txt

In the case you need to copy a directory:

scp -r DIR_PATH_ON_YOUR_HOST IP_CONTAINER:DESTINATION_PATH
scp -r directory 172.17.0.2:directory

be sure to install ssh into your container too.

apt-get install openssh-server

How to kill all processes with a given partial name?

Kill all processes matching the string "myProcessName":

ps -ef | grep 'myProcessName' | grep -v grep | awk '{print $2}' | xargs -r kill -9

Source: http://www.commandlinefu.com/commands/view/1138/ps-ef-grep-process-grep-v-grep-awk-print-2-xargs-kill-9

What's this code doing?

The ps -ef produces a list of process id's on the computer visible to this user. The pipe grep filters that down for rows containing that string. The grep -v grep says don't match on the process itself doing the grepping. The pipe awk print says split the rows on default delimiter whitespace and filter to the second column which is our process id. The pipe xargs spins up a new process to send all those pid's to kill -9, ending them all.

The above code is bad, dangerous, ugly and hackish for several reasons.

  1. If the code being force-ended is doing any database ops or secure transactions with low probability race conditions, some fraction of a percent of the time, atomicity of that transaction will be wrecked, producing undefined behavior. kill -9 takes no prisoners. If your code is sensitive to this, try replacing the xargs kill part with a transmitted flag that requests a graceful shutdown, and only if that request is denied, last-resort to kill -9

  2. There's a non zero possibility that you will accidentally end the operating system or caused undefined behavior in an unrelated process, leading to whole system instability because ps -ef lists every possible process that could exist, and you can't be sure some weird 3rd party library shares your process name, or that in the time between read and execute kill -9, the processid had changed to something else, and now you've accidentally ended some random process you didn't intend to.

But, if you understand the risks and control for them with very unique names, and you're ok with a few dropped transactions or occasional corruption in data, then 99.9% of the time yer gonna be fine. If there's a problem, reboot the computer, make sure there aren't any process collisions. It's because of code like this that makes the tech support script: "Have you tried restarting your computer" a level 5 meme.

How to send password securely over HTTP?

Using https sounds best option here (certificates are not that expensive nowadays). However if http is a requirement, you may use some encription - encript it on server side and decript in users browser (send key separately).

We have used that while implementing safevia.net - encription is done on clients (sender/receiver) sides, so users data are not available on network nor server layer.

How to pass parameter to click event in Jquery

Better Approach:

<script type="text/javascript">
    $('#btn').click(function() {
      var id = $(this).attr('id');
      alert(id);
    });
</script>

<input id="btn" type="button" value="click" />

But, if you REALLY need to do the click handler inline, this will work:

<script type="text/javascript">
    function display(el) {
        var id = $(el).attr('id');
        alert(id);
    }
</script>

<input id="btn" type="button" value="click" OnClick="display(this);" />

Failed linking file resources

This similar error may also show if you have deleted an Activity java file previously and have not deleted the corresponding xml layout file.

Delete the xml file for the deleted Activity java file and Clean or Rebuild the project.

The reason behind it may be because of the mismatch of context in the xml. (This might occur if you are copy-pasting an xml layout code) Match the tools:context to the java file of the activity.

image

How to set a:link height/width with css?

Your problem is probably that a elements are display: inline by nature. You can't set the width and height of inline elements.

You would have to set display: block on the a, but that will bring other problems because the links start behaving like block elements. The most common cure to that is giving them float: left so they line up side by side anyway.

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

In case it helps anyone, the solution mentioned in this other question worked for me when pip stopped working today after upgrading it: Pip broken after upgrading

It seems that it's an issue when a previously cached location changes, so you can refresh the cache with this command:

hash -r

What's the best way to use R scripts on the command line (terminal)?

Miguel Sanchez's response is the way it should be. The other way executing Rscript could be 'env' command to run the system wide RScript.

#!/usr/bin/env Rscript

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';

how to use JSON.stringify and json_decode() properly

When you use JSON stringify then use html_entity_decode first before json_decode.

$tempData = html_entity_decode($tempData);
$cleanData = json_decode($tempData);

Changing the tmp folder of mysql

This is answered in the documentation:

Where MySQL Stores Temporary Files

On Unix, MySQL uses the value of the TMPDIR environment variable as the path name of the directory in which to store temporary files. If TMPDIR is not set, MySQL uses the system default, which is usually /tmp, /var/tmp, or /usr/tmp.

On Windows, Netware and OS2, MySQL checks in order the values of the TMPDIR, TEMP, and TMP environment variables. For the first one found to be set, MySQL uses it and does not check those remaining. If none of TMPDIR, TEMP, or TMP are set, MySQL uses the Windows system default, which is usually C:\windows\temp.

How can I encode a string to Base64 in Swift?

After thorough research I found the solution

Encoding

    let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    let base64String =plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
    println(base64String) // bXkgcGxhbmkgdGV4dA==

Decoding

    let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
    let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)    
    println(decodedString) // my plain data

More on this http://creativecoefficient.net/swift/encoding-and-decoding-base64/

Replacing some characters in a string with another character

Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _:

$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN

Notice that the +(pattern) pattern requires extended pattern matching, turned on with

shopt -s extglob

Alternatively, with the -s ("squeeze") option of tr:

$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN

Python: split a list based on a condition?

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

Check this

How to pass model attributes from one Spring MVC controller to another controller?

I used @ControllerAdvice , please check is available in Spring 3.X; I am using it in Spring 4.0.

@ControllerAdvice 
public class CommonController extends ControllerBase{
@Autowired
MyService myServiceInstance;

    @ModelAttribute("userList")
    public List<User> getUsersList()
    {
       //some code
       return ...
    }
}

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

How to set a value to a file input in HTML?

As everyone else here has stated: You cannot upload just any file automatically with JavaScript.

HOWEVER! If you have access to the information you want to send in your code (i.e., not C:\passwords.txt), then you can upload it as a blob-type, and then treat it as a file.

What the server will end up seeing will be indistinguishable from someone actually setting the value of <input type="file" />. The trick, ultimately, is to begin a new XMLHttpRequest() with the server...

function uploadFile (data) {
        // define data and connections
    var blob = new Blob([JSON.stringify(data)]);
    var url = URL.createObjectURL(blob);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'myForm.php', true);
    
        // define new form
    var formData = new FormData();
    formData.append('someUploadIdentifier', blob, 'someFileName.json');
        
        // action after uploading happens
    xhr.onload = function(e) {
        console.log("File uploading completed!");
    };
    
        // do the uploading
    console.log("File uploading started!");
    xhr.send(formData);
}

    // This data/text below is local to the JS script, so we are allowed to send it!
uploadFile({'hello!':'how are you?'});

So, what could you possibly use this for? I use it for uploading HTML5 canvas elements as jpg's. This saves the user the trouble of having to open a file input element, only to select the local, cached image that they just resized, modified, etc.. But it should work for any file type.

Paging with LINQ for objects

   ( for o in objects
    where ...
    select new
   {
     A=o.a,
     B=o.b
   })
.Skip((page-1)*pageSize)
.Take(pageSize)

How to Troubleshoot Intermittent SQL Timeout Errors

Sounds like you may already have your answer but in case you need one more place to look you may want to check out the size and activity of your temp DB. We had an issue like this once at a client site where a few times a day their performance would horribly degrade and occasionally timeout. The problem turned out to be a separate application that was thrashing the temp DB so much it was affecting overall server performance.

Good luck with the continued troubleshooting!

how to download image from any web page in java

If you want to save the image and you know its URL you can do this:

try(InputStream in = new URL("http://example.com/image.jpg").openStream()){
    Files.copy(in, Paths.get("C:/File/To/Save/To/image.jpg"));
}

You will also need to handle the IOExceptions which may be thrown.

How to view transaction logs in SQL Server 2008

You could use the undocumented

DBCC LOG(databasename, typeofoutput)

where typeofoutput:

0: Return only the minimum of information for each operation -- the operation, its context and the transaction ID. (Default)
1: As 0, but also retrieve any flags and the log record length.
2: As 1, but also retrieve the object name, index name, page ID and slot ID.
3: Full informational dump of each operation.
4: As 3 but includes a hex dump of the current transaction log row.

For example, DBCC LOG(database, 1)

You could also try fn_dblog.

For rolling back a transaction using the transaction log I would take a look at Stack Overflow post Rollback transaction using transaction log.

jQuery - get all divs inside a div with class ".container"

Known ID

$(".container > #first");

or

$(".container").children("#first");

or since IDs should be unique within a single document:

$("#first");

The last one is of course the fastest.

Unknown ID

Since you're saying that you don't know their ID top couple of the upper selectors (where #first is written), can be changed to:

$(".container > div");
$(".container").children("div");

The last one (of the first three selectors) that only uses ID is of course not possible to be changed in this way.

If you also need to filter out only those child DIV elements that define ID attribute you'd write selectors down this way:

$(".container > div[id]");
$(".container").children("div[id]");

Attach click handler

Add the following code to attach click handler to any of your preferred selector:

// use selector of your choice and call 'click' on it
$(".container > div").click(function(){
    // if you need element's ID
    var divID = this.id;
    cache your element if you intend to use it multiple times
    var clickedDiv = $(this);
    // add CSS class to it
    clickedDiv.addClass("add-some-class");
    // do other stuff that needs to be done
});

CSS3 Selectors specification

I would also like to point you to CSS3 selector specification that jQuery uses. It will help you lots in the future because there may be some selectors you're not aware of at all and could make your life much much easier.

After your edited question

I'm not completey sure that I know what you're after even though you've written some pseudo code... Anyway. Some parts can still be answered:

$(".container > div[id]").each(function(){
    var context = $(this);
    // get menu parent element: Sub: Show Grid
    // maybe I'm not appending to the correct element here but you should know
    context.appendTo(context.parent().parent());
    context.text("Show #" + this.id);
    context.attr("href", "");
    context.click(function(evt){
        evt.preventDefault();
        $(this).toggleClass("showgrid");
    })
});

the last thee context usages could be combined into a single chained one:

context.text(...).attr(...).click(...);

Regarding DOM elements

You can always get the underlaying DOM element from the jQuery result set.

$(...).get(0)
// or
$(...)[0]

will get you the first DOM element from the jQuery result set. jQuery result is always a set of elements even though there's none in them or only one.

But when I used .each() function and provided an anonymous function that will be called on each element in the set, this keyword actually refers to the DOM element.

$(...).each(function(){
    var DOMelement = this;
    var jQueryElement = $(this);
    ...
});

I hope this clears some things for your.

Rounding integer division (instead of truncating)

The following correctly rounds the quotient to the nearest integer for both positive and negative operands WITHOUT floating point or conditional branches (see assembly output below). Assumes N-bit 2's complement integers.

#define ASR(x) ((x) < 0 ? -1 : 0)  // Compiles into a (N-1)-bit arithmetic shift right
#define ROUNDING(x,y) ( (y)/2 - (ASR((x)^(y)) & (y)))

int RoundedQuotient(int x, int y)
   {
   return (x + ROUNDING(x,y)) / y ;
   }

The value of ROUNDING will have the same sign as the dividend (x) and half the magnitude of the divisor (y). Adding ROUNDING to the dividend thus increases its magnitude before the integer division truncates the resulting quotient. Here's the output of the gcc compiler with -O3 optimization for a 32-bit ARM Cortex-M4 processor:

RoundedQuotient:                // Input parameters: r0 = x, r1 = y
    eor     r2, r1, r0          // r2 = x^y
    and     r2, r1, r2, asr #31 // r2 = ASR(x^y) & y
    add     r3, r1, r1, lsr #31 // r3 = (y < 0) ? y + 1 : y
    rsb     r3, r2, r3, asr #1  // r3 = y/2 - (ASR(x^y) & y)
    add     r0, r0, r3          // r0 = x + (y/2 - (ASR(x^y) & y)
    sdiv    r0, r0, r1          // r0 = (x + ROUNDING(x,y)) / y
    bx      lr                  // Returns r0 = rounded quotient

Display images in asp.net mvc

It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:

public class ImageHandler : IHttpHandler
{
    byte[] bytes;

    public void ProcessRequest(HttpContext context)
    {
        int param;
        if (int.TryParse(context.Request.QueryString["id"], out param))
        {
            using (var db = new MusicLibContext())
            {
                if (param == -1)
                {
                    bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));

                    context.Response.ContentType = "image/png";
                }
                else
                {
                    var data = (from x in db.Images
                                where x.ImageID == (short)param
                                select x).FirstOrDefault();

                    bytes = data.ImageData;

                    context.Response.ContentType = "image/" + data.ImageFileType;
                }

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
                context.Response.End();
            }
        }
        else
        {
            //image not found
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

In the view, i added the ID of the photo to the query string of the handler.

How to load html string in a webview?

read from assets html file

ViewGroup webGroup;
  String content = readContent("content/ganji.html");

        final WebView webView = new WebView(this);
        webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

        webGroup.addView(webView);

Define an <img>'s src attribute in CSS

They are right. IMG is a content element and CSS is about design. But, how about when you use some content elements or properties for design purposes? I have IMG across my web pages that must change if i change the style (the CSS).

Well this is a solution for defining IMG presentation (no really the image) in CSS style.
1: create a 1x1 transparent gif or png.
2: Assign propery "src" of IMG to that image.
3: Define final presentation with "background-image" in the CSS style.

It works like a charm :)

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

This PowerShell code should do the trick

Get-ItemProperty
HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | 
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Format-Table –AutoSize

Twitter Bootstrap 3.0 how do I "badge badge-important" now

The context classes for badge are indeed removed from Bootstrap 3, so you'd have to add some custom CSS to create the same effect like...

.badge-important{background-color:#b94a48;}

Bootply

Return sql rows where field contains ONLY non-alphanumeric characters

SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.

As it happens, you are close. Just need leading+trailing wildcards and move the NOT

 WHERE whatever NOT LIKE '%[a-z0-9]%'

How to use setArguments() and getArguments() methods in Fragments?

Just call getArguments() in your Frag2's onCreateView() method:

public class Frag2 extends Fragment {

     public View onCreateView(LayoutInflater inflater,
         ViewGroup containerObject,
         Bundle savedInstanceState){
         //here is your arguments
         Bundle bundle=getArguments(); 

        //here is your list array 
        String[] myStrings=bundle.getStringArray("elist");   
     }
}

Ordering issue with date values when creating pivot tables

April 20, 2017

I've read all the previously posted answers, and they require a lot of extra work. The quick and simple solution I have found is as follows:

1) Un-group the date field in the pivot table. 2) Go to the Pivot Field List UI. 3) Re-arrange your fields so that the Date field is listed FIRST in the ROWS section. 4) Under the Design menu, select Report Layout / Show in Tabular Form.

By default, Excel sorts by the first field in a pivot table. You may not want the Date field to be first, but it's a compromise that will save you time and much work.

Merging arrays with the same keys

$arr1 = array(
   "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
   "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
   "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
   "3" => array("fid" => 1, "tid" => 7, "name" => "Xi"),
   "4" => array("fid" => 2, "tid" => 9, "name" => "Xigua")
);

if you want to convert this array as following:

$arr2 = array(
   "0" => array(
          "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
          "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
          "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
          "3" => array("fid" => 1, "tid" => 7, "name" => "Xi")
    ),

    "1" => array(
          "0" =>array("fid" => 2, "tid" => 9, "name" => "Xigua")
     )
);

so, my answer will be like this:

$outer_array = array();
$unique_array = array();
foreach($arr1 as $key => $value)
{
    $inner_array = array();

    $fid_value = $value['fid'];
    if(!in_array($value['fid'], $unique_array))
    {
            array_push($unique_array, $fid_value);
            unset($value['fid']);
            array_push($inner_array, $value);
            $outer_array[$fid_value] = $inner_array;


    }else{
            unset($value['fid']);
            array_push($outer_array[$fid_value], $value);

    }
}
var_dump(array_values($outer_array));

hope this answer will help somebody sometime.

python encoding utf-8

You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode before it can encode it back to UTF-8. That is what is failing here:

>>> data = u'\u00c3'            # Unicode data
>>> data = data.encode('utf8')  # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8')         # Try to *re*-encode it
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Just write your data directly to the file, there is no need to encode already-encoded data.

If you instead build up unicode values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open() instead, which returns a file object that will encode unicode values to UTF-8 for you.

You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).

For your MySQL insert problem, you need to do two things:

  • Add charset='utf8' to your MySQLdb.connect() call.

  • Use unicode objects, not str objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:

    artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode
    
    c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    
    # ...
    
    c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
    

It may actually work better if you used codecs.open() to decode the contents automatically instead:

import codecs

sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
    for line in findex:
        if u'#artiste' not in line:
            continue

        artiste=line.split(u'[:::]')[1].strip()

    cursor = sql.cursor()
    cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    if not cursor.fetchone()[0]:
        cursor = sql.cursor()
        cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
        artists_inserted += 1

You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:

How can you test if an object has a specific property?

I've been using the following which returns the property value, as it would be accessed via $thing.$prop, if the "property" would be to exist and not throw a random exception. If the property "doesn't exist" (or has a null value) then $null is returned: this approach functions in/is useful for strict mode, because, well, Gonna Catch 'em All.

I find this approach useful because it allows PS Custom Objects, normal .NET objects, PS HashTables, and .NET collections like Dictionary to be treated as "duck-typed equivalent", which I find is a fairly good fit for PowerShell.

Of course, this does not meet the strict definition of "has a property".. which this question may be explicitly limited to. If accepting the larger definition of "property" assumed here, the method can be trivially modified to return a boolean.

Function Get-PropOrNull {
    param($thing, [string]$prop)
    Try {
        $thing.$prop
    } Catch {
    }
}

Examples:

Get-PropOrNull (Get-Date) "Date"                   # => Monday, February 05, 2018 12:00:00 AM
Get-PropOrNull (Get-Date) "flub"                   # => $null
Get-PropOrNull (@{x="HashTable"}) "x"              # => "HashTable"
Get-PropOrNull ([PSCustomObject]@{x="Custom"}) "x" # => "Custom"
$oldDict = New-Object "System.Collections.HashTable"
$oldDict["x"] = "OldDict"
Get-PropOrNull $d "x"                              # => "OldDict"

And, this behavior might not [always] be desired.. ie. it's not possible to distinguish between x.Count and x["Count"].

Clear ComboBox selected text

This is what you need:

comboBox1.ResetText();

JavaScript - Get minutes between two dates

The following code worked for me,

function timeDiffCalc(dateNow,dateFuture) {
    var newYear1 = new Date(dateNow);
    var newYear2 = new Date(dateFuture);

        var dif = (newYear2 - newYear1);
        var dif = Math.round((dif/1000)/60);
        console.log(dif);

}

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

Because python checks in the directories in sequential order starting at the first directory in sys.path list, till it find the .py file it was looking for.

Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

So, most probably, you had a .py file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).

Also, a thing to note about ImportErrors , lets say the import error says - ImportError: No module named main - it doesn't mean the main.py is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py or some other file.

Example -

My directory structure looks like -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py

Now From testmain.py , I call from shared import phtest , it works fine.

Now lets say I introduce a shared.py in test directory` , example -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py 
  - shared.py

Now when I try to do from shared import phtest from testmain.py , I will get the error -

ImportError: cannot import name 'phtest'

As you can see above, the file that is causing the issue is shared.py , not phtest.py .

In Gradle, is there a better way to get Environment Variables?

I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:

home = System.getenv('HOME')

It helps to keep in mind that anything that works in pure Java will work in Gradle too.

Java: How to access methods from another class

You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.

1) Give Alphas a Beta in the constructor. In class Alpha write:

public class Alpha {
   private Beta beta;
   public Alpha(Beta beta) {
     this.beta = beta; 
   }

and call cAlpha = new Alpha(cBeta) from main()

2) give Alphas a mutator that gives them a beta. In class Alpha write:

public class Alpha {
   private Beta beta;
   public void setBeta (Beta newBeta) {
     this.beta = beta;
   }

and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or

3) have a beta as an argument to doSomethingAlpha. in class Alpha write:

public void DoSomethingAlpha(Beta cBeta) {
      cbeta.DoSomethingBeta()
}

Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!

How can I convince IE to simply display application/json rather than offer to download it?

If you are okay with just having IE open the JSON into a notepad, you can change your system's default program for .json files to Notepad.

To do this, create or find a .json file, right mouse click, and select "Open With" or "Choose Default Program."

This might come in handy if you by chance want to use Internet Explorer but your IT company wont let you edit your registry. Otherwise, I recommend the above answers.

CSS transition between left -> right and top -> bottom positions

For elements with dynamic width it's possible to use transform: translateX(-100%); to counter the horizontal percentage value. This leads to two possible solutions:

1. Option: moving the element in the entire viewport:

Transition from:

transform: translateX(0);

to

transform: translateX(calc(100vw - 100%));

_x000D_
_x000D_
#viewportPendulum {_x000D_
  position: fixed;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateX(calc(100vw - 100%));_x000D_
  }_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
_x000D_
_x000D_

2. Option: moving the element in the parent container:

Transition from:

transform: translateX(0);
left: 0;

to

left: 100%;
transform: translateX(-100%);

_x000D_
_x000D_
#parentPendulum {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  animation: 2s ease-in-out infinite alternate swingParent;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
    left: 0;_x000D_
  }_x000D_
  to {_x000D_
    left: 100%;_x000D_
    transform: translateX(-100%);_x000D_
  }_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  padding: 2rem 0;_x000D_
  margin: 2rem 15%;_x000D_
  background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Demo on Codepen

Note: This approach can easily be extended to work for vertical positioning. Visit example here.

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

NOTE1: All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes).

NOTE2: Support library should not use a different version than the compileSdkVersion

For API 28 you can use:

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:recyclerview-v7:28.0.0-alpha1'

https://mvnrepository.com/artifact/com.android.support/appcompat-v7/28.0.0-alpha1 https://mvnrepository.com/artifact/com.android.support/recyclerview-v7/28.0.0-alpha1

All support libraries: https://mvnrepository.com/artifact/com.android.support

Deploy a project using Git push

Given an environment where you have multiple developers accessing the same repository the following guidelines may help.

Ensure that you have a unix group that all devs belong to and give ownership of the .git repository to that group.

  1. In the .git/config of the server repository set sharedrepository = true. (This tells git to allow multiple users which is needed for commits and deployment.

  2. set the umask of each user in their bashrc files to be the same - 002 is a good start

NodeJs : TypeError: require(...) is not a function

Remember to export your routes.js.

In routes.js, write your routes and all your code in this function module:

exports = function(app, passport) {

/* write here your code */ 

}

How to select distinct rows in a datatable and store into an array

objds.Table1.Select(r => r.ProcessName).AsEnumerable().Distinct();

Is it possible to forward-declare a function in Python?

You can't forward-declare a function in Python. If you have logic executing before you've defined functions, you've probably got a problem anyways. Put your action in an if __name__ == '__main__' at the end of your script (by executing a function you name "main" if it's non-trivial) and your code will be more modular and you'll be able to use it as a module if you ever need to.

Also, replace that list comprehension with a generator express (i.e., print "\n".join(str(bla) for bla in sorted(mylist, cmp=cmp_configs)))

Also, don't use cmp, which is deprecated. Use key and provide a less-than function.

Frequency table for a single variable

Maybe .value_counts()?

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

How add "or" in switch statements?

You do it by stacking case labels:

switch(myvar)
{
    case 2:
    case 5:
    ...
    break;

    case 7: 
    case 12:
    ...
    break;
    ...
}

CSS to select/style first word

What you are looking for is a pseudo-element that doesn't exist. There is :first-letter and :first-line, but no :first-word.

You can of course do this with JavaScript. Here's some code I found that does this: http://www.dynamicsitesolutions.com/javascript/first-word-selector/

python-pandas and databases like mysql

import the module

import pandas as pd
import oursql

connect

conn=oursql.connect(host="localhost",user="me",passwd="mypassword",db="classicmodels")
sql="Select customerName, city,country from customers order by customerName,country,city"
df_mysql = pd.read_sql(sql,conn)
print df_mysql

That works just fine and using pandas.io.sql frame_works (with the deprecation warning). Database used is the sample database from mysql tutorial.

Filtering a data frame by values in a column

Thought I'd update this with a dplyr solution

library(dplyr)    
filter(studentdata, Drink == "water")

How do I center floated elements?

Add this to you styling

position:relative;
float: left;
left: calc(50% - *half your container length here);

*If your container width is 50px put 25px, if it is 10em put 5em.

How to edit a JavaScript alert box title?

No, you can't.

It's a security/anti-phishing feature.

How do I check if a PowerShell module is installed?

You can use the ListAvailable option of Get-Module:

if (Get-Module -ListAvailable -Name SomeModule) {
    Write-Host "Module exists"
} 
else {
    Write-Host "Module does not exist"
}

How to simulate a touch event in Android?

use adb Shell Commands to simulate the touch event

adb shell input tap x y 

and also 

adb shell sendevent /dev/input/event0 3 0 5 
adb shell sendevent /dev/input/event0 3 1 29 

How to implement the ReLU function in Numpy

numpy didn't have the function of relu, but you define it by yourself as follow:

def relu(x):
    return np.maximum(0, x)

for example:

arr = np.array([[-1,2,3],[1,2,3]])

ret = relu(arr)
print(ret) # print [[0 2 3] [1 2 3]]

How to count certain elements in array?

I'm a begin fan of js array's reduce function.

const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)

In fact if you really want to get fancy you can create a count function on the Array prototype. Then you can reuse it.

Array.prototype.count = function(filterMethod) {
  return this.reduce((count, item) => filterMethod(item)? count + 1 : count, 0);
} 

Then do

const myArray =[1, 2, 3, 5, 2, 8, 9, 2]
const count = myArray.count(x => x==2)

Git push existing repo to a new and different remote repo server?

If you have Existing Git repository:

cd existing_repo
git remote rename origin old-origin
git remote add origin https://gitlab.com/newproject
git push -u origin --all
git push -u origin --tags

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

No such keg: /usr/local/Cellar/git

Had a similar issue while installing "Lua" in OS X using homebrew. I guess it could be useful for other users facing similar issue in homebrew.

On running the command:

$ brew install lua

The command returned an error:

Error: /usr/local/opt/lua is not a valid keg
(in general the error can be of /usr/local/opt/ is not a valid keg

FIXED it by deleting the file/directory it is referring to, i.e., deleting the "/usr/local/opt/lua" file.

root-user # rm -rf /usr/local/opt/lua

And then running the brew install command returned success.

jQuery, get ID of each element in a class using .each?

Try this, replacing .myClassName with the actual name of the class (but keep the period at the beginning).

$('.myClassName').each(function() {
    alert( this.id );
});

So if the class is "test", you'd do $('.test').each(func....

This is the specific form of .each() that iterates over a jQuery object.

The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t.

Using that form of $.each(), you would need to do it like this:

$.each($('.myClassName'), function() {
    alert( this.id );
});

...which will have the same result as the example above.

How to count number of files in each directory?

Slightly modified version of Sebastian's answer using find instead of du (to exclude file-size-related overhead that du has to perform and that is never used):

 find ./ -mindepth 2 -type f | cut -d/ -f2 | sort | uniq -c | sort -nr

-mindepth 2 parameter is used to exclude files in current directory. If you remove it, you'll see a bunch of lines like the following:

  234 dir1
  123 dir2
    1 file1
    1 file2
    1 file3
      ...
    1 fileN

(much like the du-based variant does)

If you do need to count the files in current directory as well, use this enhanced version:

{ find ./ -mindepth 2 -type f | cut -d/ -f2 | sort && find ./ -maxdepth 1 -type f | cut -d/ -f1; } | uniq -c | sort -nr

The output will be like the following:

  234 dir1
  123 dir2
   42 .

Setting up redirect in web.config file

In case that you need to add the http redirect in many sites, you could use it as a c# console program:

   class Program
{
    static int Main(string[] args)
    {
        if (args.Length < 3)
        {
            Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
            return 1;
        }

        if (args.Length == 3)
        {
            if (args[0].ToLower() == "-insert-redirect")
            {
                var path = args[1];
                var value = args[2];

                if (InsertRedirect(path, value))
                    Console.WriteLine("Redirect added.");
                return 0;
            }
        }

        Console.WriteLine("Wrong parameters.");
        return 1;

    }

    static bool InsertRedirect(string path, string value)
    {
        try
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(path);

            // This should find the appSettings node (should be only one):
            XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");

            var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
            if (existNode != null)
                return false;

            // Create new <add> node
            XmlNode nodeNewKey = doc.CreateElement("httpRedirect");

            XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
            XmlAttribute attributeDestination = doc.CreateAttribute("destination");
            //XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");

            // Assign values to both - the key and the value attributes:

            attributeEnable.Value = "true";
            attributeDestination.Value = value;
            //attributeResponseStatus.Value = "Permanent";

            // Add both attributes to the newly created node:
            nodeNewKey.Attributes.Append(attributeEnable);
            nodeNewKey.Attributes.Append(attributeDestination);
            //nodeNewKey.Attributes.Append(attributeResponseStatus);

            // Add the node under the 
            nodeAppSettings.AppendChild(nodeNewKey);
            doc.Save(path);

            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Exception adding redirect: {e.Message}");
            return false;
        }
    }
}

How to fix: "HAX is not working and emulator runs in emulation mode"

If you are on a mac you can install haxm using homebrew via cask which is a built-in extension (as of 2015) which allows installing non-open-source and desktop apps (i.e. chrome, firefox, eclipse, etc.):

brew cask install intel-haxm 

Android Studio

If you are using Android Studio then you can achieve the same result from the menu Tools ? SDK Manager, and then on the SDK Tools tab, select the checkbox for Intel x86 Emulator Accelerator (HAXM installer), and click Ok.

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

How to print a debug log?

You need to change your frame of mind. You are writing PHP, not whatever else it is that you are used to write. Debugging in PHP is not done in a console environment.

In PHP, you have 3 categories of debugging solutions:

  1. Output to a webpage (see dBug library for a nicer view of things).
  2. Write to a log file
  3. In session debugging with xDebug

Learn to use those instead of trying to make PHP behave like whatever other language you are used to.

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

How to modify the nodejs request default timeout time?

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

How to implement class constructor in Visual Basic?

If you mean VB 6, that would be Private Sub Class_Initialize().

http://msdn.microsoft.com/en-us/library/55yzhfb2(VS.80).aspx

If you mean VB.NET it is Public Sub New() or Shared Sub New().

Best Way to read rss feed in .net Using C#

Add System.ServiceModel in references

Using SyndicationFeed:

string url = "http://fooblog.com/feed";
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();
foreach (SyndicationItem item in feed.Items)
{
    String subject = item.Title.Text;    
    String summary = item.Summary.Text;
    ...                
}

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

find filenames NOT ending in specific extensions on Unix?

Other solutions on this page aren't desirable if you have a long list of extensions -- maintaining a long sequence of -not -name 'this' -not -name 'that' -not -name 'other' would be tedious and error-prone -- or if the search is programmatic and the list of extensions is built at runtime.

For those situations, a solution that more clearly separates data (the list of extensions) and code (the parameters to find) may be desirable. Given a directory & file structure that looks like this:

.
+-- a
    +-- 1.txt
    +-- 15.xml
    +-- 8.dll
    +-- b
    ¦   +-- 16.xml
    ¦   +-- 2.txt
    ¦   +-- 9.dll
    ¦   +-- c
    ¦       +-- 10.dll
    ¦       +-- 17.xml
    ¦       +-- 3.txt
    +-- d
    ¦   +-- 11.dll
    ¦   +-- 18.xml
    ¦   +-- 4.txt
    ¦   +-- e
    ¦       +-- 12.dll
    ¦       +-- 19.xml
    ¦       +-- 5.txt
    +-- f
        +-- 13.dll
        +-- 20.xml
        +-- 6.txt
        +-- g
            +-- 14.dll
            +-- 21.xml
            +-- 7.txt

You can do something like this:

## data section, list undesired extensions here
declare -a _BADEXT=(xml dll)

## code section, this never changes
BADEXT="$( IFS="|" ; echo "${_BADEXT[*]}" | sed 's/|/\\|/g' )"
find . -type f ! -regex ".*\.\($BADEXT\)"

Which results in:

./a/1.txt
./a/b/2.txt
./a/b/c/3.txt
./a/d/4.txt
./a/d/e/5.txt
./a/f/6.txt
./a/f/g/7.txt

You can change the extensions list without changing the code block.

NOTE doesn't work with native OSX find - use gnu find instead.

Cannot delete or update a parent row: a foreign key constraint fails

I tried the solution mentioned by @Alino Manzi but it didn't work for me on the WordPress related tables using wpdb.

then I modified the code as below and it worked

SET FOREIGN_KEY_CHECKS=OFF; //disabling foreign key

//run the queries which are giving foreign key errors

SET FOREIGN_KEY_CHECKS=ON; // enabling foreign key

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I'd say it depends on what you need it for:

  1. If you need it just to get 3 columns layout, I'd suggest to do it with float.

  2. If you need it for menu, you can use inline-block. For the whitespace problem, you can use few tricks as described by Chris Coyier here http://css-tricks.com/fighting-the-space-between-inline-block-elements/.

  3. If you need to make a multiple choice option, which the width needs to spread evenly inside a specified box, then I'd prefer display: table. This will not work correctly in some browsers, so it depends on your browser support.

Lastly, what might be the best method is using flexbox. The spec for this has changed few times, so it's not stable just yet. But once it has been finalized, this will be the best method I reckon.

Why is my element value not getting changed? Am I using the wrong function?

It's document.getElementById, not document.getElementsByID

I'm assuming you have <input id="Tue" ...> somewhere in your markup.

XMLHttpRequest cannot load an URL with jQuery

I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi.

My change was only in web.config file and is working.

<httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol> 

Thanks for you solution @Rytis!

Subtracting time.Duration from time in Go

There's time.ParseDuration which will happily accept negative durations, as per manual. Otherwise put, there's no need to negate a duration where you can get an exact duration in the first place.

E.g. when you need to substract an hour and a half, you can do that like so:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    duration, _ := time.ParseDuration("-1.5h")

    then := now.Add(duration)

    fmt.Println("then:", then)
}

https://play.golang.org/p/63p-T9uFcZo

Simulating a click in jQuery/JavaScript on a link

Try this

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
        return;
    }
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(buttonId).dispatchEvent(e);
    } else {
        document.getElementById(buttonId).click();
    }
}

and you can use it like

submitRequest("target-element-id");

How do I get the different parts of a Flask request's url?

You can examine the url through several Request fields:

Imagine your application is listening on the following application root:

http://www.example.com/myapplication

And a user requests the following URI:

http://www.example.com/myapplication/foo/page.html?x=y

In this case the values of the above mentioned attributes would be the following:

    path             /foo/page.html
    full_path        /foo/page.html?x=y
    script_root      /myapplication
    base_url         http://www.example.com/myapplication/foo/page.html
    url              http://www.example.com/myapplication/foo/page.html?x=y
    url_root         http://www.example.com/myapplication/

You can easily extract the host part with the appropriate splits.

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

refering to Deepak Vishwakarma's answer, I tried with that and was facing same problem with the url-problem. I installed maven-3.6.3 and inside .m2 folder I found a

settings.xml.bak

file and from that copied that mirror link and just changed url what @Deepak did. It worked like charm! Mirror link I got from that .bak file

http://local.maven.repo:9081/nexus/content/groups/public

Then executed :

mvn clean 
mvn clean install

SQL Error: ORA-00922: missing or invalid option

there's nothing wrong with using CHAR like that.. I think your problem is that you have a space in your tablename. It should be: charteredflight or chartered_flight..

Selection with .loc in python

This is using dataframes from the pandas package. The "index" part can be either a single index, a list of indices, or a list of booleans. This can be read about in the documentation: https://pandas.pydata.org/pandas-docs/stable/indexing.html

So the index part specifies a subset of the rows to pull out, and the (optional) column_name specifies the column you want to work with from that subset of the dataframe. So if you want to update the 'class' column but only in rows where the class is currently set as 'versicolor', you might do something like what you list in the question:

iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'

Is there any way to delete local commits in Mercurial?

You can get around this even more easily with the Rebase extension, just use hg pull --rebase and your commits are automatically re-comitted to the pulled revision, avoiding the branching issue.

How to convert a JSON string to a Map<String, String> with Jackson JSON

just wanted to give a Kotlin answer

val propertyMap = objectMapper.readValue<Map<String,String>>(properties, object : TypeReference<Map<String, String>>() {})

Can I configure a subdomain to point to a specific port on my server

If you only got one IP on the server, there is no chance to do that. DNS is a simple name to number (IP) resolver. If you have two IPs on the server, you can point each subdomain to each of the IP-addresses and run both servers on the default port on each IP.
one.example.com -> 127.0.0.1 (server: 127.0.0.1:25565)
two.example.com -> 127.0.0.2 (server: 127.0.0.2:25565)

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

In my case I added the missing import, which was the ReactiveFormsModule.

What's the difference between jquery.js and jquery.min.js?

Both contain the same functionality but the .min.js equivalent has been optimized in size. You can open both files and take a look at them. In the .min.js file you'll notice that all variables names have been reduced to short names and that most whitespace & comments have been taken out.

How do I show running processes in Oracle DB?

This one shows SQL that is currently "ACTIVE":-

select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/

This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:

select
  object_name, 
  object_type, 
  session_id, 
  type,         -- Type or system/user lock
  lmode,        -- lock mode in which session holds lock
  request, 
  block, 
  ctime         -- Time since current mode was granted
from
  v$locked_object, all_objects, v$lock
where
  v$locked_object.object_id = all_objects.object_id AND
  v$lock.id1 = all_objects.object_id AND
  v$lock.sid = v$locked_object.session_id
order by
  session_id, ctime desc, object_name
/

This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.

COLUMN percent FORMAT 999.99 

SELECT sid, to_char(start_time,'hh24:mi:ss') stime, 
message,( sofar/totalwork)* 100 percent 
FROM v$session_longops
WHERE sofar/totalwork < 1
/

How to start rails server?

In rails 2.3.x application you can start your server by following command:

ruby script/server

In rails 3.x, you need to go for:

rails s

Swap DIV position with CSS only

The accepted answer worked for most browsers but for some reason on iOS Chrome and Safari browsers the content that should have shown second was being hidden. I tried some other steps that forced content to stack on top of each other, and eventually I tried the following solution that gave me the intended effect (switch content display order on mobile screens), without bugs of stacked or hidden content:

.container {
  display:flex;
  flex-direction: column-reverse;
}

.section1,
.section2 {
  height: auto;
}

Which .NET Dependency Injection frameworks are worth looking into?

Autofac. https://github.com/autofac/Autofac It is really fast and pretty good. Here is a link with comparisons (made after Ninject fixed a memory leak issue).

http://www.codinginstinct.com/2008/05/ioc-container-benchmark-rerevisted.html

Bootstrap date time picker

In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
    <html lang="en">_x000D_
    <head>_x000D_
      <meta charset="utf-8">_x000D_
      <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    _x000D_
    _x000D_
      <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
    </head>_x000D_
    _x000D_
    _x000D_
    <body>_x000D_
    _x000D_
       <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    _x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Align items in a stack panel?

for windows 10 use relativePanel instead of stack panel, and use

relativepanel.alignrightwithpanel="true"

for the contained elements.

How to determine if a list of polygon points are in clockwise order?

For what it is worth, I used this mixin to calculate the winding order for Google Maps API v3 apps.

The code leverages the side effect of polygon areas: a clockwise winding order of vertexes yields a positive area, while a counter-clockwise winding order of the same vertexes produces the same area as a negative value. The code also uses a sort of private API in the Google Maps geometry library. I felt comfortable using it - use at your own risk.

Sample usage:

var myPolygon = new google.maps.Polygon({/*options*/});
var isCW = myPolygon.isPathClockwise();

Full example with unit tests @ http://jsfiddle.net/stevejansen/bq2ec/

/** Mixin to extend the behavior of the Google Maps JS API Polygon type
 *  to determine if a polygon path has clockwise of counter-clockwise winding order.
 *  
 *  Tested against v3.14 of the GMaps API.
 *
 *  @author  [email protected]
 *
 *  @license http://opensource.org/licenses/MIT
 *
 *  @version 1.0
 *
 *  @mixin
 *  
 *  @param {(number|Array|google.maps.MVCArray)} [path] - an optional polygon path; defaults to the first path of the polygon
 *  @returns {boolean} true if the path is clockwise; false if the path is counter-clockwise
 */
(function() {
  var category = 'google.maps.Polygon.isPathClockwise';
     // check that the GMaps API was already loaded
  if (null == google || null == google.maps || null == google.maps.Polygon) {
    console.error(category, 'Google Maps API not found');
    return;
  }
  if (typeof(google.maps.geometry.spherical.computeArea) !== 'function') {
    console.error(category, 'Google Maps geometry library not found');
    return;
  }

  if (typeof(google.maps.geometry.spherical.computeSignedArea) !== 'function') {
    console.error(category, 'Google Maps geometry library private function computeSignedArea() is missing; this may break this mixin');
  }

  function isPathClockwise(path) {
    var self = this,
        isCounterClockwise;

    if (null === path)
      throw new Error('Path is optional, but cannot be null');

    // default to the first path
    if (arguments.length === 0)
        path = self.getPath();

    // support for passing an index number to a path
    if (typeof(path) === 'number')
        path = self.getPaths().getAt(path);

    if (!path instanceof Array && !path instanceof google.maps.MVCArray)
      throw new Error('Path must be an Array or MVCArray');

    // negative polygon areas have counter-clockwise paths
    isCounterClockwise = (google.maps.geometry.spherical.computeSignedArea(path) < 0);

    return (!isCounterClockwise);
  }

  if (typeof(google.maps.Polygon.prototype.isPathClockwise) !== 'function') {
    google.maps.Polygon.prototype.isPathClockwise = isPathClockwise;
  }
})();

How to run a Powershell script from the command line and pass a directory as a parameter

Add the param declation at the top of ps1 file

test.ps1

param(
  # Our preferred encoding
  [parameter(Mandatory=$false)]
  [ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
  [string]$Encoding = "UTF8"
)

write ("Encoding : {0}" -f $Encoding)

result

C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII

How to bind 'touchstart' and 'click' events but not respond to both?

I had to do something similar. Here is a simplified version of what worked for me. If a touch event is detected, remove the click binding.

$thing.on('touchstart click', function(event){
  if (event.type == "touchstart")
    $(this).off('click');

  //your code here
});

In my case the click event was bound to an <a> element so I had to remove the click binding and rebind a click event which prevented the default action for the <a> element.

$thing.on('touchstart click', function(event){
  if (event.type == "touchstart")
    $(this).off('click').on('click', function(e){ e.preventDefault(); });

  //your code here
});

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

How can I catch all the exceptions that will be thrown through reading and writing a file?

Do you mean catch an Exception of any type that is thrown, as opposed to just specific Exceptions?

If so:

try {
   //...file IO...
} catch(Exception e) {
   //...do stuff with e, such as check its type or log it...
}

Does Python have “private” variables in classes?

Sorry guys for "resurrecting" the thread, but, I hope this will help someone:

In Python3 if you just want to "encapsulate" the class attributes, like in Java, you can just do the same thing like this:

class Simple:
    def __init__(self, str):
        print("inside the simple constructor")
        self.__s = str

    def show(self):
        print(self.__s)

    def showMsg(self, msg):
        print(msg + ':', self.show())

To instantiate this do:

ss = Simple("lol")
ss.show()

Note that: print(ss.__s) will throw an error.

In practice, Python3 will obfuscate the global attribute name. Turning this like a "private" attribute, like in Java. The attribute's name is still global, but in an inaccessible way, like a private attribute in other languages.

But don't be afraid of it. It doesn't matter. It does the job too. ;)

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

this is easy,
if you use .htaccess , check http: for https: ,
if you use codeigniter, check config : url_base -> you url http change for https.....
I solved my problem.

How can I get the length of text entered in a textbox using jQuery?

If your textbox has an id attribute of "mytextbox", then you can get the length like this:

var myLength = $("#mytextbox").val().length;
  • $("#mytextbox") finds the textbox by its id.
  • .val() gets the value of the input element entered by the user, which is a string.
  • .length gets the number of characters in the string.

Stop MySQL service windows

to stop the service:

sc stop mysql56

and to start it:

sc start mysql56

you might need to change the mysql56 to whatever your version is.

C: printf a float value

printf("%.<number>f", myFloat) //where <number> - digit after comma

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

How to call a parent method from child class in javascript?

Here's how its done: ParentClass.prototype.myMethod();

Or if you want to call it in the context of the current instance, you can do: ParentClass.prototype.myMethod.call(this)

Same goes for calling a parent method from child class with arguments: ParentClass.prototype.myMethod.call(this, arg1, arg2, ..) * Hint: use apply() instead of call() to pass arguments as an array.

Wait till a Function with animations is finished until running another Function

You can do it via callback function.

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});

function function1(param, callback) { ...do stuff callback(); }

Docker is installed but Docker Compose is not ? why?

just use brew:

brew install docker-compose

pthread function from a class

C++ : How to pass class member function to pthread_create()?

http://thispointer.com/c-how-to-pass-class-member-function-to-pthread_create/

typedef void * (*THREADFUNCPTR)(void *);

class C { 
   // ...
   void *print(void *) { cout << "Hello"; }
}

pthread_create(&threadId, NULL, (THREADFUNCPTR) &C::print, NULL);

Convert Bitmap to File

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

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

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

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

Dynamic button click event handler

You can use AddHandler to add a handler for any event.

For example, this might be:

AddHandler theButton.Click, AddressOf Me.theButton_Click

rand() between 0 and 1

In my case (I'm using VS 2017) works fine the following simple code:

#include "pch.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

int main()
{
    srand(time(NULL));

    for (int i = 1000; i > 0; i--) //try it thousand times
    {
        int randnum = (double)rand() / ((double)RAND_MAX + 1);
        std::cout << " rnum: " << rand()%2 ;
    }
} 

Python group by

Do it in 2 steps. First, create a dictionary.

>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for v, k in input: res[k].append(v)
...

Then, convert that dictionary into the expected format.

>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]

It is also possible with itertools.groupby but it requires the input to be sorted first.

>>> sorted_input = sorted(input, key=itemgetter(1))
>>> groups = groupby(sorted_input, key=itemgetter(1))
>>> [{'type':k, 'items':[x[0] for x in v]} for k, v in groups]
[{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]

Note both of these do not respect the original order of the keys. You need an OrderedDict if you need to keep the order.

>>> from collections import OrderedDict
>>> res = OrderedDict()
>>> for v, k in input:
...   if k in res: res[k].append(v)
...   else: res[k] = [v]
... 
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}]

How to ALTER multiple columns at once in SQL Server

If i understood your question correctly you can add multiple columns in a table by using below mentioned query.

Query:

Alter table tablename add (column1 dataype, column2 datatype);

Android Studio rendering problems

In new update android studio 2.2 facing rendering issue then follow this steps.

I fixed it - in styles.xml file I changed

"Theme.AppCompat.Light.DarkActionBar"

to

"Base.Theme.AppCompat.Light.DarkActionBar"

It's some kind of hack I came across a long time ago to solve similar rendering problems in previous Android Studio versions.

Apply CSS to jQuery Dialog Buttons

You can use the open event handler to apply additional styling:

 open: function(event) {
     $('.ui-dialog-buttonpane').find('button:contains("Cancel")').addClass('cancelButton');
 }

How to rename uploaded file before saving it into a directory?

The move_uploaded_file will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file

Delete all rows in an HTML table

Assing some id to tbody tag. i.e. . After this, the following line should retain the table header/footer and remove all the rows.

document.getElementById("yourID").innerHTML="";

And, if you want the entire table (header/rows/footer) to wipe out, then set the id at table level i.e.

How do I set the time zone of MySQL?

This work for me for a location in India:

SET GLOBAL time_zone = "Asia/Calcutta";
SET time_zone = "+05:30";
SET @@session.time_zone = "+05:30";

Reading CSV file and storing values into an array

Hi all, I created a static class for doing this. + column check + quota sign removal

public static class CSV
{
    public static List<string[]> Import(string file, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
    {
        return ReadCSVFile(file, csvDelimiter, ignoreHeadline, removeQuoteSign);
    }

    private static List<string[]> ReadCSVFile(string filename, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
    {
        string[] result = new string[0];
        List<string[]> lst = new List<string[]>();

        string line;
        int currentLineNumner = 0;
        int columnCount = 0;

        // Read the file and display it line by line.  
        using (System.IO.StreamReader file = new System.IO.StreamReader(filename))
        {
            while ((line = file.ReadLine()) != null)
            {
                currentLineNumner++;
                string[] strAr = line.Split(csvDelimiter);
                // save column count of dirst line
                if (currentLineNumner == 1)
                {
                    columnCount = strAr.Count();
                }
                else
                {
                    //Check column count of every other lines
                    if (strAr.Count() != columnCount)
                    {
                        throw new Exception(string.Format("CSV Import Exception: Wrong column count in line {0}", currentLineNumner));
                    }
                }

                if (removeQuoteSign) strAr = RemoveQouteSign(strAr);

                if (ignoreHeadline)
                {
                    if(currentLineNumner !=1) lst.Add(strAr);
                }
                else
                {
                    lst.Add(strAr);
                }
            }

        }

        return lst;
    }
    private static string[] RemoveQouteSign(string[] ar)
    {
        for (int i = 0;i< ar.Count() ; i++)
        {
            if (ar[i].StartsWith("\"") || ar[i].StartsWith("'")) ar[i] = ar[i].Substring(1);
            if (ar[i].EndsWith("\"") || ar[i].EndsWith("'")) ar[i] = ar[i].Substring(0,ar[i].Length-1);

        }
        return ar;
    }

}

How do I delete all messages from a single queue using the CLI?

rabbitmqadmin is the perfect tool for this

rabbitmqadmin purge queue name=name_of_the_queue_to_be_purged

How to do case insensitive string comparison?

str = 'Lol', str2 = 'lOl', regex = new RegExp('^' + str + '$', 'i');
if (regex.test(str)) {
    console.log("true");
}