Programs & Examples On #Box2d

Box2D is a free open source 2-dimensional physics simulator engine written in C++ by Erin Catto and published under the zlib license

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I have found following solution to replace following code

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'
        classpath 'com.google.gms:google-services:3.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

It's work fine for me

sorting a vector of structs

Just make a comparison function/functor:

bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.word.size() < b.word.size();
}

std::sort(info.begin(), info.end(), my_cmp);

Or provide an bool operator<(const data& a) const in your data class:

struct data {
    string word;
    int number;

    bool operator<(const data& a) const
    {
        return word.size() < a.word.size();
    }
};

or non-member as Fred said:

struct data {
    string word;
    int number;
};

bool operator<(const data& a, const data& b)
{
    return a.word.size() < b.word.size();
}

and just call std::sort():

std::sort(info.begin(), info.end());

setting request headers in selenium

You can do it with PhantomJSDriver.

PhantomJSDriver pd = ((PhantomJSDriver) ((WebDriverFacade) getDriver()).getProxiedDriver());
pd.executePhantomJS(
            "this.onResourceRequested = function(request, net) {" +
            "   net.setHeader('header-name', 'header-value')" +
            "};");

Using the request object, you can filter also so the header won't be set for every request.

Controlling a USB power supply (on/off) with Linux

I had a problem when connecting my android phone, I couldn't charge my phone because the power switch on and then off ... PowerTop let me find this setting and was useful to fix the issue ( auto value was causing issue):

echo 'on' | sudo tee /sys/bus/usb/devices/1-1/power/control

Access restriction on class due to restriction on required library rt.jar?

Just change the order of build path libraries of your project. Right click on project>Build Path> Configure Build Path>Select Order and Export(Tab)>Change the order of the entries. I hope moving the "JRE System library" to the bottom will work. It worked so for me. Easy and simple....!!!

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Using HTML and Local Images Within UIWebView

Swift Version of Lithu T.V's answer:

webView.loadHTMLString(htmlString, baseURL: NSBundle.mainBundle().bundleURL)

There is no argument given that corresponds to the required formal parameter - .NET Error

You have a constructor which takes 2 parameters. You should write something like:

new ErrorEventArg(errorMsv, lastQuery)

It's less code and easier to read.

EDIT

Or, in order for your way to work, you can try writing a default constructor for ErrorEventArg which would have no parameters, like this:

public ErrorEventArg() {}

Fatal Error :1:1: Content is not allowed in prolog

The real solution that I found for this issue was by disabling any XML Format post processors. I have added a post processor called "jp@gc - XML Format Post Processor" and started noticing the error "Fatal Error :1:1: Content is not allowed in prolog"

By disabling the post processor had stopped throwing those errors.

How to select from subquery using Laravel Query Builder?

Laravel v5.6.12 (2018-03-14) added fromSub() and fromRaw() methods to query builder (#23476).

The accepted answer is correct but can be simplified into:

DB::query()->fromSub(function ($query) {
    $query->from('abc')->groupBy('col1');
}, 'a')->count();

The above snippet produces the following SQL:

select count(*) as aggregate from (select * from `abc` group by `col1`) as `a`

JPA and Hibernate - Criteria vs. JPQL or HQL

I usually use Criteria when I don't know what the inputs will be used on which pieces of data. Like on a search form where the user can enter any of 1 to 50 items and I don't know what they will be searching for. It is very easy to just append more to the criteria as I go through checking for what the user is searching for. I think it would be a little more troublesome to put an HQL query in that circumstance. HQL is great though when I know exactly what I want.

Set Page Title using PHP

Move the data retrieval at the top of the script, and after that use:

<title>Ultan.me - <?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></title>

Excel: Use a cell value as a parameter for a SQL query

If you are using microsoft query, you can add "?" to your query...

select name from user where id= ?

that will popup a small window asking for the cell/data/etc when you go back to excel.

In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.

I get conflicting provisioning settings error when I try to archive to submit an iOS app

I opened the project file in a text editor "Atom" then I searched for the provisioning profile id and deleted it.

How can I access Google Sheet spreadsheets only with Javascript?

There's a solution that does not require one to publish the spreadsheet. However, the sheet does need to be 'Shared'. More specifically, one needs to share the sheet in a manner where anyone with the link can access the spreadsheet. Once this is done, one can use the Google Sheets HTTP API.

First up, you need an Google API key. Head here: https://developers.google.com/places/web-service/get-api-key NB. Please be aware of the security ramifications of having an API key made available to the public: https://support.google.com/googleapi/answer/6310037

Get all data for a spreadsheet - warning, this can be a lot of data.

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true

Get sheet metadata

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}

Get a range of cells

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{sheetName}!{cellRange}?key={yourAPIKey}

Now armed with this information, one can use AJAX to retrieve data and then manipulate it in JavaScript. I would recommend using axios.

var url = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true";                                                             
axios.get(url)
  .then(function (response) {
    console.log(response);                                                                                                                                                    
  })
  .catch(function (error) {
    console.log(error);                                                                                                                                                       
  });                

unable to set private key file: './cert.pem' type PEM

I had the same issue, eventually I found a solution that works without splitting the file, by following Petter Ivarrson's answer

My problem was when converting .p12 certificate to .pem. I used:

openssl pkcs12 -in cert.p12 -out cert.pem

This converts and exports all certificates (CA + CLIENT) together with a private key into one file.

The problem was when I tried to verify if the hashes of certificate and key are matching by running:

// Get certificate HASH
openssl x509 -noout -modulus -in cert.pem | openssl md5

// Get private key HASH
openssl rsa -noout -modulus -in cert.pem | openssl md5

This displayed different hashes and that was the reason CURL failed. See here: https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/

I guess that was because all certificates are inside a file (CA + CLIENT) and CURL takes CA certificate instead of CLIENT one. Because CA is first in the list.

So the solution was to export only CLIENT certificate together with private key:

openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
``

Now when I re-run the verification:
```sh
openssl x509 -noout -modulus -in cert.pem | openssl md5
openssl rsa -noout -modulus -in cert.pem | openssl md5

HASHES MATCHED !!!

So I was able to make a curl request by running

curl -ivk --cert ./cert.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

without problems!!!

That being said... I think the best solution is to split the certificates into separate file and use them separately like Petter Ivarsson wrote:

curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

How to match hyphens with Regular Expression?

Is this what you are after?

MatchCollection matches = Regex.Matches(mystring, "-");

Loop through a date range with JavaScript

If startDate and endDate are indeed date objects you could convert them to number of milliseconds since midnight Jan 1, 1970, like this:

var startTime = startDate.getTime(), endTime = endDate.getTime();

Then you could loop from one to another incrementing loopTime by 86400000 (1000*60*60*24) - number of milliseconds in one day:

for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
    var loopDay=new Date(loopTime)
    //use loopDay as you wish
}

glm rotate usage in Opengl

You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).

All you need to do is (see here)

Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Note that to convert from degrees to radians, use glm::radians(degrees)

That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.

note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6

Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

How can you tell if a value is not numeric in Oracle?

You can use the following regular expression which will match integers (e.g., 123), floating-point numbers (12.3), and numbers with exponents (1.2e3):

^-?\d*\.?\d+([eE]-?\d+)?$

If you want to accept + signs as well as - signs (as Oracle does with TO_NUMBER()), you can change each occurrence of - above to [+-]. So you might rewrite your block of code above as follows:

IF (option_id = 0021) THEN 
    IF NOT REGEXP_LIKE(value, '^[+-]?\d*\.?\d+([eE][+-]?\d+)?$') OR TO_NUMBER(value) < 10000 OR TO_NUMBER(value) > 7200000 THEN
        ip_msg(6214,option_name);
        RETURN;
    END IF;
END IF;

I am not altogether certain that would handle all values so you may want to add an EXCEPTION block or write a custom to_number() function as @JustinCave suggests.

Where are environment variables stored in the Windows Registry?

I always had problems with that, and I made a getx.bat script:

:: getx %envvar% [\m]
:: Reads envvar from user environment variable and stores it in the getxvalue variable
:: with \m read system environment

@SETLOCAL EnableDelayedExpansion
@echo OFF

@set l_regpath="HKEY_CURRENT_USER\Environment"
@if "\m"=="%2" set l_regpath="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

::REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH /t REG_SZ /f /d "%PATH%"
::@REG QUERY %l_regpath% /v %1 /S

@FOR /F "tokens=*" %%A IN ('REG QUERY %l_regpath% /v %1 /S') DO (
@  set l_a=%%A
@    if NOT "!l_a!"=="!l_a:    =!" set l_line=!l_a!
)

:: Delimiter is four spaces. Change it to tab \t
@set l_line=!l_line!
@set l_line=%l_line:    =    %

@set getxvalue=

@FOR /F "tokens=3* delims=  " %%A IN ("%l_line%") DO (
@    set getxvalue=%%A
)
@set getxvalue=!getxvalue!
@echo %getxvalue% > getxfile.tmp.txt
@ENDLOCAL

:: We already used tab as a delimiter
@FOR /F "delims=    " %%A IN (getxfile.tmp.txt) DO (
    @set getxvalue=%%A
)
@del getxfile.tmp.txt

@echo ON

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

In my case clicking the checkbox for 'import project into workspace' fixed the error, even though the project was already in the workspace folder and didn't actually get moved their by eclipse.

Ternary operator (?:) in Bash

There's also a very similar but simpler syntax for ternary conditionals in bash:

a=$(( b == 5 ? 123 : 321  ))

How to save data file into .RData?

Alternatively, when you want to save individual R objects, I recommend using saveRDS.

You can save R objects using saveRDS, then load them into R with a new variable name using readRDS.

Example:

# Save the city object
saveRDS(city, "city.rds")

# ...

# Load the city object as city
city <- readRDS("city.rds")

# Or with a different name
city2 <- readRDS("city.rds")

But when you want to save many/all your objects in your workspace, use Manetheran's answer.

Calculate median in c#

Thanks Rafe, this takes into account the issues your replyers posted.

public static double GetMedian(double[] sourceNumbers) {
        //Framework 2.0 version of this method. there is an easier way in F4        
        if (sourceNumbers == null || sourceNumbers.Length == 0)
            throw new System.Exception("Median of empty array not defined.");

        //make sure the list is sorted, but use a new array
        double[] sortedPNumbers = (double[])sourceNumbers.Clone();
        Array.Sort(sortedPNumbers);

        //get the median
        int size = sortedPNumbers.Length;
        int mid = size / 2;
        double median = (size % 2 != 0) ? (double)sortedPNumbers[mid] : ((double)sortedPNumbers[mid] + (double)sortedPNumbers[mid - 1]) / 2;
        return median;
    }

Differences between Lodash and Underscore.js

In 2014 I still think my point holds:

IMHO, this discussion got blown out of proportion quite a bit. Quoting the aforementioned blog post:

Most JavaScript utility libraries, such as Underscore, Valentine, and wu, rely on the “native-first dual approach.” This approach prefers native implementations, falling back to vanilla JavaScript only if the native equivalent is not supported. But jsPerf revealed an interesting trend: the most efficient way to iterate over an array or array-like collection is to avoid the native implementations entirely, opting for simple loops instead.

As if "simple loops" and "vanilla Javascript" are more native than Array or Object method implementations. Jeez ...

It certainly would be nice to have a single source of truth, but there isn't. Even if you've been told otherwise, there is no Vanilla God, my dear. I'm sorry. The only assumption that really holds is that we are all writing JavaScript code that aims at performing well in all major browsers, knowing that all of them have different implementations of the same things. It's a bitch to cope with, to put it mildly. But that's the premise, whether you like it or not.

Maybe all of you are working on large scale projects that need twitterish performance so that you really see the difference between 850,000 (Underscore.js) vs. 2,500,000 (Lodash) iterations over a list per second right now!

I for one am not. I mean, I worked on projects where I had to address performance issues, but they were never solved or caused by neither Underscore.js nor Lodash. And unless I get hold of the real differences in implementation and performance (we're talking C++ right now) of, let’s say, a loop over an iterable (object or array, sparse or not!), I rather don't get bothered with any claims based on the results of a benchmark platform that is already opinionated.

It only needs one single update of, let’s say, Rhino to set its Array method implementations on fire in a fashion that not a single "medieval loop methods perform better and forever and whatnot" priest can argue his/her way around the simple fact that all of a sudden array methods in Firefox are much faster than his/her opinionated brainfuck. Man, you just can't cheat your runtime environment by cheating your runtime environment! Think about that when promoting ...

your utility belt

... next time.

So to keep it relevant:

  • Use Underscore.js if you're into convenience without sacrificing native'ish.
  • Use Lodash if you're into convenience and like its extended feature catalogue (deep copy, etc.) and if you're in desperate need of instant performance and most importantly don't mind settling for an alternative as soon as native API's outshine opinionated workarounds. Which is going to happen soon. Period.
  • There's even a third solution. DIY! Know your environments. Know about inconsistencies. Read their (John-David's and Jeremy's) code. Don't use this or that without being able to explain why a consistency/compatibility layer is really needed and enhances your workflow or improves the performance of your application. It is very likely that your requirements are satisfied with a simple polyfill that you're perfectly able to write yourself. Both libraries are just plain vanilla with a little bit of sugar. They both just fight over who's serving the sweetest pie. But believe me, in the end both are only cooking with water. There's no Vanilla God so there can't be no Vanilla pope, right?

Choose whatever approach fits your needs the most. As usual. I'd prefer fallbacks on actual implementations over opinionated runtime cheats anytime, but even that seems to be a matter of taste nowadays. Stick to quality resources like http://developer.mozilla.com and http://caniuse.com and you'll be just fine.

Remove characters from NSString?

You could use:

NSString *stringWithoutSpaces = [myString 
   stringByReplacingOccurrencesOfString:@" " withString:@""];

How to embed a Facebook page's feed into my website

If you are looking for a custom code instead of plugin, then this might help you. Facebook graph has under gone some changes since it has evolved. These steps are for the latest Graph API which I tried recently and worked well.

There are two main steps involved - 1. Getting Facebook Access Token, 2. Calling the Graph API passing the access token.

1. Getting the access token - Here is the step by step process to get the access token for your Facebook page. - Embed Facebook page feed on my website. As per this you need to create an app in Facebook developers page which would give you an App Id and an App Secret. Use these two and get the Access Token.

2. Calling the Graph API - This would be pretty simple once you get the access token. You just need to form a URL to Graph API with all the fields/properties you want to retrieve and make a GET request to this URL. Here is one example on how to do it in asp.net MVC. Embedding facebook feeds using asp.net mvc. This should be pretty similar in any other technology as it would be just a HTTP GET request.

Sample FQL Query: https://graph.facebook.com/FBPageName/posts?fields=full_picture,picture,link,message,created_time&limit=5&access_token=YOUR_ACCESS_TOKEN_HERE

The remote server returned an error: (407) Proxy Authentication Required

Just add this to config

<system.net>
    <defaultProxy useDefaultCredentials="true" >
    </defaultProxy>
</system.net>

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

I did this with a combination of:

  • Using multiple tables
  • Fixed-size cells
  • jQuery's scrollTop and scrollLeft functions

Here's a jsfiddle example to demonstrate.

Haven't tested on all browsers but I imagine it's not great on older IE versions.

_x000D_
_x000D_
$("#clscroll-content").scroll(function() {_x000D_
    $("#clscroll-row-headers").scrollTop($("#clscroll-content").scrollTop());_x000D_
    $("#clscroll-column-headers").scrollLeft($("#clscroll-content").scrollLeft());_x000D_
});_x000D_
_x000D_
$("#clscroll-column-headers").scroll(function() {_x000D_
    $("#clscroll-content").scrollLeft($("#clscroll-column-headers").scrollLeft());_x000D_
});_x000D_
_x000D_
$("#clscroll-row-headers").scroll(function() {_x000D_
    $("#clscroll-content").scrollTop($("#clscroll-row-headers").scrollTop());_x000D_
});
_x000D_
.clscroll table {_x000D_
    table-layout: fixed;_x000D_
}_x000D_
_x000D_
.clscroll td, .clscroll th { _x000D_
    overflow: hidden;_x000D_
}_x000D_
_x000D_
.corner-header {_x000D_
    float: left;_x000D_
}_x000D_
_x000D_
.column-headers {_x000D_
    float: left;_x000D_
    overflow: scroll;_x000D_
}_x000D_
_x000D_
.row-headers {_x000D_
    clear: both;_x000D_
    float: left;    _x000D_
    overflow: scroll;_x000D_
}_x000D_
_x000D_
.table-content {_x000D_
    table-layout: fixed;_x000D_
    float: left;_x000D_
    overflow: scroll;_x000D_
}_x000D_
_x000D_
.clscroll td, .clscroll th { _x000D_
    width: 200px;_x000D_
    border: 1px solid black;_x000D_
}_x000D_
_x000D_
.row-headers, .table-content {_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
.column-headers, .table-content, .table-content table, .column-headers table {_x000D_
    width: 400px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="clscroll corner-header">_x000D_
  <table>_x000D_
      <tr>_x000D_
          <th>&nbsp;</th>_x000D_
      </tr>_x000D_
  </table>_x000D_
</div>_x000D_
<div class="clscroll column-headers" id="clscroll-column-headers">_x000D_
  <table>_x000D_
      <tr>_x000D_
          <th>Bus</th>_x000D_
          <th>Plane</th>_x000D_
          <th>Boat</th>_x000D_
          <th>Bicycle</th>_x000D_
      </tr>_x000D_
  </table>_x000D_
</div>_x000D_
<div class="clscroll row-headers" id="clscroll-row-headers">_x000D_
  <table>_x000D_
      <tr>_x000D_
          <th>Red</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <th>Green</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <th>Blue</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <th>Orange</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <th>Purple</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <th>Yellow</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <th>Pink</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <th>Brown</th>_x000D_
      </tr>_x000D_
  </table>_x000D_
</div>_x000D_
<div class="clscroll table-content" id="clscroll-content">_x000D_
  <table>_x000D_
      <tr>_x000D_
          <td>Red Bus</td>_x000D_
          <td>Red Plane</td>_x000D_
          <td>Red Boat</td>_x000D_
          <td>Red Bicycle</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <td>Green Bus</td>_x000D_
          <td>Green Plane</td>_x000D_
          <td>Green Boat</td>_x000D_
          <td>Green Bicycle</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <td>Blue Bus</td>_x000D_
          <td>Blue Plane</td>_x000D_
          <td>Blue Boat</td>_x000D_
          <td>Blue Bicycle</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <td>Orange Bus</td>_x000D_
          <td>Orange Plane</td>_x000D_
          <td>Orange Boat</td>_x000D_
          <td>Orange Bicycle</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <td>Purple Bus</td>_x000D_
          <td>Purple Plane</td>_x000D_
          <td>Purple Boat</td>_x000D_
          <td>Purple Bicycle</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <td>Yellow Bus</td>_x000D_
          <td>Yellow Plane</td>_x000D_
          <td>Yellow Boat</td>_x000D_
          <td>Yellow Bicycle</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <td>Pink Bus</td>_x000D_
          <td>Pink Plane</td>_x000D_
          <td>Pink Boat</td>_x000D_
          <td>Pink Bicycle</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
          <td>Brown Bus</td>_x000D_
          <td>Brown Plane</td>_x000D_
          <td>Brown Boat</td>_x000D_
          <td>Brown Bicycle</td>_x000D_
      </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Access VBA | How to replace parts of a string with another string

Since the string "North" might be the beginning of a street name, e.g. "Northern Boulevard", street directions are always between the street number and the street name, and separated from street number and street name.

Public Function strReplace(varValue As Variant) as Variant

Select Case varValue

    Case "Avenue"
        strReplace = "Ave"

    Case " North "
        strReplace = " N "

    Case Else
        strReplace = varValue

End Select

End Function

What's the most concise way to read query parameters in AngularJS?

It can be done by two ways:

  1. Using $routeParams

Best and recommended solution is to use $routeParams into your controller. It Requires the ngRoute module to be installed.

   function MyController($scope, $routeParams) {
      // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
      // Route: /Chapter/:chapterId/Section/:sectionId
      // $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
      var search = $routeParams.search;
  }
  1. Using $location.search().

There is a caveat here. It will work only with HTML5 mode. By default, it does not work for the URL which does not have hash(#) in it http://localhost/test?param1=abc&param2=def

You can make it work by adding #/ in the URL. http://localhost/test#/?param1=abc&param2=def

$location.search() to return an object like:

{
  param1: 'abc',
  param2: 'def'
}

How to Export Private / Secret ASC Key to Decrypt GPG Files

I think you had not yet import the private key as the message error said, To import public/private key from gnupg:

gpg --import mypub_key
gpg --allow-secret-key-import --import myprv_key

How to remove docker completely from ubuntu 14.04

Probably your problem is that for Docker that has been installed from default Ubuntu repository, the package name is docker.io

Or package name may be something like docker-ce. Try running

dpkg -l | grep -i docker

to identify what installed package you have

So you need to change package name in commands from https://stackoverflow.com/a/31313851/2340159 to match package name. For example, for docker.io it would be:

sudo apt-get purge -y docker.io
sudo apt-get autoremove -y --purge docker.io
sudo apt-get autoclean

It adds:

The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command:

sudo rm -rf /var/lib/docker

Remove docker from apparmor.d:

sudo rm /etc/apparmor.d/docker

Remove docker group:

sudo groupdel docker

Vue.js redirection to another page

You can also use the v-bind directly to the template like ...

<a :href="'/path-to-route/' + IdVariable">

the : is the abbreviation of v-bind.

How do I redirect in expressjs while passing some context?

There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You'll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.

app.get('/category', function(req, res) {
  var string = encodeURIComponent('something that would break');
  res.redirect('/?valid=' + string);
});

You can snag that in your other route by getting the parameters sent by using req.query.

app.get('/', function(req, res) {
  var passedVariable = req.query.valid;
  // Do something with variable
});

For more dynamic way you can use the url core module to generate the query string for you:

const url = require('url');    
app.get('/category', function(req, res) {
    res.redirect(url.format({
       pathname:"/",
       query: {
          "a": 1,
          "b": 2,
          "valid":"your string here"
        }
     }));
 });

So if you want to redirect all req query string variables you can simply do

res.redirect(url.format({
       pathname:"/",
       query:req.query,
     });
 });

And if you are using Node >= 7.x you can also use the querystring core module

const querystring = require('querystring');    
app.get('/category', function(req, res) {
      const query = querystring.stringify({
          "a": 1,
          "b": 2,
          "valid":"your string here"
      });
      res.redirect('/?' + query);
 });

Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:

app.get('/category', function(req, res) {
  req.session.valid = true;
  res.redirect('/');
});

And later on after the redirect...

app.get('/', function(req, res) {
  var passedVariable = req.session.valid;
  req.session.valid = null; // resets session variable
  // Do something
});

There is also the option of using an old feature of Express, req.flash. Doing so in newer versions of Express will require you to use another library. Essentially it allows you to set up variables that will show up and reset the next time you go to a page. It's handy for showing errors to users, but again it's been removed by default. EDIT: Found a library that adds this functionality.

Hopefully that will give you a general idea how to pass information around in an Express application.

implements Closeable or implements AutoCloseable

The try-with-resources Statement.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }

}

Please refer to the docs.

Dynamic WHERE clause in LINQ

This project on CodePlex have what you want.

System.Linq.Dynamic - http://dynamiclinq.codeplex.com/

Project Description

Extends System.Linq.Dynamic to support Execution of Lambda expressions defined in a string against Entity Framework or any provider that supports IQueryable.

As it is an extension of the source code you can find on Scott Guthrie's Blog it will allow you to do things like this:

enter image description here

And things like this:

enter image description here

iterating over each character of a String in ruby 1.8.6 (each_char)

"ABCDEFG".chars.each do |char|
  puts char
end

also

"ABCDEFG".each_char {|char| p char}

Ruby version >2.5.1

What is the usefulness of PUT and DELETE HTTP request methods?

Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times

According to your requirement :

1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD

Laravel - check if Ajax request

To check an ajax request you can use if (Request::ajax())

Note: If you are using laravel 5, then in the controller replace

use Illuminate\Http\Request;

with

use Request; 

I hope it'll work.

Reading Excel file using node.js

Install 'spread_sheet' node module,it will both add and fetch row from local spreadsheet

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

Adding the following attribute within the opening < widget > tag worked for me. Simple and live reloads correctly on a Android 9 emulator. xmlns:android="http://schemas.android.com/apk/res/android"

<widget id="com.my.awesomeapp" version="1.0.0" 
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:cdv="http://cordova.apache.org/ns/1.0">

Arrays vs Vectors: Introductory Similarities and Differences

arrays:

  • are a builtin language construct;
  • come almost unmodified from C89;
  • provide just a contiguous, indexable sequence of elements; no bells and whistles;
  • are of fixed size; you can't resize an array in C++ (unless it's an array of POD and it's allocated with malloc);
  • their size must be a compile-time constant unless they are allocated dynamically;
  • they take their storage space depending from the scope where you declare them;
  • if dynamically allocated, you must explicitly deallocate them;
  • if they are dynamically allocated, you just get a pointer, and you can't determine their size; otherwise, you can use sizeof (hence the common idiom sizeof(arr)/sizeof(*arr), that however fails silently when used inadvertently on a pointer);
  • automatically decay to a pointers in most situations; in particular, this happens when passing them to a function, which usually requires passing a separate parameter for their size;
  • can't be returned from a function;
  • can't be copied/assigned directly;
  • dynamical arrays of objects require a default constructor, since all their elements must be constructed first;

std::vector:

  • is a template class;
  • is a C++ only construct;
  • is implemented as a dynamic array;
  • grows and shrinks dynamically;
  • automatically manage their memory, which is freed on destruction;
  • can be passed to/returned from functions (by value);
  • can be copied/assigned (this performs a deep copy of all the stored elements);
  • doesn't decay to pointers, but you can explicitly get a pointer to their data (&vec[0] is guaranteed to work as expected);
  • always brings along with the internal dynamic array its size (how many elements are currently stored) and capacity (how many elements can be stored in the currently allocated block);
  • the internal dynamic array is not allocated inside the object itself (which just contains a few "bookkeeping" fields), but is allocated dynamically by the allocator specified in the relevant template parameter; the default one gets the memory from the freestore (the so-called heap), independently from how where the actual object is allocated;
  • for this reason, they may be less efficient than "regular" arrays for small, short-lived, local arrays;
  • when reallocating, the objects are copied (moved, in C++11);
  • does not require a default constructor for the objects being stored;
  • is better integrated with the rest of the so-called STL (it provides the begin()/end() methods, the usual STL typedefs, ...)

Also consider the "modern alternative" to arrays - std::array; I already described in another answer the difference between std::vector and std::array, you may want to have a look at it.

How to change text transparency in HTML/CSS?

What about the css opacity attribute? 0 to 1 values.

But then you probably need to use a more explicit dom element than "font". For instance:

<html><body><span style=\"opacity: 0.5;\"><font color=\"black\" face=\"arial\" size=\"4\">THIS IS MY TEXT</font></span></body></html>

As an additional information I would of course suggest you use CSS declarations outside of your html elements, but as well try to use the font css style instead of the font html tag.

For cross browser css3 styles generator, have a look at http://css3please.com/

While loop to test if a file exists in bash

If you are on linux and have inotify-tools installed, you can do this:

file=/tmp/list.txt
while [ ! -f "$file" ]
do
    inotifywait -qqt 2 -e create -e moved_to "$(dirname $file)"
done

This reduces the delay introduced by sleep while still polling every "x" seconds. You can add more events if you anticipate that they are needed.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

Reading a file line by line in Go

Example from this gist

func readLine(path string) {
  inFile, err := os.Open(path)
  if err != nil {
     fmt.Println(err.Error() + `: ` + path)
     return
  }
  defer inFile.Close()

  scanner := bufio.NewScanner(inFile)
  for scanner.Scan() {
    fmt.Println(scanner.Text()) // the line
  }
}

but this gives an error when there is a line that larger than Scanner's buffer.

When that happened, what I do is use reader := bufio.NewReader(inFile) create and concat my own buffer either using ch, err := reader.ReadByte() or len, err := reader.Read(myBuffer)

Another way that I use (replace os.Stdin with file like above), this one concats when lines are long (isPrefix) and ignores empty lines:


func readLines() []string {
  r := bufio.NewReader(os.Stdin)
  bytes := []byte{}
  lines := []string{}
  for {
    line, isPrefix, err := r.ReadLine()
    if err != nil {
      break
    }
    bytes = append(bytes, line...)
    if !isPrefix {
      str := strings.TrimSpace(string(bytes))
      if len(str) > 0 {
        lines = append(lines, str)
        bytes = []byte{}
      }
    }
  }
  if len(bytes) > 0 {
    lines = append(lines, string(bytes))
  }
  return lines
}

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

Code snippet or shortcut to create a constructor in Visual Studio

Type "ctor" + TAB + TAB (hit the Tab key twice). This will create the default constructor for the class you are in:

public MyClass()
{

}

It seems that in some cases you will have to press TAB twice.

jQuery: How to get to a particular child of a parent?

$(this).parent()

Tree traversal is fun

$(this).parent().siblings(".something1");

$(this).parent().prev(); // if you always want the parent's previous sibling

$(this).parents(".box").children(".something1");

And much more ways, you might find these docs helpful.

How to set background color of HTML element using css properties in JavaScript

Add this script element to your body element:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>

Convert string to ASCII value python

Here is a pretty concise way to perform the concatenation:

>>> s = "hello world"
>>> ''.join(str(ord(c)) for c in s)
'10410110810811132119111114108100'

And a sort of fun alternative:

>>> '%d'*len(s) % tuple(map(ord, s))
'10410110810811132119111114108100'

How to listen state changes in react.js?

In 2020 you can listen state changes with useEffect hook like this

export function MyComponent(props) {
    const [myState, setMystate] = useState('initialState')

    useEffect(() => {
        console.log(myState, '- Has changed')
    },[myState]) // <-- here put the parameter to listen
}

git stash apply version

Just making simple to understand for beginners.

Check your git stash list with below command :

git stash list

And then apply with below command:

git stash apply stash@{n}

For example: I am applying my latest stash(latest is always index {0} on top of the stash list).

 git stash apply stash@{0}

using setTimeout on promise chain

In node.js you can also do the following:

const { promisify } = require('util')
const delay = promisify(setTimeout)

delay(1000).then(() => console.log('hello'))

Notification Icon with the new Firebase Cloud Messaging system

Thought I would add an answer to this one, since my problem was simple but hard to notice. In particular I had copy/pasted an existing meta-data element when creating my com.google.firebase.messaging.default_notification_icon, which used an android:value tag to specify its value. This will not work for the notification icon, and once I changed it to android:resource everything worked as expected.

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

How to delete empty folders using windows command prompt?

Adding to corroded answer from the same referenced page is a PowerShell version http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx#8408736

Get-ChildItem -Recurse . | where { $_.PSISContainer -and @( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item

or, more tersely,

gci -R . | where { $_.PSISContainer -and @( $_ | gci ).Count -eq 0 } | ri

credit goes to the posting author

How to modify list entries during for loop?

In short, to do modification on the list while iterating the same list.

list[:] = ["Modify the list" for each_element in list "Condition Check"]

example:

list[:] = [list.remove(each_element) for each_element in list if each_element in ["data1", "data2"]]

Creating a new empty branch for a new project

If your git version does not have the --orphan option, this method should be used:

git symbolic-ref HEAD refs/heads/<newbranch> 
rm .git/index 
git clean -fdx 

After doing some work:

git add -A
git commit -m <message>
git push origin <newbranch>

Correct way to read a text file into a buffer in C?

char source[1000000];

FILE *fp = fopen("TheFile.txt", "r");
if(fp != NULL)
{
    while((symbol = getc(fp)) != EOF)
    {
        strcat(source, &symbol);
    }
    fclose(fp);
}

There are quite a few things wrong with this code:

  1. It is very slow (you are extracting the buffer one character at a time).
  2. If the filesize is over sizeof(source), this is prone to buffer overflows.
  3. Really, when you look at it more closely, this code should not work at all. As stated in the man pages:

The strcat() function appends a copy of the null-terminated string s2 to the end of the null-terminated string s1, then add a terminating `\0'.

You are appending a character (not a NUL-terminated string!) to a string that may or may not be NUL-terminated. The only time I can imagine this working according to the man-page description is if every character in the file is NUL-terminated, in which case this would be rather pointless. So yes, this is most definitely a terrible abuse of strcat().

The following are two alternatives to consider using instead.

If you know the maximum buffer size ahead of time:

#include <stdio.h>
#define MAXBUFLEN 1000000

char source[MAXBUFLEN + 1];
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
    size_t newLen = fread(source, sizeof(char), MAXBUFLEN, fp);
    if ( ferror( fp ) != 0 ) {
        fputs("Error reading file", stderr);
    } else {
        source[newLen++] = '\0'; /* Just to be safe. */
    }

    fclose(fp);
}

Or, if you do not:

#include <stdio.h>
#include <stdlib.h>

char *source = NULL;
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
    /* Go to the end of the file. */
    if (fseek(fp, 0L, SEEK_END) == 0) {
        /* Get the size of the file. */
        long bufsize = ftell(fp);
        if (bufsize == -1) { /* Error */ }

        /* Allocate our buffer to that size. */
        source = malloc(sizeof(char) * (bufsize + 1));

        /* Go back to the start of the file. */
        if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }

        /* Read the entire file into memory. */
        size_t newLen = fread(source, sizeof(char), bufsize, fp);
        if ( ferror( fp ) != 0 ) {
            fputs("Error reading file", stderr);
        } else {
            source[newLen++] = '\0'; /* Just to be safe. */
        }
    }
    fclose(fp);
}

free(source); /* Don't forget to call free() later! */

How do I prevent 'git diff' from using a pager?

git -P diff

Or --no-pager.

BTW: To preserve colour with cat

git diff --color=always | cat

How to calculate the sum of the datatable column in asp.net?

To calculate the sum of a column in a DataTable use the DataTable.Compute method.

Example of usage from the linked MSDN article:

DataTable table = dataSet.Tables["YourTableName"];

// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount)", string.Empty);

Display the result in your Total Amount Label like so:

lblTotalAmount.Text = sumObject.ToString();

What are the specific differences between .msi and setup.exe file?

.msi files are windows installer files without the windows installer runtime, setup.exe can be any executable programm (probably one that installs stuff on your computer)

How to loop through all but the last item of a list?

the easiest way to compare the sequence item with the following:

for i, j in zip(a, a[1:]):
     # compare i (the current) to j (the following)

How do I subtract minutes from a date in javascript?

Extend Date class with this function

// Add (or substract if value is negative) the value, expresed in timeUnit
// to the date and return the new date.
Date.dateAdd = function(currentDate, value, timeUnit) {

    timeUnit = timeUnit.toLowerCase();
    var multiplyBy = { w:604800000,
                     d:86400000,
                     h:3600000,
                     m:60000,
                     s:1000 };
    var updatedDate = new Date(currentDate.getTime() + multiplyBy[timeUnit] * value);

    return updatedDate;
};

So you can add or substract a number of minutes, seconds, hours, days... to any date.

add_10_minutes_to_current_date = Date.dateAdd( Date(), 10, "m");
subs_1_hour_to_a_date = Date.dateAdd( date_value, -1, "h");

Getting All Variables In Scope

The Simplest Way to Get Access to Vars in a Particular Scope

  1. Open Developer Tools > Resources (in Chrome)
  2. Open file with a function that has access to that scope (tip cmd/ctrl+p to find file)
  3. Set breakpoint inside that function and run your code
  4. When it stops at your breakpoint, you can access the scope var through console (or scope var window)

Note: You want to do this against un-minified js.

The Simplest Way to Show All Non-Private Vars

  1. Open Console (in Chrome)
  2. Type: this.window
  3. Hit Enter

Now you will see an object tree you can expand with all declared objects.

How to trigger checkbox click event even if it's checked through Javascript code?

You can use .change() function too

E.g.:

$('form input[type=checkbox]').change(function() { console.log('hello') });

Size-limited queue that holds last N elements in Java

The only thing I know that has limited space is the BlockingQueue interface (which is e.g. implemented by the ArrayBlockingQueue class) - but they do not remove the first element if filled, but instead block the put operation until space is free (removed by other thread).

To my knowledge your trivial implementation is the easiest way to get such an behaviour.

How would I extract a single file (or changes to a file) from a git stash?

Edit: See cambunctious's answer, which is basically what I now prefer because it only uses the changes in the stash, rather than comparing them to your current state. This makes the operation additive, with much less chance of undoing work done since the stash was created.

To do it interactively, you would first do

git diff stash^! -- path/to/relevant/file/in/stash.ext perhaps/another/file.ext > my.patch

...then open the patch file in a text editor, alter as required, then do

git apply < my.patch

cambunctious's answer bypasses the interactivity by piping one command directly to the other, which is fine if you know you want all changes from the stash. You can edit the stash^! to be any commit range that has the cumulative changes you want (but check over the output of the diff first).

If applying the patch/diff fails, you can change the last command to git apply --reject which makes all the changes it can, and leaves .rej files where there are conflicts it can;r resolve. The .rej files can then be applied using wiggle, like so:

wiggle --replace path/to/relevant/file/in/stash.ext path/to/relevant/file/in/stash.ext.rej

This will either resolve the conflict, or give you conflict markers that you'd get from a merge.


Previous solution: There is an easy way to get changes from any branch, including stashes:

$ git checkout --patch stash@{0} path/to/file

You may omit the file spec if you want to patch in many parts. Or omit patch (but not the path) to get all changes to a single file. Replace 0 with the stash number from git stash list, if you have more than one. Note that this is like diff, and offers to apply all differences between the branches. To get changes from only a single commit/stash, have a look at git cherry-pick --no-commit.

Possible to perform cross-database queries with PostgreSQL?

see https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/ [published 2017]

These days you also have the option to use https://prestodb.io/

You can run SQL on that PrestoDB node and it will distribute the SQL query as required. It can connect to the same node twice for different databases, or it might be connecting to different nodes on different hosts.

It does not support:

DELETE
ALTER TABLE
CREATE TABLE (CREATE TABLE AS is supported)
GRANT
REVOKE
SHOW GRANTS
SHOW ROLES
SHOW ROLE GRANTS

So you should only use it for SELECT and JOIN needs. Connect directly to each database for the above needs. (It looks like you can also INSERT or UPDATE which is nice)

Client applications connect to PrestoDB primarily using JDBC, but other types of connection are possible including a Tableu compatible web API

This is an open source tool governed by the Linux Foundation and Presto Foundation.

The founding members of the Presto Foundation are: Facebook, Uber, Twitter, and Alibaba.

The current members are: Facebook, Uber, Twitter, Alibaba, Alluxio, Ahana, Upsolver, and Intel.

How to get the position of a character in Python?

Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last '.', in this case use rfind:

path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15

in my case, I use the following, which works whatever the complete file name is:

filename_without_extension = complete_name[:complete_name.rfind('.')]

Embedding Windows Media Player for all browsers

You could use conditional comments to get IE and Firefox to do different things

<![if !IE]>
<p> Firefox only code</p>
<![endif]>

<!--[if IE]>
<p>Internet Explorer only code</p>
<![endif]-->

The browsers themselves will ignore code that isn't meant for them to read.

How to bind Events on Ajax loaded Content?

if your question is "how to bind events on ajax loaded content" you can do like this :

$("img.lazy").lazyload({
    effect : "fadeIn",
    event: "scrollstop",
    skip_invisible : true
}).removeClass('lazy');

// lazy load to DOMNodeInserted event
$(document).bind('DOMNodeInserted', function(e) {
    $("img.lazy").lazyload({
        effect : "fadeIn",
        event: "scrollstop",
        skip_invisible : true
    }).removeClass('lazy');
});

so you don't need to place your configuration to every you ajax code

Setting a property with an EventTrigger

Stopping the Storyboard can be done in the code behind, or the xaml, depending on where the need comes from.

If the EventTrigger is moved outside of the button, then we can go ahead and target it with another EventTrigger that will tell the storyboard to stop. When the storyboard is stopped in this manner it will not revert to the previous value.

Here I've moved the Button.Click EventTrigger to a surrounding StackPanel and added a new EventTrigger on the the CheckBox.Click to stop the Button's storyboard when the CheckBox is clicked. This lets us check and uncheck the CheckBox when it is clicked on and gives us the desired unchecking behavior from the button as well.

    <StackPanel x:Name="myStackPanel">

        <CheckBox x:Name="myCheckBox"
                  Content="My CheckBox" />

        <Button Content="Click to Uncheck"
                x:Name="myUncheckButton" />

        <Button Content="Click to check the box in code."
                Click="OnClick" />

        <StackPanel.Triggers>

            <EventTrigger RoutedEvent="Button.Click"
                          SourceName="myUncheckButton">
                <EventTrigger.Actions>
                    <BeginStoryboard x:Name="myBeginStoryboard">
                        <Storyboard x:Name="myStoryboard">
                            <BooleanAnimationUsingKeyFrames Storyboard.TargetName="myCheckBox"
                                                            Storyboard.TargetProperty="IsChecked">
                                <DiscreteBooleanKeyFrame KeyTime="00:00:00"
                                                         Value="False" />
                            </BooleanAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>

            <EventTrigger RoutedEvent="CheckBox.Click"
                          SourceName="myCheckBox">
                <EventTrigger.Actions>
                    <StopStoryboard BeginStoryboardName="myBeginStoryboard" />
                </EventTrigger.Actions>
            </EventTrigger>

        </StackPanel.Triggers>
    </StackPanel>

To stop the storyboard in the code behind, we will have to do something slightly different. The third button provides the method where we will stop the storyboard and set the IsChecked property back to true through code.

We can't call myStoryboard.Stop() because we did not begin the Storyboard through the code setting the isControllable parameter. Instead, we can remove the Storyboard. To do this we need the FrameworkElement that the storyboard exists on, in this case our StackPanel. Once the storyboard is removed, we can once again set the IsChecked property with it persisting to the UI.

    private void OnClick(object sender, RoutedEventArgs e)
    {
        myStoryboard.Remove(myStackPanel);
        myCheckBox.IsChecked = true;
    }

How to dismiss a Twitter Bootstrap popover by clicking outside?

This has been asked before here. The same answer I gave then still applies:

I had a similar need, and found this great little extension of the Twitter Bootstrap Popover by Lee Carmichael, called BootstrapX - clickover. He also has some usage examples here. Basically it will change the popover into an interactive component which will close when you click elsewhere on the page, or on a close button within the popover. This will also allow multiple popovers open at once and a bunch of other nice features.

get dictionary key by value

types.Values.ToList().IndexOf("one");

Values.ToList() converts your dictionary values into a List of objects. IndexOf("one") searches your new List looking for "one" and returns the Index which would match the index of the Key/Value pair in the dictionary.

This method does not care about the dictionary keys, it simply returns the index of the value that you are looking for.

Keep in mind there may be more than one "one" value in your dictionary. And that is the reason there is no "get key" method.

Running npm command within Visual Studio Code

Same thing was happening to me after I installed Node.js. Node and npm was recognized in PowerShell and Command Prompt but not in VS Code. I fixed it by adding the Node.js install path to the system's environment PATH variable. The node.js install path on my system was:

C:\Program Files\nodejs

Where I find the node.exe that is needed. The user's PATH variable already had the Node.js install path but for some reason VS Code needs the Node.js install path in the system's PATH variables.

Windows 10 instructions:

  1. Windows key and type "environment"
  2. Select "Edit the system environment variables"
  3. Click button labelled "Environment Variables..."
  4. In "System variables" section edit the "Path" variable
  5. Add Node.js install path to the list (C:\Program Files\nodejs)

The other answers were great but this is another way to fix it that worked for me without needing to install stuff, run as admin, or change the default settings.

Darken background image on hover

Try following code:

.image {
    background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook.png');
    width: 58px;
    height: 58px;
    opacity:0.2;
}

.image:hover{
    opacity:1;
}

configure: error: C compiler cannot create executables

When you see this error message, you might not have accepted the Xcode license agreement yet after an upgrade.

First of all, make sure you have upgraded your commandline tools:

$ xcode-select --install

Now Apple wants you to agree to their license before you can use these tools:

$ gcc
Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.

$ sudo gcc
You have not agreed to the Xcode license agreements. You must agree to both license agreements below in order to use Xcode.
[...]

After you have accepted it, the commandline tools will work as expected.

How do I disable a Pylint warning?

There are several ways to disable warnings & errors from Pylint. Which one to use has to do with how globally or locally you want to apply the disablement -- an important design decision.

Multiple Approaches

  1. In one or more pylintrc files.

This involves more than the ~/.pylintrc file (in your $HOME directory) as described by Chris Morgan. Pylint will search for rc files, with a precedence that values "closer" files more highly:

  • A pylintrc file in the current working directory; or

  • If the current working directory is in a Python module (i.e. it contains an __init__.py file), searching up the hierarchy of Python modules until a pylintrc file is found; or

  • The file named by the environment variable PYLINTRC; or

  • If you have a home directory that isn’t /root:

    • ~/.pylintrc; or

    • ~/.config/pylintrc; or

    • /etc/pylintrc

Note that most of these files are named pylintrc -- only the file in ~ has a leading dot.

To your pylintrc file, add lines to disable specific pylint messages. For example:

[MESSAGES CONTROL]
disable=locally-disabled
  1. Further disables from the pylint command line, as described by Aboo and Cairnarvon. This looks like pylint --disable=bad-builtin. Repeat --disable to suppress additional items.

  2. Further disables from individual Python code lines, as described by Imolit. These look like some statement # pylint: disable=broad-except (extra comment on the end of the original source line) and apply only to the current line. My approach is to always put these on the end of other lines of code so they won't be confused with the block style, see below.

  3. Further disables defined for larger blocks of Python code, up to complete source files.

    • These look like # pragma pylint: disable=bad-whitespace (note the pragma key word).

    • These apply to every line after the pragma. Putting a block of these at the top of a file makes the suppressions apply to the whole file. Putting the same block lower in the file makes them apply only to lines following the block. My approach is to always put these on a line of their own so they won't be confused with the single-line style, see above.

    • When a suppression should only apply within a span of code, use # pragma pylint: enable=bad-whitespace (now using enable not disable) to stop suppressing.

Note that disabling for a single line uses the # pylint syntax while disabling for this line onward uses the # pragma pylint syntax. These are easy to confuse especially when copying & pasting.

Putting It All Together

I usually use a mix of these approaches.

  • I use ~/.pylintrc for absolutely global standards -- very few of these.

  • I use project-level pylintrc at different levels within Python modules when there are project-specific standards. Especially when you're taking in code from another person or team, you may find they use conventions that you don't prefer, but you don't want to rework the code. Keeping the settings at this level helps not spread those practices to other projects.

  • I use the block style pragmas at the top of single source files. I like to turn the pragmas off (stop suppressing messages) in the heat of development even for Pylint standards I don't agree with (like "too few public methods" -- I always get that warning on custom Exception classes) -- but it's helpful to see more / maybe all Pylint messages while you're developing. That way you can find the cases you want to address with single-line pragmas (see below), or just add comments for the next developer to explain why that warning is OK in this case.

  • I leave some of the block-style pragmas enabled even when the code is ready to check in. I try to use few of those, but when it makes sense for the module, it's OK to do as documentation. However I try to leave as few on as possible, preferably none.

  • I use the single-line-comment style to address especially potent errors. For example, if there's a place where it actually makes sense to do except Exception as exc, I put the # pylint: disable=broad-except on that line instead of a more global approach because this is a strange exception and needs to be called out, basically as a form of documentation.


Like everything else in Python, you can act at different levels of indirection. My advice is to think about what belongs at what level so you don't end up with a too-lenient approach to Pylint.

jQuery 1.9 .live() is not a function

Forward port of .live() for jQuery >= 1.9 Avoids refactoring JS dependencies on .live() Uses optimized DOM selector context

/** 
 * Forward port jQuery.live()
 * Wrapper for newer jQuery.on()
 * Uses optimized selector context 
 * Only add if live() not already existing.
*/
if (typeof jQuery.fn.live == 'undefined' || !(jQuery.isFunction(jQuery.fn.live))) {
  jQuery.fn.extend({
      live: function (event, callback) {
         if (this.selector) {
              jQuery(document).on(event, this.selector, callback);
          }
      }
  });
}

Linking a qtDesigner .ui file to python/pyqt?

The cleaner way in my opinion is to first export to .py as aforementioned:

pyuic4 foo.ui > foo.py

And then use it inside your code (e.g main.py), like:

from foo import Ui_MyWindow


class MyWindow(QtGui.QDialog):
    def __init__(self):
        super(MyWindow, self).__init__()

        self.ui = Ui_MyWindow()
        self.ui.setupUi(self)

        # go on setting up your handlers like:
        # self.ui.okButton.clicked.connect(function_name)
        # etc...

def main():
    app = QtGui.QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

This way gives the ability to other people who don't use qt-designer to read the code, and also keeps your functionality code outside foo.py that could be overwritten by designer. You just reference ui through MyWindow class as seen above.

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

OneTouch deployment will do all the detection and installation of pre-requisites. It's probably best to go with a pre-made solution than trying to roll your own. Trying to roll your own may lead to problems because whatever thing you key on may change with a hotfix or service pack. Likely Microsoft has some heuristic for determining what version is running.

Java 8 forEach with index

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
  .forEach(idx ->
    query.bind(
      idx,
      params.get(idx)
    )
  )
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

How to pass parameters to a Script tag?

If you are using jquery you might want to consider their data method.

I have used something similar to what you are trying in your response but like this:

<script src="http://path.to/widget.js" param_a = "2" param_b = "5" param_c = "4">
</script>

You could also create a function that lets you grab the GET params directly (this is what I frequently use):

function $_GET(q,s) {
    s = s || window.location.search;
    var re = new RegExp('&'+q+'=([^&]*)','i');
    return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}

// Grab the GET param
var param_a = $_GET('param_a');

List vs tuple, when to use each?

Tuples are fixed size in nature whereas lists are dynamic.
In other words, a tuple is immutable whereas a list is mutable.

  1. You can't add elements to a tuple. Tuples have no append or extend method.
  2. You can't remove elements from a tuple. Tuples have no remove or pop method.
  3. You can find elements in a tuple, since this doesn’t change the tuple.
  4. You can also use the in operator to check if an element exists in the tuple.

  • Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.

  • It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.

  • Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable.

Source: Dive into Python 3

outline on only one border

You can use box-shadow to create an outline on one side. Like outline, box-shadow does not change the size of the box model.

This puts a line on top:

box-shadow: 0 -1px 0 #000;

I made a jsFiddle where you can check it out in action.


INSET

For an inset border, use the inset keyword. This puts an inset line on top:

box-shadow: 0 1px 0 #000 inset;

Multiple lines can be added using comma-separated statements. This puts an inset line on the top and the left:

box-shadow: 0 1px 0 #000 inset,
            1px 0 0 #000 inset;

For more details on how box-shadow works, check out the MDN page.

Two decimal places using printf( )

Use: "%.2f" or variations on that.

See the POSIX spec for an authoritative specification of the printf() format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.

Since you're coding in C++, you should probably be avoiding printf() and its relatives.

How to JUnit test that two List<E> contain the same elements in the same order?

Why not simply use List#equals?

assertEquals(argumentComponents, imapPathComponents);

Contract of List#equals:

two lists are defined to be equal if they contain the same elements in the same order.

how to reset <input type = "file">

The reseting input file is on very single

$('input[type=file]').val(null);

If you bind reset the file in change other field of the form, or load form with ajax.

This example is applicable

selector for example is $('input[type=text]') or any element of the form

event click, change, or any event

$('body').delegate('event', 'selector', function(){
     $('input[type=file]').val(null) ;
});

Update rows in one table with data from another table based on one column in each being equal

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      );

Or this (if t2.column1 <=> t1.column1 are many to one and anyone of them is good):

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
    and
      rownum = 1    
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      ); 

XML serialization in Java?

"Simple XML Serialization" Project

You may want to look at the Simple XML Serialization project. It is the closest thing I've found to the System.Xml.Serialization in .Net.

phpMyAdmin - config.inc.php configuration?

I had the same problem for days until I noticed (how could I look at it and not read the code :-(..) that config.inc.php is calling config-db.php

** MySql Server version: 5.7.5-m15
** Apache/2.4.10 (Ubuntu)
** phpMyAdmin 4.2.9.1deb0.1

/etc/phpmyadmin/config-db.php:

$dbuser='yourDBUserName';
$dbpass='';
$basepath='';
$dbname='phpMyAdminDBName';
$dbserver='';
$dbport='';
$dbtype='mysql';

Here you need to define your username, password, dbname and others that are showing empty' use default unless you changed their configuration. That solved the issue for me.
U hope it helps you.
latest.phpmyadmin.docs

How to restart Postgresql

This should work:

sudo systemctl stop postgresql

sudo systemctl start postgresql

Dealing with HTTP content in HTTPS pages

I don't know if this would fit what you are doing, but as a quick fix I would "wrap" the http content into an https script. For instance, on your page that is served through https i would introduce an iframe that would replace your rss feed and in the src attr of the iframe put a url of a script on your server that captures the feed and outputs the html. the script is reading the feed through http and outputs it through https (thus "wrapping")

Just a thought

How to identify a strong vs weak relationship on ERD?

We draw a solid line if and only if we have an ID-dependent relationship; otherwise it would be a dashed line.

Consider a weak but not ID-dependent relationship; We draw a dashed line because it is a weak relationship.

Easiest way to convert int to string in C++

Use:

#define convertToString(x) #x

int main()
{
    convertToString(42); // Returns const char* equivalent of 42
}

jQuery ui datepicker with Angularjs

myModule.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'dd/mm/yy',
                onSelect: function (date) {   
                    var ar=date.split("/");
                    date=new Date(ar[2]+"-"+ar[1]+"-"+ar[0]);
                    ngModelCtrl.$setViewValue(date.getTime());
                //    scope.course.launchDate = date;
                    scope.$apply();
                }
            });

        }
    };
});

HTML Code :

<input type="text" jqdatepicker  ng-model="course.launchDate" required readonly />

How to find and replace string?

Do we really need a Boost library for seemingly such a simple task?

To replace all occurences of a substring use this function:

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

Fatal error: Cannot use object of type stdClass as array in

Controller (Example: User.php)

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Users extends CI_controller
{

    // Table
    protected  $table = 'users';

    function index()
    {
        $data['users'] = $this->model->ra_object($this->table);
        $this->load->view('users_list', $data);
    }
}

View (Example: users_list.php)

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Surname</th>
        </tr>
    </thead>

    <tbody>
        <?php foreach($users as $user) : ?>
            <tr>
            <td><?php echo $user->name; ?></td>
            <td><?php echo $user->surname; ?></th>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<!-- // User table -->

SQL- Ignore case while searching for a string

You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI as your collation. The one you specify in your question is explictly case sensitive.

You can see a list of collations here.

How to disable the resize grabber of <textarea>?

example of textarea for disable the resize option

<textarea CLASS="foo"></textarea>

<style>
textarea.foo
{
resize:none;
}

</style>

How do you change the value inside of a textfield flutter?

_mytexteditingcontroller.value = new TextEditingController.fromValue(new TextEditingValue(text: "My String")).value;

This seems to work if anyone has a better way please feel free to let me know.

How to use string.substr() function?

Possible solution without using substr()

#include<iostream>
#include<string>

using namespace std;


int main() {
    string c="12345";
    int p=0;

    for(int i=0;i<c.length();i++) {
        cout<<c[i];
        p++;

        if (p % 2 == 0 && i != c.length()-1) {
            cout<<" "<<c[i];
            p++;
        }
    }
}

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

When you restore backup, Make sure to try with the same username for the old one and the new one.

Count unique values with pandas per groups

You need nunique:

df = df.groupby('domain')['ID'].nunique()

print (df)
domain
'facebook.com'    1
'google.com'      1
'twitter.com'     2
'vk.com'          3
Name: ID, dtype: int64

If you need to strip ' characters:

df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com    1
google.com      1
twitter.com     2
vk.com          3
Name: ID, dtype: int64

Or as Jon Clements commented:

df.groupby(df.domain.str.strip("'"))['ID'].nunique()

You can retain the column name like this:

df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
    domain  ID
0       fb   1
1      ggl   1
2  twitter   2
3       vk   3

The difference is that nunique() returns a Series and agg() returns a DataFrame.

Where is the Docker daemon log?

If your OS is using systemd then you can view docker daemon log with:

sudo journalctl -fu docker.service

How can I programmatically check whether a keyboard is present in iOS app?

Swift implementation:

class KeyboardStateListener: NSObject
{
  static var shared = KeyboardStateListener()
  var isVisible = false

  func start() {
    let nc = NSNotificationCenter.defaultCenter()
    nc.addObserver(self, selector: #selector(didShow), name: UIKeyboardDidShowNotification, object: nil)
    nc.addObserver(self, selector: #selector(didHide), name: UIKeyboardDidHideNotification, object: nil)
  }

  func didShow()
  {
    isVisible = true
  }

  func didHide()
  {
    isVisible = false
  } 
}

Because swift doesn't execute class load method on startup it is important to start this service on app launch:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool
{
  ...    
  KeyboardStateListener.shared.start() 
}

Oracle PL/SQL - How to create a simple array variable?

You could just declare a DBMS_SQL.VARCHAR2_TABLE to hold an in-memory variable length array indexed by a BINARY_INTEGER:

DECLARE
   name_array dbms_sql.varchar2_table;
BEGIN
   name_array(1) := 'Tim';
   name_array(2) := 'Daisy';
   name_array(3) := 'Mike';
   name_array(4) := 'Marsha';
   --
   FOR i IN name_array.FIRST .. name_array.LAST
   LOOP
      -- Do something
   END LOOP;
END;

You could use an associative array (used to be called PL/SQL tables) as they are an in-memory array.

DECLARE
   TYPE employee_arraytype IS TABLE OF employee%ROWTYPE
        INDEX BY PLS_INTEGER;
   employee_array employee_arraytype;
BEGIN
   SELECT *
     BULK COLLECT INTO employee_array
     FROM employee
    WHERE department = 10;
   --
   FOR i IN employee_array.FIRST .. employee_array.LAST
   LOOP
      -- Do something
   END LOOP;
END;

The associative array can hold any make up of record types.

Hope it helps, Ollie.

How to normalize a vector in MATLAB efficiently? Any related built-in function?

By the rational of making everything multiplication I add the entry at the end of the list

    clc; clear all;
    V = rand(1024*1024*32,1);
    N = 10;
    tic; for i=1:N, V1 = V/norm(V);         end; toc % 4.5 s
    tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 7.5 s
    tic; for i=1:N, V3 = V/sqrt(V'*V);      end; toc % 4.9 s
    tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 6.8 s
    tic; for i=1:N, V1 = V/norm(V);         end; toc % 4.7 s
    tic; for i=1:N, d = 1/norm(V); V1 = V*d;end; toc % 4.9 s
    tic; for i=1:N, d = norm(V)^-1; V1 = V*d;end;toc % 4.4 s

Visual Studio 2015 doesn't have cl.exe

In Visual Studio 2019 you can find cl.exe inside

32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64

Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.

32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"

If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.

Converting NSString to NSDate (and back again)

If anyone is interested in doing something like this in Swift these days, I have a start on something, although it's not perfect.

func detectDate(dateString: NSString) -> NSDate {

    var error: NSError?
    let detector: NSDataDetector = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Date.toRaw(), error: &error)!

    if error == nil {
        var matches = detector.matchesInString(dateString, options: nil, range: NSMakeRange(0, dateString.length))

        let currentLocale = NSLocale.currentLocale()
        for match in matches {
            match.resultType == NSTextCheckingType.Date
            NSLog("Date: \(match.date.description)")
            return match.date
        }
    }
    return NSDate()
}

Java - Convert image to Base64

Late GraveDig ... Just constrain your byte array to the file size.

FileInputStream fis = new FileInputStream( file );
byte[] byteArray= new byte[(int) file.length()];

How to run a jar file in a linux commandline

For OpenSuse Linux, One can simply install the java-binfmt package in the zypper repository as shown below:

sudo zypper in java-binfmt-misc
chmod 755 file.jar
./file.jar

jQuery - selecting elements from inside a element

Have a look here -- to query a sub-element of an element:

$(document.getElementById('parentid')).find('div#' + divID + ' span.child');

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Change your code to.

<?php
$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".$rows['user'];
?>

There was syntax error in your query.

How can I add C++11 support to Code::Blocks compiler?

The answer with screenshots (put the checkbox as in the second pic, then press OK):

enter image description here enter image description here

ViewDidAppear is not called when opening app from background

Curious about the exact sequence of events, I instrumented an app as follows: (@Zohaib, you can use the NSNotificationCenter code below to answer your question).

// AppDelegate.m

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    NSLog(@"app will enter foreground");
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    NSLog(@"app did become active");
}

// ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"view did load");

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)appDidBecomeActive:(NSNotification *)notification {
    NSLog(@"did become active notification");
}

- (void)appWillEnterForeground:(NSNotification *)notification {
    NSLog(@"will enter foreground notification");
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"view will appear");
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"view did appear");
}

At launch, the output looks like this:

2013-04-07 09:31:06.505 myapp[15459:11303] view did load
2013-04-07 09:31:06.507 myapp[15459:11303] view will appear
2013-04-07 09:31:06.511 myapp[15459:11303] app did become active
2013-04-07 09:31:06.512 myapp[15459:11303] did become active notification
2013-04-07 09:31:06.517 myapp[15459:11303] view did appear

Enter the background then reenter the foreground:

2013-04-07 09:32:05.923 myapp[15459:11303] app will enter foreground
2013-04-07 09:32:05.924 myapp[15459:11303] will enter foreground notification
2013-04-07 09:32:05.925 myapp[15459:11303] app did become active
2013-04-07 09:32:05.926 myapp[15459:11303] did become active notification

How to check if a list is empty in Python?

if not myList:
  print "Nothing here"

Core dumped, but core file is not in the current directory?

In Ubuntu18.04, the most easist way to get a core file is inputing the command below to stop the apport service.

sudo service apport stop

Then rerun the application, you will get dump file in current directory.

Equivalent to 'app.config' for a library (DLL)

In response to the original question, I typically add the config file in my test project as a link; you can then use the DeploymentItem attribute to addit to the Out folder of the test run.

[TestClass]
[DeploymentItem("MyProject.Cache.dll.config")]
public class CacheTest
{
    .
    .
    .
    .
}

In response to the comments that Assemblies can't be project specific, they can and it provides great flexibility esp. when working with IOC frameworks.

What is the purpose of mvnw and mvnw.cmd files?

Command mvnw uses Maven that is by default downloaded to ~/.m2/wrapper on the first use.

URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties:

distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

To update or change Maven version invoke the following (remember about --non-recursive for multi-module projects):

./mvnw io.takari:maven:wrapper -Dmaven=3.3.9 

or just modify .mvn/wrapper/maven-wrapper.properties manually.

To generate wrapper from scratch using Maven (you need to have it already in PATH run:

mvn io.takari:maven:wrapper -Dmaven=3.3.9 

RegEx for matching "A-Z, a-z, 0-9, _" and "."

^[A-Za-z0-9_.]+$

From beginning until the end of the string, match one or more of these characters.

Edit:

Note that ^ and $ match the beginning and the end of a line. When multiline is enabled, this can mean that one line matches, but not the complete string.

Use \A for the beginning of the string, and \z for the end.

See for example: http://msdn.microsoft.com/en-us/library/h5181w5w(v=vs.110).aspx

How to set iframe size dynamically

Not quite sure what the 300 is supposed to mean? Miss typo? However for iframes it would be best to use CSS :) - Ive found befor when importing youtube videos that it ignores inline things.

<style>
    #myFrame { width:100%; height:100%; }
</style>

<iframe src="html_intro.asp" id="myFrame">
<p>Hi SOF</p>
</iframe>

Is there a unique Android device ID?

For detailed instructions on how to get a unique identifier for each Android device your application is installed from, see the official Android Developers Blog posting Identifying App Installations.

It seems the best way is for you to generate one yourself upon installation and subsequently read it when the application is re-launched.

I personally find this acceptable but not ideal. No one identifier provided by Android works in all instances as most are dependent on the phone's radio states (Wi-Fi on/off, cellular on/off, Bluetooth on/off). The others, like Settings.Secure.ANDROID_ID must be implemented by the manufacturer and are not guaranteed to be unique.

The following is an example of writing data to an installation file that would be stored along with any other data the application saves locally.

public class Installation {
    private static String sID = null;
    private static final String INSTALLATION = "INSTALLATION";

    public synchronized static String id(Context context) {
        if (sID == null) {
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if (!installation.exists())
                    writeInstallationFile(installation);
                sID = readInstallationFile(installation);
            } 
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sID;
    }

    private static String readInstallationFile(File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    private static void writeInstallationFile(File installation) throws IOException {
        FileOutputStream out = new FileOutputStream(installation);
        String id = UUID.randomUUID().toString();
        out.write(id.getBytes());
        out.close();
    }
}

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:

Convert date yyyyMMdd to system.datetime format

have at look at the static methods DateTime.Parse() and DateTime.TryParse(). They will allow you to pass in your date string and a format string, and get a DateTime object in return.

http://msdn.microsoft.com/en-us/library/6fw7727c.aspx

How to overcome "'aclocal-1.15' is missing on your system" warning?

2018, yet another solution ...

https://github.com/apereo/mod_auth_cas/issues/97

in some cases simply running

$ autoreconf -f -i

and nothing else .... solves the problem.

You do that in the directory /pcre2-10.30 .

What a nightmare.

(This usually did not solve the problem in 2017, but now usually does seem to solve the problem - they fixed something. Also, it seems your Dockerfile should now usually start with "FROM ibmcom/swift-ubuntu" ; previously you had to give a certain version/dev-build to make it work.)

Callback functions in Java

yet i see there is most preferred way which was what i was looking for.. it's basically derived from these answers but i had to manipulate it to more more redundant and efficient.. and i think everybody looking for what i come up with

To the point::

first make an Interface that simple

public interface myCallback {
    void onSuccess();
    void onError(String err);
}

now to make this callback run when ever you wish to do to handle the results - more likely after async call and you wanna run some stuff which depends on these reuslts

// import the Interface class here

public class App {

    public static void main(String[] args) {
        // call your method
        doSomething("list your Params", new myCallback(){
            @Override
            public void onSuccess() {
                // no errors
                System.out.println("Done");
            }

            @Override
            public void onError(String err) {
                // error happen
                System.out.println(err);
            }
        });
    }

    private void doSomething(String param, // some params..
                             myCallback callback) {
        // now call onSuccess whenever you want if results are ready
        if(results_success)
            callback.onSuccess();
        else
            callback.onError(someError);
    }

}

doSomething is the function that takes some time you wanna add a callback to it to notify you when the results came, add the call back interface as a parameter to this method

hope my point is clear, enjoy ;)

Convert from ASCII string encoded in Hex to plain ASCII?

Alternatively, you can also do this ...

Python 2 Interpreter

print "\x70 \x61 \x75 \x6c"

Example

user@linux:~# python
Python 2.7.14+ (default, Mar 13 2018, 15:23:44) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> print "\x70 \x61 \x75 \x6c"
p a u l
>>> exit()
user@linux:~# 

or

Python 2 One-Liner

python -c 'print "\x70 \x61 \x75 \x6c"'

Example

user@linux:~# python -c 'print "\x70 \x61 \x75 \x6c"'
p a u l
user@linux:~# 

Python 3 Interpreter

user@linux:~$ python3
Python 3.6.9 (default, Apr 18 2020, 01:56:04) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> print("\x70 \x61 \x75 \x6c")
p a u l

>>> print("\x70\x61\x75\x6c")
paul

Python 3 One-Liner

python -c 'print("\x70 \x61 \x75 \x6c")'

Example

user@linux:~$ python -c 'print("\x70 \x61 \x75 \x6c")'
p a u l

user@linux:~$ python -c 'print("\x70\x61\x75\x6c")'
paul

How to append multiple values to a list in Python

You can use the sequence method list.extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.

>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

So you can use list.append() to append a single value, and list.extend() to append multiple values.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

The problem occurs because webpack-dev-server 2.4.4 adds a host check. You can disable it by adding this to your webpack config:

 devServer: {
    compress: true,
    disableHostCheck: true,   // That solved it

 }      

EDIT: Please note, this fix is insecure.

Please see the following answer for a secure solution: https://stackoverflow.com/a/43621275/5425585

Mergesort with Python

from run_time import run_time
from random_arr import make_arr

def merge(arr1: list, arr2: list):
    temp = []
    x, y = 0, 0
    while len(arr1) and len(arr2):
        if arr1[0] < arr2[0]:
            temp.append(arr1[0])
            x += 1
            arr1 = arr1[x:]
        elif arr1[0] > arr2[0]:
            temp.append(arr2[0])
            y += 1
            arr2 = arr2[y:]
        else:
            temp.append(arr1[0])
            temp.append(arr2[0])
            x += 1
            y += 1
            arr1 = arr1[x:]
            arr2 = arr2[y:]

    if len(arr1) > 0:
        temp += arr1
    if len(arr2) > 0:
        temp += arr2
    return temp

@run_time
def merge_sort(arr: list):
    total = len(arr)
    step = 2
    while True:
        for i in range(0, total, step):
            arr[i:i + step] = merge(arr[i:i + step//2], arr[i + step//2:i + step])
        step *= 2
        if step > 2 * total:
            return arr

arr = make_arr(20000)
merge_sort(arr)
# run_time is 0.10300588607788086

Read a javascript cookie by name

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");

    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
     }
}

Source: W3Schools

Edit: as @zcrar70 noted, the above code is incorrect, please see the following answer Javascript getCookie functions

Display QImage with QtGui

One common way is to add the image to a QLabel widget using QLabel::setPixmap(), and then display the QLabel as you would any other widget. Example:

#include <QtGui>

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  QPixmap pm("your-image.jpg");
  QLabel lbl;
  lbl.setPixmap(pm);
  lbl.show();
  return app.exec();
}

How to set the font size in Emacs?

Aquamacs:

(set-face-attribute 'default nil :font "Monaco-16" )

From the Emacs Wiki Globally Change the Default Font, it says you can use either of these:

(set-face-attribute 'default nil :font FONT )

(set-frame-font FONT nil t)

Where FONT is something like "Monaco-16", e.g.:

(set-face-attribute 'default nil :font "Monaco-16" )

There was an extra closing parenthesis in the first suggestion on the wiki, which caused an error on startup. I finally noticed the extra closing parenthesis, and I subsequently corrected the suggestion on the wiki. Then both of the suggestions worked for me.

return string with first match Regex

You shouldn't be using .findall() at all - .search() is what you want. It finds the leftmost match, which is what you want (or returns None if no match exists).

m = re.search(pattern, text)
result = m.group(0) if m else ""

Whether you want to put that in a function is up to you. It's unusual to want to return an empty string if no match is found, which is why nothing like that is built in. It's impossible to get confused about whether .search() on its own finds a match (it returns None if it didn't, or an SRE_Match object if it did).

Apache: "AuthType not set!" 500 Error

The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?

Require all granted is only in 2.4, but Allow all ... stops working in 2.4, and we want to be able to rollout a config that works in both.

The only solution I found, which I am not sure is the proper one, is to use:

# backwards compatibility with apache 2.2
Order allow,deny
Allow from all

# forward compatibility with apache 2.4
Require all granted
Satisfy Any

This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...

See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

mongoError: Topology was destroyed

I was struggling with this for some time - As you can see from other answers, the issue can be very different.

The easiest way to find out whats causing is this is to turn on loggerLevel: 'info' in the options

How to make Apache serve index.php instead of index.html?

PHP will work only on the .php file extension.

If you are on Apache you can also set, in your httpd.conf file, the extensions for PHP. You'll have to find the line:

AddType application/x-httpd-php .php .html
                                     ^^^^^

and add how many extensions, that should be read with the PHP interpreter, as you want.

Links in <select> dropdown options

... or if you want / need to keep your option 'value' as it was, just add a new attribute:

<select id="my_selection">
<option value="x" href="/link/to/somewhere">value 1</option>
<option value="y" href="/link/to/somewhere/else">value 2</option>
</select>

<script>
document.getElementById('my_selection').onchange = function() {
    window.location.href = this.children[this.selectedIndex].getAttribute('href');
}
</script>

How to save user input into a variable in html and js

Like I use on PHP and JavaScript:

<input type="hidden" id="CatId" value="<?php echo $categoryId; ?>">

Update the JavaScript:

var categoryId = document.getElementById('CatId').value;

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

Remove duplicates from a list of objects based on property in Java 8

This worked for me:

list.stream().distinct().collect(Collectors.toList());

You need to implement equals, of course

Uncaught TypeError: Cannot read property 'value' of null

I am unsure which of them is wrong because you did not provide your HTML, but one of these does not exist:

var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
var str2 = document.getElementById("holiday").value;
var str3 = document.getElementById("cal_option").value;

There is either no element with the id cal_preview, year, holiday, cal_option, or some combination.

Therefore, JavaScript is unable to read the value of something that does not exist.

EDIT:

If you want to check that the element exists first, you could use an if statement for each:

var str,
element = document.getElementById('cal_preview');
if (element != null) {
    str = element.value;
}
else {
    str = null;
}

You could obviously change the else statement if you want or have no else statement at all, but that is all about preference.

Dynamic Web Module 3.0 -- 3.1

I had the same problem and fixed this by editing org.eclipse.wst.common.project.facet.core.xml.

In this file, I was able to change the following line

<installed facet="jst.web" version="3.1"/>

back to

<installed facet="jst.web" version="3.0"/>

That seemed to fix the problem for me.

How to use JavaScript regex over multiple lines?

Now there's the s (single line) modifier, that lets the dot matches new lines as well :) \s will also match new lines :D

Just add the s behind the slash

 /<pre.*?<\/pre>/gms

How to throw an exception in C?

C doesn't support exceptions. You can try compiling your C code as C++ with Visual Studio or G++ and see if it'll compile as-is. Most C applications will compile as C++ without major changes, and you can then use the try... catch syntax.

process.waitFor() never returns

It appears you are not reading the output before waiting for it to finish. This is fine only if the output doesn't fill the buffer. If it does, it will wait until you read the output, catch-22.

Perhaps you have some errors which you are not reading. This would case the application to stop and waitFor to wait forever. A simple way around this is to re-direct the errors to the regular output.

ProcessBuilder pb = new ProcessBuilder("tasklist");
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
    System.out.println("tasklist: " + line);
process.waitFor();

Best way to make WPF ListView/GridView sort on column-header clicking?

I wrote a set of attached properties to automatically sort a GridView, you can check it out here. It doesn't handle the up/down arrow, but it could easily be added.

<ListView ItemsSource="{Binding Persons}"
          IsSynchronizedWithCurrentItem="True"
          util:GridViewSort.AutoSort="True">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn Header="Name"
                                DisplayMemberBinding="{Binding Name}"
                                util:GridViewSort.PropertyName="Name"/>
                <GridViewColumn Header="First name"
                                DisplayMemberBinding="{Binding FirstName}"
                                util:GridViewSort.PropertyName="FirstName"/>
                <GridViewColumn Header="Date of birth"
                                DisplayMemberBinding="{Binding DateOfBirth}"
                                util:GridViewSort.PropertyName="DateOfBirth"/>
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>

How to check if a String contains any of some strings

If you need ContainsAny with a specific StringComparison (for example to ignore case) then you can use this String Extentions method.

public static class StringExtensions
{
    public static bool ContainsAny(this string input, IEnumerable<string> containsKeywords, StringComparison comparisonType)
    {
        return containsKeywords.Any(keyword => input.IndexOf(keyword, comparisonType) >= 0);
    }
}

Usage with StringComparison.CurrentCultureIgnoreCase:

var input = "My STRING contains Many Substrings";
var substrings = new[] {"string", "many substrings", "not containing this string" };
input.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// The statement above returns true.

”xyz”.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// This statement returns false.

Homebrew install specific version of formula?

Based on the workflow described by @tschundeee and @Debilski’s update 1, I automated the procedure and added cleanup in this script.

Download it, put it in your path and brewv <formula_name> <wanted_version>. For the specific OP, it would be:

cd path/to/downloaded/script/
./brewv postgresql 8.4.4

:)

An error occurred while collecting items to be installed (Access is denied)

I got this error on my ubuntu box until I ran eclipse as root and installed from there:

$ gksudo eclipse

Eclipse was trying to download the packages to /usr/lib/* where I don't have write permissions

How to print out a variable in makefile

from a "Mr. Make post" https://www.cmcrossroads.com/article/printing-value-makefile-variable

Add the following rule to your Makefile:

print-%  : ; @echo $* = $($*)

Then, if you want to find out the value of a makefile variable, just:

make print-VARIABLE

and it will return:

VARIABLE = the_value_of_the_variable

Coding Conventions - Naming Enums

If I can add my $0.02, I prefer using PascalCase as enum values in C.

In C, they are basically global, and PEER_CONNECTED gets really tiring as opposed to PeerConnected.

Breath of fresh air.

Literally, it makes me breathe easier.

In Java, it is possible to use raw enum names as long as you static import them from another class.

import static pkg.EnumClass.*;

Now, you can use the unqualified names, that you qualified in a different way already.

I am currently (thinking) about porting some C code to Java and currently 'torn' between choosing Java convention (which is more verbose, more lengthy, and more ugly) and my C style.

PeerConnected would become PeerState.CONNECTED except in switch statements, where it is CONNECTED.

Now there is much to say for the latter convention and it does look nice but certain "idiomatic phrases" such as if (s == PeerAvailable) become like if (s == PeerState.AVAILABLE) and nostalgically, this is a loss of meaning to me.

I think I still prefer the Java style because of clarity but I have a hard time looking at the screaming code.

Now I realize PascalCase is already widely used in Java but very confusing it would not really be, just a tad out of place.

What can cause a “Resource temporarily unavailable” on sock send() command

"Resource temporarily unavailable" is the error message corresponding to EAGAIN, which means that the operation would have blocked but nonblocking operation was requested. For send(), that could be due to any of:

  • explicitly marking the file descriptor as nonblocking with fcntl(); or
  • passing the MSG_DONTWAIT flag to send(); or
  • setting a send timeout with the SO_SNDTIMEO socket option.

How do I cancel an HTTP fetch() request?

As for now there is no proper solution, as @spro says.

However, if you have an in-flight response and are using ReadableStream, you can close the stream to cancel the request.

fetch('http://example.com').then((res) => {
  const reader = res.body.getReader();

  /*
   * Your code for reading streams goes here
   */

  // To abort/cancel HTTP request...
  reader.cancel();
});

In jQuery, how do I get the value of a radio button when they all have the same name?

There is another way also. Try below code

$(document).ready(function(){

      $("input[name='gender']").on("click", function() {
            alert($(this).val());
        });
});

Jenkins - passing variables between jobs?

I think the answer above needs some update:

I was trying to create a dynamic directory to store my upstream build artifacts so I wanted to pass my upstream job build number to downstream job I tried the above steps but couldn't make it work. Here is how it worked:

  1. I copied the artifacts from my current job using copy artifacts plugin.
  2. In post build action of upstream job I added the variable like "SOURCE_BUILD_NUMBER=${BUILD_NUMBER}" and configured it to trigger the downstream job.
  3. Everything worked except that my downstream job was not able to get $SOURCE_BUILD_NUMBER to create the directory.
  4. So I found out that to use this variable I have to define the same variable in down stream job as a parameter variable like in this picture below:

enter image description here

This is because the new version of jenkins require's you to define the variable in the downstream job as well. I hope it's helpful.

How do I automatically set the $DISPLAY variable for my current session?

You'll need to tell your vnc client to export the correct $DISPLAY once you have logged in. How you do that will probably depend on your vnc client.

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

How to set a primary key in MongoDB?

One way of achieving this behaviour is by setting the value to _id (which is reserved for a primary key in MongoDB) field based on the custom fields you want to treat as primary key.
i.e. If I want employee_id as the primary key then at the time of creating document in MongoDB; assign _id value same as that of employee_id.

How should I use try-with-resources with JDBC?

As others have stated, your code is basically correct though the outer try is unneeded. Here are a few more thoughts.

DataSource

Other answers here are correct and good, such the accepted Answer by bpgergo. But none of the show the use of DataSource, commonly recommended over use of DriverManager in modern Java.

So for the sake of completeness, here is a complete example that fetches the current date from the database server. The database used here is Postgres. Any other database would work similarly. You would replace the use of org.postgresql.ds.PGSimpleDataSource with an implementation of DataSource appropriate to your database. An implementation is likely provided by your particular driver, or connection pool if you go that route.

A DataSource implementation need not be closed, because it is never “opened”. A DataSource is not a resource, is not connected to the database, so it is not holding networking connections nor resources on the database server. A DataSource is simply information needed when making a connection to the database, with the database server's network name or address, the user name, user password, and various options you want specified when a connection is eventually made. So your DataSource implementation object does not go inside your try-with-resources parentheses.

Nested try-with-resources

Your code makes proper used of nested try-with-resources statements.

Notice in the example code below that we also use the try-with-resources syntax twice, one nested inside the other. The outer try defines two resources: Connection and PreparedStatement. The inner try defines the ResultSet resource. This is a common code structure.

If an exception is thrown from the inner one, and not caught there, the ResultSet resource will automatically be closed (if it exists, is not null). Following that, the PreparedStatement will be closed, and lastly the Connection is closed. Resources are automatically closed in reverse order in which they were declared within the try-with-resource statements.

The example code here is overly simplistic. As written, it could be executed with a single try-with-resources statement. But in a real work you will likely be doing more work between the nested pair of try calls. For example, you may be extracting values from your user-interface or a POJO, and then passing those to fulfill ? placeholders within your SQL via calls to PreparedStatement::set… methods.

Syntax notes

Trailing semicolon

Notice that the semicolon trailing the last resource statement within the parentheses of the try-with-resources is optional. I include it in my own work for two reasons: Consistency and it looks complete, and it makes copy-pasting a mix of lines easier without having to worry about end-of-line semicolons. Your IDE may flag the last semicolon as superfluous, but there is no harm in leaving it.

Java 9 – Use existing vars in try-with-resources

New in Java 9 is an enhancement to try-with-resources syntax. We can now declare and populate the resources outside the parentheses of the try statement. I have not yet found this useful for JDBC resources, but keep it in mind in your own work.

ResultSet should close itself, but may not

In an ideal world the ResultSet would close itself as the documentation promises:

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

Unfortunately, in the past some JDBC drivers infamously failed to fulfill this promise. As a result, many JDBC programmers learned to explicitly close all their JDBC resources including Connection, PreparedStatement, and ResultSet too. The modern try-with-resources syntax has made doing so easier, and with more compact code. Notice that the Java team went to the bother of marking ResultSet as AutoCloseable, and I suggest we make use of that. Using a try-with-resources around all your JDBC resources makes your code more self-documenting as to your intentions.

Code example

package work.basil.example;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Objects;

public class App
{
    public static void main ( String[] args )
    {
        App app = new App();
        app.doIt();
    }

    private void doIt ( )
    {
        System.out.println( "Hello World!" );

        org.postgresql.ds.PGSimpleDataSource dataSource = new org.postgresql.ds.PGSimpleDataSource();

        dataSource.setServerName( "1.2.3.4" );
        dataSource.setPortNumber( 5432 );

        dataSource.setDatabaseName( "example_db_" );
        dataSource.setUser( "scott" );
        dataSource.setPassword( "tiger" );

        dataSource.setApplicationName( "ExampleApp" );

        System.out.println( "INFO - Attempting to connect to database: " );
        if ( Objects.nonNull( dataSource ) )
        {
            String sql = "SELECT CURRENT_DATE ;";
            try (
                    Connection conn = dataSource.getConnection() ;
                    PreparedStatement ps = conn.prepareStatement( sql ) ;
            )
            {
                … make `PreparedStatement::set…` calls here.
                try (
                        ResultSet rs = ps.executeQuery() ;
                )
                {
                    if ( rs.next() )
                    {
                        LocalDate ld = rs.getObject( 1 , LocalDate.class );
                        System.out.println( "INFO - date is " + ld );
                    }
                }
            }
            catch ( SQLException e )
            {
                e.printStackTrace();
            }
        }

        System.out.println( "INFO - all done." );
    }
}

What is the maximum length of a valid email address?

The other answers muddy the water a bit. Simple answer: 254 total chars in our control for email 256 are for the ENTIRE email address, which includes implied "<" at the beginning, and ">" at the end. Therefore, 254 are left over for our use.

Contains method for a slice

If the slice is sorted, there is a binary search implemented in the sort package.

Getting value from a cell from a gridview on RowDataBound event

protected void gvbind_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';";
        e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
        e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvbind, "Select$" + e.Row.RowIndex);
    }
}

Java Singleton and Synchronization

Yes, you need to make getInstance() synchronized. If it's not there might arise a situation where multiple instances of the class can be made.

Consider the case where you have two threads that call getInstance() at the same time. Now imagine T1 executes just past the instance == null check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance() synchronized prevents this problem.

There a few ways to make singletons thread-safe, but making getInstance() synchronized is probably the simplest.

How to check if a variable is null or empty string or all whitespace in JavaScript?

function isEmptyOrSpaces(str){
    return str === null || str.match(/^[\s\n\r]*$/) !== null;
}

How to add a href link in PHP?

Just do it in HTML

<a href="https://www.google.com">Google</a>

What is the use of printStackTrace() method in Java?

printStackTrace() prints the locations where the exception occurred in the source code, thus allowing the author who wrote the program to see what went wrong. But since it shows problems in the source code, the user(s) who may or may not have any coding experience may not be able to understand what went wrong, so if the program allows the user to send error messages to the authors, the users may not be able to give good data on what went wrong.

You should consider the Logger.getLogger() method, it offers a better exception handling (logging) facility, and besides printStackTrace() without arguments is considered to be obsolete and should ONLY be used for debugging purposes, not for user display.

Can I hide the HTML5 number input’s spin box?

Short answer:

_x000D_
_x000D_
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
input[type="number"] {
    -moz-appearance: textfield;
}
_x000D_
<input type="number" />
_x000D_
_x000D_
_x000D_

Longer answer:

To add to existing answer...

Firefox:

In current versions of Firefox, the (user agent) default value of the -moz-appearance property on these elements is number-input. Changing that to the value textfield effectively removes the spinner.

input[type="number"] {
    -moz-appearance: textfield;
}

In some cases, you may want the spinner to be hidden initially, and then appear on hover/focus. (This is currently the default behavior in Chrome). If so, you can use the following:

_x000D_
_x000D_
input[type="number"] {
    -moz-appearance: textfield;
}
input[type="number"]:hover,
input[type="number"]:focus {
    -moz-appearance: number-input;
}
_x000D_
<input type="number"/>
_x000D_
_x000D_
_x000D_


Chrome:

In current versions of Chrome, the (user agent) default value of the -webkit-appearance property on these elements is already textfield. In order to remove the spinner, the -webkit-appearance property's value needs to be changed to none on the ::-webkit-outer-spin-button/::-webkit-inner-spin-button pseudo classes (it is -webkit-appearance: inner-spin-button by default).

_x000D_
_x000D_
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
_x000D_
<input type="number" />
_x000D_
_x000D_
_x000D_

It's worth pointing out that margin: 0 is used to remove the margin in older versions of Chrome.

Currently, as of writing this, here is the default user agent styling on the 'inner-spin-button' pseudo class:

input::-webkit-inner-spin-button {
    -webkit-appearance: inner-spin-button;
    display: inline-block;
    cursor: default;
    flex: 0 0 auto;
    align-self: stretch;
    -webkit-user-select: none;
    opacity: 0;
    pointer-events: none;
    -webkit-user-modify: read-only;
}

SQL query for a carriage return in a string and ultimately removing carriage return

You can also use regular expressions:

SELECT * FROM Parameters WHERE Name REGEXP '\n';

APR based Apache Tomcat Native library was not found on the java.library.path?

My case: Seeing the same INFO message.

Centos 6.2 x86_64 Tomcat 6.0.24

This fixed the problem for me:

yum install tomcat-native

boom!

How can I declare and define multiple variables in one line using C++?

If you declare one variable/object per line not only does it solve this problem, but it makes the code clearer and prevents silly mistakes when declaring pointers.

To directly answer your question though, you have to initialize each variable to 0 explicitly. int a = 0, b = 0, c = 0;.

Convert Python dict into a dataframe

Pass the items of the dictionary to the DataFrame constructor, and give the column names. After that parse the Date column to get Timestamp values.

Note the difference between python 2.x and 3.x:

In python 2.x:

df = pd.DataFrame(data.items(), columns=['Date', 'DateValue'])
df['Date'] = pd.to_datetime(df['Date'])

In Python 3.x: (requiring an additional 'list')

df = pd.DataFrame(list(data.items()), columns=['Date', 'DateValue'])
df['Date'] = pd.to_datetime(df['Date'])

How to find distinct rows with field in list using JPA and Spring?

@Query("SELECT DISTINCT name FROM people WHERE name NOT IN (:names)")
List<String> findNonReferencedNames(@Param("names") List<String> names);

How do I get a list of files in a directory in C++?

If you're in Windows & using MSVC, the MSDN library has sample code that does this.

And here's the code from that link:

#include <windows.h>
#include <tchar.h> 
#include <stdio.h>
#include <strsafe.h>

void ErrorHandler(LPTSTR lpszFunction);

int _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA ffd;
   LARGE_INTEGER filesize;
   TCHAR szDir[MAX_PATH];
   size_t length_of_arg;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;

   // If the directory is not specified as a command-line argument,
   // print usage.

   if(argc != 2)
   {
      _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
      return (-1);
   }

   // Check that the input path plus 2 is not longer than MAX_PATH.

   StringCchLength(argv[1], MAX_PATH, &length_of_arg);

   if (length_of_arg > (MAX_PATH - 2))
   {
      _tprintf(TEXT("\nDirectory path is too long.\n"));
      return (-1);
   }

   _tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);

   // Prepare string for use with FindFile functions.  First, copy the
   // string to a buffer, then append '\*' to the directory name.

   StringCchCopy(szDir, MAX_PATH, argv[1]);
   StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

   // Find the first file in the directory.

   hFind = FindFirstFile(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
      return dwError;
   } 

   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
      }
      else
      {
         filesize.LowPart = ffd.nFileSizeLow;
         filesize.HighPart = ffd.nFileSizeHigh;
         _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);

   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
   }

   FindClose(hFind);
   return dwError;
}


void ErrorHandler(LPTSTR lpszFunction) 
{ 
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

Java Compare Two Lists

public static boolean compareList(List ls1, List ls2){
    return ls1.containsAll(ls2) && ls1.size() == ls2.size() ? true :false;
     }

public static void main(String[] args) {

    ArrayList<String> one = new ArrayList<String>();
    one.add("one");
    one.add("two");
    one.add("six");

    ArrayList<String> two = new ArrayList<String>();
    two.add("one");
    two.add("six");
    two.add("two");

    System.out.println("Output1 :: " + compareList(one, two));

    two.add("ten");

    System.out.println("Output2 :: " + compareList(one, two));
  }

Ruby on Rails: Clear a cached page

This line in development.rb ensures that caching is not happening.

config.action_controller.perform_caching             = false

You can clear the Rails cache with

Rails.cache.clear

That said - I am not convinced this is a caching issue. Are you making changes to the page and not seeing them reflected? You aren't perhaps looking at the live version of that page? I have done that once (blush).

Update:

You can call that command from in the console. Are you sure you are running the application in development?

The only alternative is that the page that you are trying to render isn't the page that is being rendered.

If you watch the server output you should be able to see the render command when the page is rendered similar to this:

Rendered shared_partials/_latest_featured_video (31.9ms)
Rendered shared_partials/_s_invite_friends (2.9ms)
Rendered layouts/_sidebar (2002.1ms)
Rendered layouts/_footer (2.8ms)
Rendered layouts/_busy_indicator (0.6ms)

How does the JPA @SequenceGenerator annotation work

I use this and it works right

@Id
@GeneratedValue(generator = "SEC_ODON", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "SEC_ODON", sequenceName = "SO.SEC_ODON",allocationSize=1)
@Column(name="ID_ODON", unique=true, nullable=false, precision=10, scale=0)
public Long getIdOdon() {
    return this.idOdon;
}

How to implement a ConfigurationSection with a ConfigurationElementCollection

The previous answer is correct but I'll give you all the code as well.

Your app.config should look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
   </configSections>
   <ServicesSection>
      <Services>
         <add Port="6996" ReportType="File" />
         <add Port="7001" ReportType="Other" />
      </Services>
   </ServicesSection>
</configuration>

Your ServiceConfig and ServiceCollection classes remain unchanged.

You need a new class:

public class ServiceConfigurationSection : ConfigurationSection
{
   [ConfigurationProperty("Services", IsDefaultCollection = false)]
   [ConfigurationCollection(typeof(ServiceCollection),
       AddItemName = "add",
       ClearItemsName = "clear",
       RemoveItemName = "remove")]
   public ServiceCollection Services
   {
      get
      {
         return (ServiceCollection)base["Services"];
      }
   }
}

And that should do the trick. To consume it you can use:

ServiceConfigurationSection serviceConfigSection =
   ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;

ServiceConfig serviceConfig = serviceConfigSection.Services[0];

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

You don't need to downgrade your gulp from gulp 4. Use gulp.series() to combine multiple tasks. At first install gulp globally with

npm install --global gulp-cli

and then install locally on your working directory with

npm install --save-dev gulp

see details here

Example:

package.json

{
  "name": "gulp-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.26.3",
    "gulp": "^4.0.0",
    "gulp-sass": "^4.0.2"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "jquery": "^3.3.1",
    "popper.js": "^1.14.7"
  }
}

gulpfile.js

var gulp = require("gulp");
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();

// Specific Task
function js() {
    return gulp
    .src(['node_modules/bootstrap/dist/js/bootstrap.min.js', 'node_modules/jquery/dist/jquery.min.js', 'node_modules/popper.js/dist/umd/popper.min.js'])
    .pipe(gulp.dest('src/js'))
    .pipe(browserSync.stream());
}
gulp.task(js);

// Specific Task
function gulpSass() {
    return gulp
    .src(['src/scss/*.scss'])
    .pipe(sass())
    .pipe(gulp.dest('src/css'))
    .pipe(browserSync.stream());
}
gulp.task(gulpSass);

// Run multiple tasks
gulp.task('start', gulp.series(js, gulpSass));

Run gulp start to fire multiple tasks & run gulp js or gulp gulpSass for specific task.

Use multiple css stylesheets in the same html page

Here is a simple alternative:

1/ Suppose we have two css files, say my1.css and my2.css. In the html document head type a link to one of them, within an element with an ID, say "demo":

2/ In the html document head body define two buttons calling two JS functions:

select css1
select css2

3/ Finally, in the JS file type the two functions as follows:

function select_css1() {
document.getElementById("demo").innerHTML = ''; }

function select_css2() {
document.getElementById("demo").innerHTML = ''; }

How to use Session attributes in Spring-mvc

Use This method very simple easy to use

HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();

                                                            request.getSession().setAttribute("errorMsg", "your massage");

in jsp once use then remove

<c:remove var="errorMsg" scope="session"/>      

Margin on child element moves parent element

I find out that, inside of your .css >if you set the display property of a div element to inline-block it fixes the problem. and margin will work as is expected.

How to redirect stdout to both file and console with scripting?

I've tried a few solutions here and didn't find the one that writes into file and into console at the same time. So here is what I did (based on this answer)

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout

    def write(self, message):
        with open ("logfile.log", "a", encoding = 'utf-8') as self.log:            
            self.log.write(message)
        self.terminal.write(message)

    def flush(self):
        #this flush method is needed for python 3 compatibility.
        #this handles the flush command by doing nothing.
        #you might want to specify some extra behavior here.
        pass
sys.stdout = Logger()   

This solution uses more computing power, but reliably saves all of the data from stdout into logger file and uses less memeory. For my needs I've added time stamp into self.log.write(message) aswell. Works great.

How do I capitalize first letter of first name and last name in C#?

Mc and Mac are common surname prefixes throughout the US, and there are others. TextInfo.ToTitleCase doesn't handle those cases and shouldn't be used for this purpose. Here's how I'm doing it:

    public static string ToTitleCase(string str)
    {
        string result = str;
        if (!string.IsNullOrEmpty(str))
        {
            var words = str.Split(' ');
            for (int index = 0; index < words.Length; index++)
            {
                var s = words[index];
                if (s.Length > 0)
                {
                    words[index] = s[0].ToString().ToUpper() + s.Substring(1);
                }
            }
            result = string.Join(" ", words);
        }
        return result;
    }

How to give environmental variable path for file appender in configuration file in log4j

Maybe... :

datestamp=yyyy-MM-dd/HH:mm:ss.SSS/zzz
layout=%d{${datestamp}} ms=%-4r [%t] %-5p %l %n%m %n%n

# infoFile 
log4j.appender.infoFile=org.apache.log4j.RollingFileAppender
log4j.appender.infoFile.File=${MY_HOME}/logs/message.log
log4j.appender.infoFile.layout=org.apache.log4j.PatternLayout
log4j.appender.infoFile.layout.ConversionPattern=${layout}

How can I suppress all output from a command using Bash?

Something like

script > /dev/null 2>&1

This will prevent standard output and error output, redirecting them both to /dev/null.