Programs & Examples On #Uidocumentinteraction

A document interaction controller, along with a delegate object, provides in-app support for managing user interactions with files in the local system

Basic example for sharing text or image with UIActivityViewController in Swift

I've used the implementation above and just now I came to know that it doesn't work on iPad running iOS 13. I had to add these lines before present() call in order to make it work

//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
     popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
     popoverController.sourceView = self.view
     popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}

That's how it works for me

func shareData(_ dataToShare: [Any]){

        let activityViewController = UIActivityViewController(activityItems: dataToShare, applicationActivities: nil)

        //exclude some activity types from the list (optional)
        //activityViewController.excludedActivityTypes = [
            //UIActivity.ActivityType.postToFacebook
        //]

        //avoiding to crash on iPad
        if let popoverController = activityViewController.popoverPresentationController {
            popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
            popoverController.sourceView = self.view
            popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
        }

        self.present(activityViewController, animated: true, completion: nil)
    }

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

chromeoptions=add_argument("--no-sandbox");
add_argument("--ignore-certificate-errors");
add_argument("--disable-dev-shm-usage'")

is not a supported browser

solution:

Open Browser    ${event_url}    ${BROWSER}   options=add_argument("--no-sandbox"); add_argument("--ignore-certificate-errors"); add_argument("--disable-dev-shm-usage'")

don't forget to add spaces between ${BROWSER} options

PHP new line break in emails

EDIT: Maybe your class for sending emails has an option for HTML emails and then you can use <br />

1) Double-quotes

$output = "Good news! The item# $item_number  on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n";

If you use double-quotes then \n will work (there will be no newline in browser but see the source code in your browser - the \n characters will be replaced for newlines)

2) Single quotes doesn't have the effect as the double-quotes above:

$output = 'Good news! The item# $item_number  on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n';

all characters will be printed as is (even variables!)

3) Line breaks in HTML

$html_output = "Good news! The item# $item_number  on which you placed a bid of <br />$ $bid_price is now available for purchase at your bid price.<br />The seller, $bid_user is making this offer.<br /><br />Item Title : $title<br /><br />All the best,<br /> $bid_user<br />$email<br />";
  • There will be line breaks in your browser and variables will be replaced with their content.

How can I get city name from a latitude and longitude point?

Here's a modern solution using a promise:

function getAddress (latitude, longitude) {
    return new Promise(function (resolve, reject) {
        var request = new XMLHttpRequest();

        var method = 'GET';
        var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true';
        var async = true;

        request.open(method, url, async);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    var data = JSON.parse(request.responseText);
                    var address = data.results[0];
                    resolve(address);
                }
                else {
                    reject(request.status);
                }
            }
        };
        request.send();
    });
};

And call it like this:

getAddress(lat, lon).then(console.log).catch(console.error);

The promise returns the address object in 'then' or the error status code in 'catch'

JavaScript style.display="none" or jQuery .hide() is more efficient?

Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.

In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden') which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.

How to use MD5 in javascript to transmit a password

You might want to check out this page: http://pajhome.org.uk/crypt/md5/

However, if protecting the password is important, you should really be using something like SHA256 (MD5 is not cryptographically secure iirc). Even more, you might want to consider using TLS and getting a cert so you can use https.

How to Identify port number of SQL server

Visually you can open "SQL Server Configuration Manager" and check properties of "Network Configuration":

SQL Server Configuration

Replace negative values in an numpy array

Another minimalist Python solution without using numpy:

[0 if i < 0 else i for i in a]

No need to define any extra functions.

a = [1, 2, 3, -4, -5.23, 6]
[0 if i < 0 else i for i in a]

yields:

[1, 2, 3, 0, 0, 6]

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

Configuring RollingFileAppender in log4j

I had a similar problem and just found a way to solve it (by single-stepping through log4j-extras source, no less...)

The good news is that, unlike what's written everywhere, it turns out that you actually CAN configure TimeBasedRollingPolicy using log4j.properties (XML config not needed! At least in versions of log4j >1.2.16 see this bug report)

Here is an example:

log4j.appender.File = org.apache.log4j.rolling.RollingFileAppender
log4j.appender.File.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.File.rollingPolicy.FileNamePattern = logs/worker-${instanceId}.%d{yyyyMMdd-HHmm}.log

BTW the ${instanceId} bit is something I am using on Amazon's EC2 to distinguish the logs from all my workers -- I just need to set that property before calling PropertyConfigurator.configure(), as follow:

p.setProperty("instanceId", EC2Util.getMyInstanceId());
PropertyConfigurator.configure(p);

how to create a cookie and add to http response from inside my service layer?

A cookie is a object with key value pair to store information related to the customer. Main objective is to personalize the customer's experience.

An utility method can be created like

private Cookie createCookie(String cookieName, String cookieValue) {
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setPath("/");
    cookie.setMaxAge(MAX_AGE_SECONDS);
    cookie.setHttpOnly(true);
    cookie.setSecure(true);
    return cookie;
}

If storing important information then we should alsways put setHttpOnly so that the cookie cannot be accessed/modified via javascript. setSecure is applicable if you are want cookies to be accessed only over https protocol.

using above utility method you can add cookies to response as

Cookie cookie = createCookie("name","value");
response.addCookie(cookie);

Maven: Non-resolvable parent POM

verify if You have correct values in child POMs

GroupId
ArtefactId
Version

In Eclipse, for example, You can search for it: Eclipse: search parent pom

How can I get terminal output in python?

You can use Popen in subprocess as they suggest.

with os, which is not recomment, it's like below:

import os
a  = os.popen('pwd').readlines()

SQL Server replace, remove all after certain character

For the times when some fields have a ";" and some do not you can also add a semi-colon to the field and use the same method described.

SET MyText = LEFT(MyText+';', CHARINDEX(';',MyText+';')-1)

TypeError: worker() takes 0 positional arguments but 1 was given

When doing Flask Basic auth I got this error and then I realized I had wrapped_view(**kwargs) and it worked after changing it to wrapped_view(*args, **kwargs).

How to call a Web Service Method?

James' answer is correct, of course, but I should remind you that the whole ASMX thing is, if not obsolete, at least not the current method. I strongly suggest that you look into WCF, if only to avoid learning things you will need to forget.

Creating instance list of different objects

I see that all of the answers suggest using a list filled with Object classes and then explicitly casting the desired class, and I personally don't like that kind of approach.

What works better for me is to create an interface which contains methods for retrieving or storing data from/to certain classes I want to put in a list. Have those classes implement that new interface, add the methods from the interface into them and then you can fill the list with interface objects - List<NewInterface> newInterfaceList = new ArrayList<>() thus being able to extract the desired data from the objects in a list without having the need to explicitly cast anything.

You can also put a comparator in the interface if you need to sort the list.

how to destroy bootstrap modal window completely?

bootstrap 3 + jquery 2.0.3:

$('#myModal').on('hide.bs.modal', function () {
   $('#myModal').removeData();
})

CSS Disabled scrolling

Try using the following code snippet. This should solve your issue.

body, html { 
    overflow-x: hidden; 
    overflow-y: auto;
}

What is Domain Driven Design?

You CAN ONLY understand Domain driven design by first comprehending what the following are:

What is a domain?

The field for which a system is built. Airport management, insurance sales, coffee shops, orbital flight, you name it.

It's not unusual for an application to span several different domains. For example, an online retail system might be working in the domains of shipping (picking appropriate ways to deliver, depending on items and destination), pricing (including promotions and user-specific pricing by, say, location), and recommendations (calculating related products by purchase history).

What is a model?

"A useful approximation to the problem at hand." -- Gerry Sussman

An Employee class is not a real employee. It models a real employee. We know that the model does not capture everything about real employees, and that's not the point of it. It's only meant to capture what we are interested in for the current context.

Different domains may be interested in different ways to model the same thing. For example, the salary department and the human resources department may model employees in different ways.

What is a domain model?

A model for a domain.

What is Domain-Driven Design (DDD)?

It is a development approach that deeply values the domain model and connects it to the implementation. DDD was coined and initially developed by Eric Evans.

Culled from here

Android get image path from drawable as string

These all are ways:

String imageUri = "drawable://" + R.drawable.image;

Other ways I tested

Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");

String path = path.toString();
String path = otherPath .toString();

How do I get the information from a meta tag with JavaScript?

The other answers should probably do the trick, but this one is simpler and does not require jQuery:

document.head.querySelector("[property~=video][content]").content;

The original question used an RDFa tag with a property="" attribute. For the normal HTML <meta name="" …> tags you could use something like:

document.querySelector('meta[name="description"]').content

How to override the properties of a CSS class using another CSS class

If you list the bakground-none class after the other classes, its properties will override those already set. There is no need to use !important here.

For example:

.red { background-color: red; }
.background-none { background: none; }

and

<a class="red background-none" href="#carousel">...</a>

The link will not have a red background. Please note that this only overrides properties that have a selector that is less or equally specific.

document.getElementById().value and document.getElementById().checked not working for IE

For non-grouped elements, name and id should be same. In this case you gave name as 'sp' and id as 'sp_100'. Don't do that, do it like this:

HTML:

<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp">

Javascript:

var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp').checked = true;

For more details

please visit : http://www.impressivewebs.com/avoiding-problems-with-javascript-getelementbyid-method-in-internet-explorer-7/

Authentication failed because remote party has closed the transport stream

I would advise against restricting the SecurityProtocol to TLS 1.1.

The recommended solution is to use

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls

Another option is add the following Registry key:

Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 
Value: SchUseStrongCrypto 

It is worth noting that .NET 4.6 will use the correct protocol by default and does not require either solution.

Can VS Code run on Android?

Running VS Code on Android is not possible, at least until Android support is implemented in Electron. This has been rejected by the Electron team in the past, see electron#562

Visual Studio Codespaces and GitHub Codespaces an upcoming services that enables running VS Code in a browser. Since everything runs in a browser, it seems likely that mobile OS' will be supported.

SQL Last 6 Months

Try this one

where datediff(month, datetime_column, getdate()) <= 6

To exclude or filter out future dates

where datediff(month, datetime_column, getdate()) between 0 and 6


This part datediff(month, datetime_column, getdate()) will get the month difference in number of current date and Datetime_Column and will return Rows like:

Result
1
2
3
4
5
6
7
8
9
10

This is Our final condition to get last 6 months data

where result <= 6

Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
    public virtual Ship Ship { get; set; }
    public virtual GamePlayer GamePlayer { get; set; }     
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

How do I select an element with its name attribute in jQuery?

$('[name="ElementNameHere"]').doStuff();

jQuery supports CSS3 style selectors, plus some more.

See more

How can I reorder a list?

newList = [oldList[3]]
newList.extend(oldList[:3])
newList.extend(oldList[4:])

How to trim white space from all elements in array?

I know this is a really old post, but since Java 1.8 there is a nicer way to trim every String in an array.

Java 8 Lamda Expression solution:

List<String> temp = new ArrayList<>(Arrays.asList(yourArray));
temp.forEach(e -> {temp.set((temp.indexOf(e), e.trim()});
yourArray = temp.toArray(new String[temp.size()]);

with this solution you don't have to create a new Array.
Like in Óscar López's solution

rails 3 validation on uniqueness on multiple attributes

Multiple Scope Parameters:

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

This should answer Greg's question.

C++ queue - simple example

std::queue<myclass*> my_queue; will do the job.

See here for more information on this container.

How to capitalize the first letter of word in a string using Java?

if you only want to capitalize the first letter then the below code can be used

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

How to write to a file in Scala?

Giving another answer, because my edits of other answers where rejected.

This is the most concise and simple answer (similar to Garret Hall's)

File("filename").writeAll("hello world")

This is similar to Jus12, but without the verbosity and with correct code style

def using[A <: {def close(): Unit}, B](resource: A)(f: A => B): B =
  try f(resource) finally resource.close()

def writeToFile(path: String, data: String): Unit = 
  using(new FileWriter(path))(_.write(data))

def appendToFile(path: String, data: String): Unit =
  using(new PrintWriter(new FileWriter(path, true)))(_.println(data))

Note you do NOT need the curly braces for try finally, nor lambdas, and note usage of placeholder syntax. Also note better naming.

Which is the best IDE for Python For Windows

Python is dynamic language so the IDE can do only so much in terms of code intelligence and syntax checking but I personally recommend Komode IDE, it's pretty slick on OS/X and Windows. I've experienced high cpu use with Linux but not sure if it's caused by my VirtualBox environment.

You can also try Eclipse with PyDev plugin. It's heavier so performance might become a problem though.

Get each line from textarea

For a <br> on each line, use

<textarea wrap="physical"></textarea>

You will get \ns in the value of the textarea. Then, use the nl2br() function to create <br>s, or you can explode() it for <br> or \n.

Hope this helps

Remove characters from a string

Another method that no one has talked about so far is the substr method to produce strings out of another string...this is useful if your string has defined length and the characters your removing are on either end of the string...or within some "static dimension" of the string.

Regex to match string containing two names in any order

Try:

james.*jack

If you want both at the same time, then or them:

james.*jack|jack.*james

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

WebSockets:

  • Ratified IETF standard (6455) with support across all modern browsers and even legacy browsers using web-socket-js polyfill.

  • Uses HTTP compatible handshake and default ports making it much easier to use with existing firewall, proxy and web server infrastructure.

  • Much simpler browser API. Basically one constructor with a couple of callbacks.

  • Client/browser to server only.

  • Only supports reliable, in-order transport because it is built On TCP. This means packet drops can delay all subsequent packets.

WebRTC:

  • Just beginning to be supported by Chrome and Firefox. MS has proposed an incompatible variant. The DataChannel component is not yet compatible between Firefox and Chrome.

  • WebRTC is browser to browser in ideal circumstances but even then almost always requires a signaling server to setup the connections. The most common signaling server solutions right now use WebSockets.

  • Transport layer is configurable with application able to choose if connection is in-order and/or reliable.

  • Complex and multilayered browser API. There are JS libs to provide a simpler API but these are young and rapidly changing (just like WebRTC itself).

How to access single elements in a table in R

That is so basic that I am wondering what book you are using to study? Try

data[1, "V1"]  # row first, quoted column name second, and case does matter

Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.

I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html

SQL Order By Count

Below gives me opposite of what you have. (Notice Group column)

SELECT
    *
FROM
    myTable
GROUP BY
    Group_value,
    ID
ORDER BY
    count(Group_value)

Let me know if this is fine with you...

I am trying to get what you want too...

How to launch jQuery Fancybox on page load?

Or use this in the JS file after your fancybox is set up:

$('#link_id').trigger('click');

I believe Fancybox 1.2.1 will use default options otherwise from my testing when I needed to do this.

What is the most robust way to force a UIView to redraw?

The guaranteed, rock solid way to force a UIView to re-render is [myView setNeedsDisplay]. If you're having trouble with that, you're likely running into one of these issues:

  • You're calling it before you actually have the data, or your -drawRect: is over-caching something.

  • You're expecting the view to draw at the moment you call this method. There is intentionally no way to demand "draw right now this very second" using the Cocoa drawing system. That would disrupt the entire view compositing system, trash performance and likely create all kinds of artifacting. There are only ways to say "this needs to be drawn in the next draw cycle."

If what you need is "some logic, draw, some more logic," then you need to put the "some more logic" in a separate method and invoke it using -performSelector:withObject:afterDelay: with a delay of 0. That will put "some more logic" after the next draw cycle. See this question for an example of that kind of code, and a case where it might be needed (though it's usually best to look for other solutions if possible since it complicates the code).

If you don't think things are getting drawn, put a breakpoint in -drawRect: and see when you're getting called. If you're calling -setNeedsDisplay, but -drawRect: isn't getting called in the next event loop, then dig into your view hierarchy and make sure you're not trying to outsmart is somewhere. Over-cleverness is the #1 cause of bad drawing in my experience. When you think you know best how to trick the system into doing what you want, you usually get it doing exactly what you don't want.

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Regular expression: find spaces (tabs/space) but not newlines

As @Eiríkr Útlendi noted, the accepted solution only considers two white space characters: the horizontal tab (U+0009), and a breaking space (U+0020). It does not consider other whitespace characters such as non-breaking spaces (which happen to be in the text I am trying to deal with). A more complete whitespace character listing is included on Wikipedia and also referenced in the linked Perl answer. A simple C# solution that accounts for these other characters can be built using character class subtraction

[\s-[\r\n]]

or, including Eiríkr Útlendi's solution, you get

[\s\u3000-[\r\n]]

How to provide password to a command that prompts for one in bash?

Programs that prompt for passwords usually set the tty into "raw" mode, and read input directly from the tty. If you spawn the subprocess in a pty you can make that work. That is what Expect does...

Core dump file is not generated

Make sure your current directory (at the time of crash -- server may change directories) is writable. If the server calls setuid, the directory has to be writable by that user.

Also check /proc/sys/kernel/core_pattern. That may redirect core dumps to another directory, and that directory must be writable. More info here.

Convert laravel object to array

this worked for me in laravel 5.4

$partnerProfileIds = DB::table('partner_profile_extras')->get()->pluck('partner_profile_id');
$partnerProfileIdsArray = $partnerProfileIds->all();

output

array:4 [?
  0 => "8219c678-2d3e-11e8-a4a3-648099380678"
  1 => "28459dcb-2d3f-11e8-a4a3-648099380678"
  2 => "d5190f8e-2c31-11e8-8802-648099380678"
  3 => "6d2845b6-2d3e-11e8-a4a3-648099380678"
]

https://laravel.com/docs/5.4/collections#method-all

How to increase the max upload file size in ASP.NET?

I have a blog post on how to increase the file size for asp upload control.

From the post:

By default, the FileUpload control allows a maximum of 4MB file to be uploaded and the execution timeout is 110 seconds. These properties can be changed from within the web.config file’s httpRuntime section. The maxRequestLength property determines the maximum file size that can be uploaded. The executionTimeout property determines the maximum time for execution.

how to get the 30 days before date from Todays Date

In MS SQL Server, it is:

SELECT getdate() - 30;

How to find locked rows in Oracle

you can find the locked tables in oralce by querying with following query

    select
   c.owner,
   c.object_name,
   c.object_type,
   b.sid,
   b.serial#,
   b.status,
   b.osuser,
   b.machine
from
   v$locked_object a ,
   v$session b,
   dba_objects c
where
   b.sid = a.session_id
and
   a.object_id = c.object_id;

SonarQube not picking up Unit Test Coverage

I was facing the same problem and the challenge in my case was to configure Jacoco correctly and to configure the right parameters for Sonar. I will briefly explain, how I finally got SonarQube to display the test results and test coverage correctly.

In your project you need the Jacoco plugin in your pom or parent pom (you already got this). Moreover, you need the maven-surefire-plugin, which is used to display test results. All test reports are automatically generated when you run the maven build. The tricky part is to find the right parameters for Sonar. Not all parameters seem to work with regular expressions and you have to use a comma separated list for those (documentation is not really good in my opinion). Here is the list of parameters I have used (I used them from Bamboo, you might omit the "-D" if you use a sonar.properties file):

-Dsonar.branch.target=master (in newer version of SQ I had to remove this, so that master branch is analyzed correctly; I used auto branch checkbox in bamboo instead)
-Dsonar.working.directory=./target/sonar
-Dsonar.java.binaries=**/target/classes
-Dsonar.sources=./service-a/src,./service-b/src,./service-c/src,[..]
-Dsonar.exclusions=**/data/dto/**
-Dsonar.tests=.
-Dsonar.test.inclusions=**/*Test.java [-> all your tests have to end with "Test"]
-Dsonar.junit.reportPaths=./service-a/target/surefire-reports,./service-b/target/surefire-reports,
./service-c/target/surefire-reports,[..]
-Dsonar.jacoco.reportPaths=./service-a/target/jacoco.exec,./service-b/target/jacoco.exec,
./service-c/target/jacoco.exec,[..]
-Dsonar.projectVersion=${bamboo.buildNumber}
-Dsonar.coverage.exclusions=**/src/test/**,**/common/**
-Dsonar.cpd.exclusions=**/*Dto.java,**/*Entity.java,**/common/**

If you are using Lombok in your project, than you also need a lombok.config file to get the correct code coverage. The lombok.config file is located in the root directory of your project with the following content:

config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = true

Remove Item in Dictionary based on Value

In my case I use this

  var key=dict.FirstOrDefault(m => m.Value == s).Key;
            dict.Remove(key);

Android Eclipse - Could not find *.apk

remove -- R.java -- Clean the project and run again.. this worked for me ..

Hadoop cluster setup - java.net.ConnectException: Connection refused

For me it was that I could not cluster my zookeeper.

hdfs haadmin -getServiceState 1
active

hdfs haadmin -getServiceState 2
active

My hadoop-hdfs-zkfc-[hostname].log showed:

2017-04-14 11:46:55,351 WARN org.apache.hadoop.ha.HealthMonitor: Transport-level exception trying to monitor health of NameNode at HOST/192.168.1.55:9000: java.net.ConnectException: Connection refused Call From HOST/192.168.1.55 to HOST:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused

solution:

hdfs-site.xml
  <property>
    <name>dfs.namenode.rpc-bind-host</name>
      <value>0.0.0.0</value>
  </property>

before

netstat -plunt

tcp        0      0 192.168.1.55:9000        0.0.0.0:*               LISTEN      13133/java

nmap localhost -p 9000

Starting Nmap 6.40 ( http://nmap.org ) at 2017-04-14 12:15 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000047s latency).
Other addresses for localhost (not scanned): 127.0.0.1
PORT     STATE  SERVICE
9000/tcp closed cslistener

after

netstat -plunt
tcp        0      0 0.0.0.0:9000            0.0.0.0:*               LISTEN      14372/java

nmap localhost -p 9000

Starting Nmap 6.40 ( http://nmap.org ) at 2017-04-14 12:28 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000039s latency).
Other addresses for localhost (not scanned): 127.0.0.1
PORT     STATE SERVICE
9000/tcp open  cslistener

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

How to set Meld as git mergetool

For windows add the path for meld is like below:

 git config --global mergetool.meld.path C:\\Meld_run\\Meld.exe

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

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

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

enter image description here

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

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

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

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

it may caused by Property which is not populated by model.. instead it is populated by Controller.. which may cause this error.. solution to this is assign the property before applying ModelState validation. and this second Assumption is . you may have already have Data in your Database and trying to update it it but now fetching it.

How to use Javascript to read local text file and read line by line?

Without jQuery:

document.getElementById('file').onchange = function(){

  var file = this.files[0];

  var reader = new FileReader();
  reader.onload = function(progressEvent){
    // Entire file
    console.log(this.result);

    // By lines
    var lines = this.result.split('\n');
    for(var line = 0; line < lines.length; line++){
      console.log(lines[line]);
    }
  };
  reader.readAsText(file);
};

HTML:

<input type="file" name="file" id="file">

Remember to put your javascript code after the file field is rendered.

@RequestParam vs @PathVariable

@RequestParam annotation used for accessing the query parameter values from the request. Look at the following request URL:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20

In the above URL request, the values for param1 and param2 can be accessed as below:

public String getDetails(
    @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
...
}

The following are the list of parameters supported by the @RequestParam annotation:

  • defaultValue – This is the default value as a fallback mechanism if request is not having the value or it is empty.
  • name – Name of the parameter to bind
  • required – Whether the parameter is mandatory or not. If it is true, failing to send that parameter will fail.
  • value – This is an alias for the name attribute

@PathVariable

@PathVariable identifies the pattern that is used in the URI for the incoming request. Let’s look at the below request URL:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20

The above URL request can be written in your Spring MVC as below:

@RequestMapping("/hello/{id}")    public String getDetails(@PathVariable(value="id") String id,
    @RequestParam(value="param1", required=true) String param1,
    @RequestParam(value="param2", required=false) String param2){
.......
}

The @PathVariable annotation has only one attribute value for binding the request URI template. It is allowed to use the multiple @PathVariable annotation in the single method. But, ensure that no more than one method has the same pattern.

Also there is one more interesting annotation: @MatrixVariable

http://localhost:8080/spring_3_2/matrixvars/stocks;BT.A=276.70,+10.40,+3.91;AZN=236.00,+103.00,+3.29;SBRY=375.50,+7.60,+2.07

And the Controller method for it

 @RequestMapping(value = "/{stocks}", method = RequestMethod.GET)
  public String showPortfolioValues(@MatrixVariable Map<String, List<String>> matrixVars, Model model) {

    logger.info("Storing {} Values which are: {}", new Object[] { matrixVars.size(), matrixVars });

    List<List<String>> outlist = map2List(matrixVars);
    model.addAttribute("stocks", outlist);

    return "stocks";
  }

But you must enable:

<mvc:annotation-driven enableMatrixVariables="true" >

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

A lot of the above answers are correct. However, there seems to be more than one possible error when dealing with this.

The one I had was a capitalization issue with my App ID. My App ID for some reason wasn't capitalized but my app was. Once I recreated the App ID with correct capitalization, it all worked smoothly. Hope this helps. Frustrating as hell though.

P.S. if it still doesn't work, try editing the Code Signing Identity Field manually with "edit". Change the second line with the name of the correct provisioning profile name.

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Suppress/ print without b' prefix for bytes in Python 3

I am a little late but for Python 3.9.1 this worked for me and removed the -b prefix:

print(outputCode.decode())

An efficient way to Base64 encode a byte array?

Base64 is a way to represent bytes in a textual form (as a string). So there is no such thing as a Base64 encoded byte[]. You'd have a base64 encoded string, which you could decode back to a byte[].

However, if you want to end up with a byte array, you could take the base64 encoded string and convert it to a byte array, like:

string base64String = Convert.ToBase64String(bytes);
byte[] stringBytes = Encoding.ASCII.GetBytes(base64String);

This, however, makes no sense because the best way to represent a byte[] as a byte[], is the byte[] itself :)

Import Excel Spreadsheet Data to an EXISTING sql table?

You can copy-paste data from en excel-sheet to an SQL-table by doing so:

  • Select the data in Excel and press Ctrl + C
  • In SQL Server Management Studio right click the table and choose Edit Top 200 Rows
  • Scroll to the bottom and select the entire empty row by clicking on the row header
  • Paste the data by pressing Ctrl + V

Note: Often tables have a first column which is an ID-column with an auto generated/incremented ID. When you paste your data it will start inserting the leftmost selected column in Excel into the leftmost column in SSMS thus inserting data into the ID-column. To avoid that keep an empty column at the leftmost part of your selection in order to skip that column in SSMS. That will result in SSMS inserting the default data which is the auto generated ID.

Furthermore you can skip other columns by having empty columns at the same ordinal positions in the Excel sheet selection as those columns to be skipped. That will make SSMS insert the default value (or NULL where no default value is specified).

How to emulate GPS location in the Android Emulator?

For Android Studio users:

run the emulator,

Then, go to Tools -> Android ->Android device monitor

open the Emulator Control Tab, and use the location controls group.

What's the difference between 'r+' and 'a+' when open file in python?

One difference is for r+ if the files does not exist, it'll not be created and open fails. But in case of a+ the file will be created if it does not exist.

How to open spss data files in excel?

In order to download that driver you must have a license to SPSS. For those who do not, there is an open source tool that is very much like SPSS and will allow you to import SAV files and export them to CSV.

Here's the software

And here are the steps to export the data.

Convert a RGB Color Value to a Hexadecimal String

This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.

This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.

public class HexColor
{

  public static void main (String[] args)
  {
   JSlider sRed = new JSlider(0,255,1);
   JSlider sGreen = new JSlider(0,255,1);
   JSlider sBlue = new JSlider(0,255,1);
   JLabel hexCode = new JLabel();
   JPanel myPanel = new JPanel();
   GridBagLayout layout = new GridBagLayout();
   JFrame frame = new JFrame();

   //set frame to organize components using GridBagLayout 
   frame.setLayout(layout);

   //create gray filled rectangle 
   myPanel.paintComponent();
   myPanel.setBackground(Color.GRAY);

   //In practice this code is replicated and applied to sGreen and sBlue. 
   //For the sake of brevity I only show sRed in this post.
   sRed.addChangeListener(
         new ChangeListener()
         {
             @Override
             public void stateChanged(ChangeEvent e){
                 myPanel.setBackground(changeColor());
                 myPanel.repaint();
                 hexCode.setText(toHex());
         }
         }
     );
   //add each component to JFrame
   frame.add(myPanel);
   frame.add(sRed);
   frame.add(sGreen);
   frame.add(sBlue);
   frame.add(hexCode);
} //end of main

  //creates JPanel filled rectangle
  protected void paintComponent(Graphics g)
  {
      super.paintComponent(g);
      g.drawRect(360, 300, 10, 10);
      g.fillRect(360, 300, 10, 10);
  }

  //changes the display color in JPanel
  private Color changeColor()
  {
    int r = sRed.getValue();
    int b = sBlue.getValue();
    int g = sGreen.getValue();
    Color c;
    return  c = new Color(r,g,b);
  }

  //Displays hex representation of displayed color
  private String toHex()
  {
      Integer r = sRed.getValue();
      Integer g = sGreen.getValue();
      Integer b = sBlue.getValue();
      Color hC;
      hC = new Color(r,g,b);
      String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
      while(hex.length() < 6){
          hex = "0" + hex;
      }
      hex = "Hex Code: #" + hex;
      return hex;
  }
}

A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

Jest spyOn function called

In your test code your are trying to pass App to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:

1) Where the click handler calls a function passed as a prop, e.g.

class App extends Component {

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.props.someCallback();
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now pass in a spy function as a prop to the component, and assert that it is called:

describe('my sweet test', () => {
 it('clicks it', () => {
    const spy = jest.fn();
    const app = shallow(<App someCallback={spy} />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

2) Where the click handler sets some state on the component, e.g.

class App extends Component {
  state = {
      aProperty: 'first'
  }

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.setState({
          aProperty: 'second'
      });
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now make assertions about the state of the component, i.e.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(app.state('aProperty')).toEqual('second');
 })
})

Counting DISTINCT over multiple columns

I had a similar question but the query I had was a sub-query with the comparison data in the main query. something like:

Select code, id, title, name 
(select count(distinct col1) from mytable where code = a.code and length(title) >0)
from mytable a
group by code, id, title, name
--needs distinct over col2 as well as col1

ignoring the complexities of this, I realized I couldn't get the value of a.code into the subquery with the double sub query described in the original question

Select count(1) from (select distinct col1, col2 from mytable where code = a.code...)
--this doesn't work because the sub-query doesn't know what "a" is

So eventually I figured out I could cheat, and combine the columns:

Select count(distinct(col1 || col2)) from mytable where code = a.code...

This is what ended up working

Update a submodule to the latest commit

None of the above answers worked for me.

This was the solution, from the parent directory run:

git submodule update --init;
cd submodule-directory;
git pull;
cd ..;
git add submodule-directory;

now you can git commit and git push

Include PHP inside JavaScript (.js) files

7 years later update: This is terrible advice. Please don't do this.

If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.

<script type="text/javascript">
    phpVars = new Array();
    <?php foreach($vars as $var) {
        echo 'phpVars.push("' . $var . '");';
    };
    ?>
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>

If you're trying to call functions, then you can do this like this

<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
    functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
    functionTwo(<?php echo $moreVars; ?>, <?php echo $evenMoreVars; ?>);
</script>

setTimeout / clearTimeout problems

That's because timer is a local variable to your function.

Try creating it outside of the function.

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

I would have put this in a comment on the accepted answer, since that's where it belongs, but I can't. So, just in case anyone gets unreliable results, this could be why.

Be careful of the accepted answer, it fails if the time_point is before the epoch.

This line of code:

std::size_t fractional_seconds = ms.count() % 1000;

will yield unexpected values if ms.count() is negative (since size_t is not meant to hold negative values).

Declaring variables in Excel Cells

The lingo in excel is different, you don't "declare variables", you "name" cells or arrays.

A good overview of how you do that is below: http://office.microsoft.com/en-001/excel-help/define-and-use-names-in-formulas-HA010342417.aspx

What is the difference between YAML and JSON?

This question is 6 years old, but strangely, none of the answers really addresses all four points (speed, memory, expressiveness, portability).

Speed

Obviously this is implementation-dependent, but because JSON is so widely used, and so easy to implement, it has tended to receive greater native support, and hence speed. Considering that YAML does everything that JSON does, plus a truckload more, it's likely that of any comparable implementations of both, the JSON one will be quicker.

However, given that a YAML file can be slightly smaller than its JSON counterpart (due to fewer " and , characters), it's possible that a highly optimised YAML parser might be quicker in exceptional circumstances.

Memory

Basically the same argument applies. It's hard to see why a YAML parser would ever be more memory efficient than a JSON parser, if they're representing the same data structure.

Expressiveness

As noted by others, Python programmers tend towards preferring YAML, JavaScript programmers towards JSON. I'll make these observations:

  • It's easy to memorise the entire syntax of JSON, and hence be very confident about understanding the meaning of any JSON file. YAML is not truly understandable by any human. The number of subtleties and edge cases is extreme.
  • Because few parsers implement the entire spec, it's even harder to be certain about the meaning of a given expression in a given context.
  • The lack of comments in JSON is, in practice, a real pain.

Portability

It's hard to imagine a modern language without a JSON library. It's also hard to imagine a JSON parser implementing anything less than the full spec. YAML has widespread support, but is less ubiquitous than JSON, and each parser implements a different subset. Hence YAML files are less interoperable than you might think.

Summary

JSON is the winner for performance (if relevant) and interoperability. YAML is better for human-maintained files. HJSON is a decent compromise although with much reduced portability. JSON5 is a more reasonable compromise, with well-defined syntax.

PIG how to count a number of rows in alias

Arnon Rotem-Gal-Oz already answered this question a while ago, but I thought some may like this slightly more concise version.

LOGS = LOAD 'log';
LOG_COUNT = FOREACH (GROUP LOGS ALL) GENERATE COUNT(LOGS);

How does one represent the empty char?

To represent the fact that the value is not present you have two choices:

1) If the whole char range is meaningful and you cannot reserve any value, then use char* instead of char:

char** c = new char*[N];
c[0] = NULL; // no character
*c[1] = ' '; // ordinary character
*c[2] = 'a'; // ordinary character
*c[3] = '\0' // zero-code character

Then you'll have c[i] == NULL for when character is not present and otherwise *c[i] for ordinary characters.

2) If you don't need some values representable in char then reserve one for indicating that value is not present, for example the '\0' character.

char* c = new char[N];
c[0] = '\0'; // no character
c[1] = ' '; // ordinary character
c[2] = 'a'; // ordinary character

Then you'll have c[i] == '\0' for when character is not present and ordinary characters otherwise.

How to add subject alernative name to ssl certs?

Although this question was more specifically about IP addresses in Subject Alt. Names, the commands are similar (using DNS entries for a host name and IP entries for IP addresses).

To quote myself:

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1

Note that you only need Java 7's keytool to use this command. Once you've prepared your keystore, it should work with previous versions of Java.

(The rest of this answer also mentions how to do this with OpenSSL, but it doesn't seem to be what you're using.)

How to load GIF image in Swift?

Simple extension for local gifs. Gets all the images from the gif and adds it to the imageView animationImages.

extension UIImageView {
    static func fromGif(frame: CGRect, resourceName: String) -> UIImageView? {
        guard let path = Bundle.main.path(forResource: resourceName, ofType: "gif") else {
            print("Gif does not exist at that path")
            return nil
        }
        let url = URL(fileURLWithPath: path)
        guard let gifData = try? Data(contentsOf: url),
            let source =  CGImageSourceCreateWithData(gifData as CFData, nil) else { return nil }
        var images = [UIImage]()
        let imageCount = CGImageSourceGetCount(source)
        for i in 0 ..< imageCount {
            if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
                images.append(UIImage(cgImage: image))
            }
        }
        let gifImageView = UIImageView(frame: frame)
        gifImageView.animationImages = images
        return gifImageView
    }
}

To Use:

 guard let confettiImageView = UIImageView.fromGif(frame: view.frame, resourceName: "confetti") else { return }
 view.addSubview(confettiImageView)
 confettiImageView.startAnimating()

Repeat and duration customizations using UIImageView APIs.

confettiImageView.animationDuration = 3
confettiImageView.animationRepeatCount = 1

When you are done animating the gif and want to release the memory.

confettiImageView.animationImages = nil

Bash or KornShell (ksh)?

Bash.

The various UNIX and Linux implementations have various different source level implementations of ksh, some of which are real ksh, some of which are pdksh implementations and some of which are just symlinks to some other shell that has a "ksh" personality. This can lead to weird differences in execution behavior.

At least with bash you can be sure that it's a single code base, and all you need worry about is what (usually minimum) version of bash is installed. Having done a lot of scripting on pretty much every modern (and not-so-modern) UNIX, programming to bash is more reliably consistent in my experience.

How to send email from MySQL 5.1

I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives:

  1. Have application logic detect the need to send an e-mail and send it.
  2. Have a MySQL trigger populate a table that queues up the e-mails to be sent and have a process monitor that table and send the e-mails.

How to edit log message already committed in Subversion?

If your repository enables setting revision properties via the pre-revprop-change hook you can change log messages much easier.

svn propedit --revprop -r 1234 svn:log url://to/repository

Or in TortoiseSVN, AnkhSVN and probably many other subversion clients by right clicking on a log entry and then 'change log message'.

conflicting types error when compiling c program using gcc

You have to declare your functions before main()

(or declare the function prototypes before main())

As it is, the compiler sees my_print (my_string); in main() as a function declaration.

Move your functions above main() in the file, or put:

void my_print (char *);
void my_print2 (char *);

Above main() in the file.

Reading/Writing a MS Word file in PHP

You can use Antiword, it is a free MS Word reader for Linux and most popular OS.

$document_file = 'c:\file.doc';
$text_from_doc = shell_exec('/usr/local/bin/antiword '.$document_file);

Check if String / Record exists in DataTable

I think that if your "item_manuf_id" is the primary key of the DataTable you could use the Find method ...

string s = "stringValue";
DataRow foundRow = dtPs.Rows.Find(s);
if(foundRow != null) {
 //You have it ...
 }

How to create table using select query in SQL Server?

select <column list> into <table name> from <source> where <whereclause>

How can I replace newline or \r\n with <br/>?

If you are using nl2br, all occurrences of \n and \r will be replaced by <br>. But if (I don’t know how it is) you still get new lines you can use

str_replace("\r","",$description);
str_replace("\n","",$description);

to replace unnecessary new lines by an empty string.

How to call a JavaScript function within an HTML body

Try wrapping the createtable(); statement in a <script> tag:

<table>
        <tr>
            <th>Balance</th>
            <th>Fee</th>

        </tr>
        <script>createtable();</script>
</table>

I would avoid using document.write() and use the DOM if I were you though.

How can I cast int to enum?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace SamplePrograme
{
    public class Program
    {
        public enum Suit : int
        {
            Spades = 0,
            Hearts = 1,
            Clubs = 2,
            Diamonds = 3
        }

        public static void Main(string[] args)
        {
            //from string
            Console.WriteLine((Suit) Enum.Parse(typeof(Suit), "Clubs"));

            //from int
            Console.WriteLine((Suit)1);

            //From number you can also
            Console.WriteLine((Suit)Enum.ToObject(typeof(Suit) ,1));
        }
    }
}

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

How do you create a dictionary in Java?

You'll want a Map<String, String>. Classes that implement the Map interface include (but are not limited to):

Each is designed/optimized for certain situations (go to their respective docs for more info). HashMap is probably the most common; the go-to default.

For example (using a HashMap):

Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
type of animal

CSS: Position loading indicator in the center of the screen

This is what I've done for Angular 4:

<style type="text/css">  
  .centered {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transform: -webkit-translate(-50%, -50%);
    transform: -moz-translate(-50%, -50%);
    transform: -ms-translate(-50%, -50%);
    color:darkred;
  }
</style>

</head>

<body>
  <app-root>
        <div class="centered">
          <h1>Loading...</h1>
        </div>
  </app-root>
</body>

Maven: Failed to read artifact descriptor

I had the same problem for a while and despite doing mvn -U clean install the problem was not getting solved!

I finally solved the problem by deleting the whole .m2 folder and then restarted my IDE and the problem was gone!

So sometimes the problem would rise because of some incompatibilities or problems in your local maven repository.

How to import data from one sheet to another

Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.

NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)

Here is a link with the appropriate formulas.

The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))

  • IF(A2="","", means if A2 is blank, return a blank value
  • INDEX(Sheet1!B:B, is saying INDEX B:B where B:B is the data you want to return. IE the name column.
  • Match(A2, is saying to Match A2 which is the ID you want to return the Name for.
  • Sheet1!A:A, is saying you want to match A2 to the ID column in the previous sheet
  • ,0)) is specifying you want an exact value. 0 means return an exact match to A2, -1 means return smallest value greater than or equal to A2, 1 means return the largest value that is less than or equal to A2. Keep in mind -1 and 1 have to be sorted.

More information on the Index/Match formula

Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.

I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.

Good luck! Hope this helps.

brew install mysql on macOS

The "Base-Path" for Mysql is stored in /etc/my.cnf which is not updated when you do brew upgrade. Just open it and change the basedir value

For example, change this:

[mysqld]
basedir=/Users/3st/homebrew/Cellar/mysql/5.6.13

to point to the new version:

[mysqld]
basedir=/Users/3st/homebrew/Cellar/mysql/5.6.19

Restart mysql with:

mysql.server start

Oracle's default date format is YYYY-MM-DD, WHY?

A DATE value per the SQL standard is YYYY-MM-DD. So even though Oracle stores the time information, my guess is that they're displaying the value in a way that is compatible with the SQL standard. In the standard, there is the TIMESTAMP data type that includes date and time info.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

Alternative ASP.NET MVC 5 Fix:

In my case the error was occurring during the request. Best approach in my scenario is modifying the actual JsonValueProviderFactory which applies the fix to the global project and can be done by editing the global.cs file as such.

JsonValueProviderConfig.Config(ValueProviderFactories.Factories);

add a web.config entry:

<add key="aspnet:MaxJsonLength" value="20971520" />

and then create the two following classes

public class JsonValueProviderConfig
{
    public static void Config(ValueProviderFactoryCollection factories)
    {
        var jsonProviderFactory = factories.OfType<JsonValueProviderFactory>().Single();
        factories.Remove(jsonProviderFactory);
        factories.Add(new CustomJsonValueProviderFactory());
    }
}

This is basically an exact copy of the default implementation found in System.Web.Mvc but with the addition of a configurable web.config appsetting value aspnet:MaxJsonLength.

public class CustomJsonValueProviderFactory : ValueProviderFactory
{

    /// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
    /// <returns>A JSON value-provider object for the specified controller context.</returns>
    /// <param name="controllerContext">The controller context.</param>
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");

        object deserializedObject = CustomJsonValueProviderFactory.GetDeserializedObject(controllerContext);
        if (deserializedObject == null)
            return null;

        Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        CustomJsonValueProviderFactory.AddToBackingStore(new CustomJsonValueProviderFactory.EntryLimitedDictionary(strs), string.Empty, deserializedObject);

        return new DictionaryValueProvider<object>(strs, CultureInfo.CurrentCulture);
    }

    private static object GetDeserializedObject(ControllerContext controllerContext)
    {
        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            return null;

        string fullStreamString = (new StreamReader(controllerContext.HttpContext.Request.InputStream)).ReadToEnd();
        if (string.IsNullOrEmpty(fullStreamString))
            return null;

        var serializer = new JavaScriptSerializer()
        {
            MaxJsonLength = CustomJsonValueProviderFactory.GetMaxJsonLength()
        };
        return serializer.DeserializeObject(fullStreamString);
    }

    private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)
    {
        IDictionary<string, object> strs = value as IDictionary<string, object>;
        if (strs != null)
        {
            foreach (KeyValuePair<string, object> keyValuePair in strs)
                CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);

            return;
        }

        IList lists = value as IList;
        if (lists == null)
        {
            backingStore.Add(prefix, value);
            return;
        }

        for (int i = 0; i < lists.Count; i++)
        {
            CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakeArrayKey(prefix, i), lists[i]);
        }
    }

    private class EntryLimitedDictionary
    {
        private static int _maximumDepth;

        private readonly IDictionary<string, object> _innerDictionary;

        private int _itemCount;

        static EntryLimitedDictionary()
        {
            _maximumDepth = CustomJsonValueProviderFactory.GetMaximumDepth();
        }

        public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
        {
            this._innerDictionary = innerDictionary;
        }

        public void Add(string key, object value)
        {
            int num = this._itemCount + 1;
            this._itemCount = num;
            if (num > _maximumDepth)
            {
                throw new InvalidOperationException("The length of the string exceeds the value set on the maxJsonLength property.");
            }
            this._innerDictionary.Add(key, value);
        }
    }

    private static string MakeArrayKey(string prefix, int index)
    {
        return string.Concat(prefix, "[", index.ToString(CultureInfo.InvariantCulture), "]");
    }

    private static string MakePropertyKey(string prefix, string propertyName)
    {
        if (string.IsNullOrEmpty(prefix))
        {
            return propertyName;
        }
        return string.Concat(prefix, ".", propertyName);
    }

    private static int GetMaximumDepth()
    {
        int num;
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
            if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
            {
                return num;
            }
        }
        return 1000;
    }

    private static int GetMaxJsonLength()
    {
        int num;
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonLength");
            if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
            {
                return num;
            }
        }
        return 1000;
    }
}

SQL Server: Importing database from .mdf?

See: How to: Attach a Database File to SQL Server Express

Login to the database via sqlcmd:

sqlcmd -S Server\Instance

And then issue the commands:

USE [master]
GO
CREATE DATABASE [database_name] ON 
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\<database name>.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\<database name>.ldf' )
 FOR ATTACH ;
GO

MongoDB vs Firebase

Firebase provides some good features like real time change reflection , easy integration of authentication mechanism , and lots of other built-in features for rapid web development. Firebase, really makes Web development so simple that never exists. Firebase database is a fork of MongoDB.

What's the advantage of using Firebase over MongoDB?

You can take advantage of all built-in features of Firebase over MongoDB.

How to change text and background color?

Colors are bit-encoded. If You want to change the Text color in C++ language There are many ways. In the console, you can change the properties of output.click this icon of the console and go to properties and change color.

The second way is calling the system colors.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    //Changing Font Colors of the System

    system("Color 7C");
    cout << "\t\t\t ****CEB Electricity Bill Calculator****\t\t\t " << endl;
    cout << "\t\t\t  ***                MENU           ***\t\t\t  " <<endl;

    return 0;

}

What is the difference between bool and Boolean types in C#

No actual difference unless you get the type string. There when you use reflection or GetType() you get {Name = "Boolean" FullName = "System.Boolean"} for both.

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

ImportError: No module named mysql.connector using Python2

What worked for me was to download the .deb file directly and install it (dpkg -i mysql-connector-python_2.1.7-1ubuntu16.04_all.deb). Python downloads are located here (you will need to create a free MySQL login to download first). Make sure you choose the correct version, i.e. (python_2.1.7 vs. python-py3_2.1.7). Only the "Architecture Independent" version worked for me.

Iterate through a C array

It depends. If it's a dynamically allocated array, that is, you created it calling malloc, then as others suggest you must either save the size of the array/number of elements somewhere or have a sentinel (a struct with a special value, that will be the last one).

If it's a static array, you can sizeof it's size/the size of one element. For example:

int array[10], array_size;
...
array_size = sizeof(array)/sizeof(int);

Note that, unless it's global, this only works in the scope where you initialized the array, because if you past it to another function it gets decayed to a pointer.

Hope it helps.

Select all occurrences of selected word in VSCode

If you want to do one by one then this is what you can do:

  1. Select a word
  2. Press ctrl + d (in windows).

This will help to select words one by one.

Create autoincrement key in Java DB using NetBeans IDE

I couldn't get the accepted answer to work using the Netbeans IDE "Create Table" GUI, and I'm on Netbeans 8.2. To get it to working, create the id column with the following options e.g.

enter image description here

and then use 'New Entity Classes from Database' option to generate the entity for the table (I created a simple table called PERSON with an ID column created exactly as above and a NAME column which is simple varchar(255) column). These generated entities leave it to the user to add the auto generated id mechanism.

GENERATION.AUTO seems to try and use sequences which Derby doesn't seem to like (error stating failed to generate sequence/sequence does not exist), GENERATION.SEQUENCE therefore doesn't work either, GENERATION.IDENTITY doesn't work (get error stating ID is null), so that leaves GENERATION.TABLE.

Set your persistence unit's 'Table Generation Strategy' button to Create. This will create tables that don't exist in the DB when your jar is run (loaded?) i.e. the table your PU needs to create in order to store ID increments. In your entity replace the generated annotations above your id field with the following...

enter image description here

I also created a controller for my entity class using 'JPA Controller Classes from Entity Classes' option. I then create a simple main class to test the id was auto generated i.e.

enter image description here

The result is that the PERSON_ID_TABLE is generated correctly and my PERSON table has two PERSON entries in it with correct, auto generated ids.

How to install a plugin in Jenkins manually

Yes, you can. Download the plugin (*.hpi file) and put it in the following directory:

<jenkinsHome>/plugins/

Afterwards you will need to restart Jenkins.

What is dynamic programming?

I am also very much new to Dynamic Programming (a powerful algorithm for particular type of problems)

In most simple words, just think dynamic programming as a recursive approach with using the previous knowledge

Previous knowledge is what matters here the most, Keep track of the solution of the sub-problems you already have.

Consider this, most basic example for dp from Wikipedia

Finding the fibonacci sequence

function fib(n)   // naive implementation
    if n <=1 return n
    return fib(n - 1) + fib(n - 2)

Lets break down the function call with say n = 5

fib(5)
fib(4) + fib(3)
(fib(3) + fib(2)) + (fib(2) + fib(1))
((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))
(((fib(1) + fib(0)) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))

In particular, fib(2) was calculated three times from scratch. In larger examples, many more values of fib, or sub-problems, are recalculated, leading to an exponential time algorithm.

Now, lets try it by storing the value we already found out in a data-structure say a Map

var m := map(0 ? 0, 1 ? 1)
function fib(n)
    if key n is not in map m 
        m[n] := fib(n - 1) + fib(n - 2)
    return m[n]

Here we are saving the solution of sub-problems in the map, if we don't have it already. This technique of saving values which we already had calculated is termed as Memoization.

At last, For a problem, first try to find the states (possible sub-problems and try to think of the better recursion approach so that you can use the solution of previous sub-problem into further ones).

How to find third or n?? maximum salary from salary table?

NOTE: Please replace OFFSET 3 in Query with ANY Nth integer number

SELECT EmpName,EmpSalary
FROM SALARY
ORDER BY EmpSalary DESC
OFFSET 3 ROWS 
FETCH NEXT 1 ROWS ONLY

Description

FETCH NEXT 1 ROWS ONLY

return only 1 row

OFFSET 3 ROWS

exclude first 3 records Here you can you any integer number

HTTP URL Address Encoding in Java

I had the same problem. Solved this by unsing:

android.net.Uri.encode(urlString, ":/");

It encodes the string but skips ":" and "/".

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

Go to phpMyAdmin Directory of your Localhost Software Like Xampp, Mamp or others. Then change the host from localhost to 127.0.0.1 and change the port to 3307 . After that go to your data directory and delete all error log files except ibdata1 which is important file to hold your created database table link. Finaly restart mysql.I think your problem will be solved.

jQuery send HTML data through POST

I don't see why you shouldn't be able to send html content via a post.

if you encounter any issues, you could perhaps use some kind of encoding / decoding - but I don't see that you will.

Hibernate Auto Increment ID

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

and you leave it null (0) when persisting. (null if you use the Integer / Long wrappers)

In some cases the AUTO strategy is resolved to SEQUENCE rathen than to IDENTITY or TABLE, so you might want to manually set it to IDENTITY or TABLE (depending on the underlying database).

It seems SEQUENCE + specifying the sequence name worked for you.

How to set width of a div in percent in JavaScript?

document.getElementById('header').style.width = '50%';

If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.

Does hosts file exist on the iPhone? How to change it?

In case anybody else falls onto this page, you can also solve this by using the Ip address in the URL request instead of the domain:

NSURL *myURL = [NSURL URLWithString:@"http://10.0.0.2/mypage.php"];

Then you specify the Host manually:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
[request setAllHTTPHeaderFields:[NSDictionary dictionaryWithObjectAndKeys:@"myserver",@"Host"]];

As far as the server is concerned, it will behave the exact same way as if you had used http://myserver/mypage.php, except that the iPhone will not have to do a DNS lookup.

100% Public API.

What is w3wp.exe?

w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.

You can get more information on w3wp.exe here

http://www.processlibrary.com/en/directory/files/w3wp/25761/

Get the row(s) which have the max value in groups using groupby

You can sort the dataFrame by count and then remove duplicates. I think it's easier:

df.sort_values('count', ascending=False).drop_duplicates(['Sp','Mt'])

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

Try this -->

 new DzieckoAndOpiekun(
                         p.Imie,
                         p.Nazwisko,
                         p.Opiekun.Imie,
                         p.Opiekun.Nazwisko).ToList()

Java Calendar, getting current month value, clarification needed

Months in Java Calendar are 0-indexed. Calendar.JANUARY isn't a field so you shouldn't be passing it in to the get method.

When creating a service with sc.exe how to pass in context parameters?

I found a way to use sc.

sc config binPath= "\"c:\path with spaces in it\service_executable.exe\" "

In other words, use \ to escape any "'s you want to survive the transit into the registry.

How I can get web page's content and save it into the string variable

I've run into issues with Webclient.Downloadstring before. If you do, you can try this:

WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
    html = sr.ReadToEnd();
}

Transactions in .net

You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.

Error Code: 2013. Lost connection to MySQL server during query

Thanks!It's worked. But with the mysqldb updates the configure has became:

max_allowed_packet

net_write_timeout

net_read_timeout

mysql doc

How to change href attribute using JavaScript after opening the link in a new window?

for example try this :

<a href="http://www.google.com" id="myLink1">open link 1</a><br/> <a href="http://www.youtube.com" id="myLink2">open link 2</a>



    document.getElementById("myLink1").onclick = function() {
    window.open(
    "http://www.facebook.com"
        );
        return false;
      };

      document.getElementById("myLink2").onclick = function() {
    window.open(
    "http://www.yahoo.com"
        );
        return false;
      };

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

When to use the different log levels

An error is something that is wrong, plain wrong, no way around it, it needs to be fixed.

A warning is a sign of a pattern that might be wrong, but then also might not be.

Having said that, I cannot come up with a good example of a warning that isn't also an error. What I mean by that is that if you go to the trouble of logging a warning, you might as well fix the underlying issue.

However, things like "sql execution takes too long" might be a warning, while "sql execution deadlocks" is an error, so perhaps there's some cases after all.

Adding a 'share by email' link to website

Easiest: http://www.addthis.com/

Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

1.a. Add following in applicationContext-mvc.xml

xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc

  1. add jackson library

Change border color on <select> HTML form

Replacing the border-color with outline-color should work.

Adjusting and image Size to fit a div (bootstrap)

I had this same problem and stumbled upon the following simple solution. Just add a bit of padding to the image and it resizes itself to fit within the div.

<div class="col-sm-3">
  <img src="xxx.png" class="img-responsive" style="padding-top: 5px">
</div>

SSL InsecurePlatform error when using Requests package

if you just want to stopping insecure warning like:

/usr/lib/python3/dist-packages/urllib3/connectionpool.py:794: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html InsecureRequestWarning)

do:

requests.METHOD("https://www.google.com", verify=False)

verify=False

is the key, followings are not good at it:

requests.packages.urllib3.disable_warnings()

or

urllib3.disable_warnings()

but, you HAVE TO know, that might cause potential security risks.

Using AND/OR in if else PHP statement

You have 2 issues here.

  1. use == for comparison. You've used = which is for assignment.

  2. use && for "and" and || for "or". and and or will work but they are unconventional.

How to replace NA values in a table for selected columns

You can do:

x[, 1:2][is.na(x[, 1:2])] <- 0

or better (IMHO), use the variable names:

x[c("a", "b")][is.na(x[c("a", "b")])] <- 0

In both cases, 1:2 or c("a", "b") can be replaced by a pre-defined vector.

Shortcut for creating single item list in C#

var list = new List<string>(1) { "hello" };

Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially.

Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once.

Difference between r+ and w+ in fopen()

r = read mode only
r+ = read/write mode
w = write mode only
w+ = read/write mode, if the file already exists override it (empty it)

So yes, if the file already exists w+ will erase the file and give you an empty file.

How to Load Ajax in Wordpress

As per your request I have put this in an answer for you.

As Hieu Nguyen suggested in his answer, you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.

<script type="text/javascript">
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:

  • wp_ajax_(action): This is fired if the ajax call is made from inside the admin panel.
  • wp_ajax_nopriv_(action): This is fired if the ajax call is made from the front end of the website.

Everything else is described in the documentation linked above. Happy coding!

P.S. Here is an example that should work. (I have not tested)

Front end:

<script type="text/javascript">
    jQuery.ajax({
        url: ajaxurl,
        data: {
            action: 'my_action_name'
        },
        type: 'GET'
    });
</script>

Back end:

<?php
    function my_ajax_callback_function() {
        // Implement ajax function here
    }
    add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );    // If called from admin panel
    add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );    // If called from front end
?>

UPDATE Even though this is an old answer, it seems to keep getting thumbs up from people - which is great! I think this may be of use to some people.

WordPress has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:

var translation = {
    success: "Success!",
    failure: "Failure!",
    error: "Error!",
    ...
};

So this simply loads an object into the HTML head tag. This can be utilized in the following way:

Backend:

wp_localize_script( 'FrontEndAjax', 'ajax', array(
    'url' => admin_url( 'admin-ajax.php' )
) );

The advantage of this method is that it may be used in both themes AND plugins, as you are not hard-coding the ajax URL variable into the theme.

On the front end, the URL is now accessible via ajax.url, rather than simply ajaxurl in the previous examples.

Limit Get-ChildItem recursion depth

Use this to limit the depth to 2:

Get-ChildItem \*\*\*,\*\*,\*

The way it works is that it returns the children at each depth 2,1 and 0.


Explanation:

This command

Get-ChildItem \*\*\*

returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.

In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.

Can I run a 64-bit VMware image on a 32-bit machine?

The easiest way to check your workstation is to download the VMware Processor Check for 64-Bit Compatibility tool from the VMware website.

You can't run a 64-bit VM session on a 32-bit processor. However, you can run a 64-bit VM session if you have a 64-bit processor but have installed a 32-bit host OS and your processor supports the right extensions. The tool linked above will tell you if yours does.

What's the easiest way to escape HTML in Python?

If you wish to escape HTML in a URL:

This is probably NOT what the OP wanted (the question doesn't clearly indicate in which context the escaping is meant to be used), but Python's native library urllib has a method to escape HTML entities that need to be included in a URL safely.

The following is an example:

#!/usr/bin/python
from urllib import quote

x = '+<>^&'
print quote(x) # prints '%2B%3C%3E%5E%26'

Find docs here

How do I horizontally center an absolute positioned element inside a 100% width div?

In my experience, the best way is right:0;, left:0; and margin:0 auto. This way if the div is wide then you aren't hindered by the left: 50%; that will offset your div which results in adding negative margins etc.

DEMO http://jsfiddle.net/kevinPHPkevin/DeTJH/4/

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    margin:0 auto;
    right:0;
    left:0;
}

Default SQL Server Port

The default port 1433 is used when there is only one SQL Server named instance running on the computer.

When multiple SQL Server named instances are running, they run by default under a dynamic port (49152–65535). In this scenario, an application will connect to the SQL Server Browser service port (UDP 1434) to get the dynamic port and then connect to the dynamic port directly.

https://docs.microsoft.com/en-us/sql/sql-server/install/configure-the-windows-firewall-to-allow-sql-server-access

Change default text in input type="file"?

It is not possible. Otherwise you may need to use Silverlight or Flash upload control.

How do you convert an entire directory with ffmpeg?

If you have GNU parallel you could convert all .avi files below vid_dir to mp4 in parallel, using all except one of your CPU cores with

find vid_dir -type f -name '*.avi' -not -empty -print0 |
    parallel -0 -j -1 ffmpeg -loglevel fatal -i {} {.}.mp4

To convert from/to different formats, change '*.avi' or .mp4 as needed. GNU parallel is listed in most Linux distributions' repositories in a package which is usually called parallel.

Deleting rows with Python in a CSV file

You should have if row[2] != "0". Otherwise it's not checking to see if the string value is equal to 0.

Is there a regular expression to detect a valid regular expression?

/
^                                             # start of string
(                                             # first group start
  (?:
    (?:[^?+*{}()[\]\\|]+                      # literals and ^, $
     | \\.                                    # escaped characters
     | \[ (?: \^?\\. | \^[^\\] | [^\\^] )     # character classes
          (?: [^\]\\]+ | \\. )* \]
     | \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \)  # parenthesis, with recursive content
     | \(\? (?:R|[+-]?\d+) \)                 # recursive matching
     )
    (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )?   # quantifiers
  | \|                                        # alternative
  )*                                          # repeat content
)                                             # end first group
$                                             # end of string
/

This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.

Without whitespace and comments:

/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/

.NET does not support recursion directly. (The (?1) and (?R) constructs.) The recursion would have to be converted to counting balanced groups:

^                                         # start of string
(?:
  (?: [^?+*{}()[\]\\|]+                   # literals and ^, $
   | \\.                                  # escaped characters
   | \[ (?: \^?\\. | \^[^\\] | [^\\^] )   # character classes
        (?: [^\]\\]+ | \\. )* \]
   | \( (?:\?[:=!]
         | \?<[=!]
         | \?>
         | \?<[^\W\d]\w*>
         | \?'[^\W\d]\w*'
         )?                               # opening of group
     (?<N>)                               #   increment counter
   | \)                                   # closing of group
     (?<-N>)                              #   decrement counter
   )
  (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \|                                      # alternative
)*                                        # repeat content
$                                         # end of string
(?(N)(?!))                                # fail if counter is non-zero.

Compacted:

^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!))

From the comments:

Will this validate substitutions and translations?

It will validate just the regex part of substitutions and translations. s/<this part>/.../

It is not theoretically possible to match all valid regex grammars with a regex.

It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.

Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.

"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.

using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions

This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.

Regex itself "is not a regular language and hence cannot be parsed by regular expression..."

This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.

I see where you're matching []()/\. and other special regex characters. Where are you allowing non-special characters? It seems like this will match ^(?:[\.]+)$, but not ^abcdefg$. That's a valid regex.

[^?+*{}()[\]\\|] will match any single character, not part of any of the other constructs. This includes both literal (a - z), and certain special characters (^, $, .).

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Following Andrii Karaivanskyi's answer here's the Maven POM declaration:

<properties>
    ...
    <junit-jupiter.version>5.2.0</junit-jupiter.version>
    <junit-platform.version>1.2.0</junit-platform.version>
    ...
</properties>

<dependencies>
    ...
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit-jupiter.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <version>${junit-platform.version}</version>
        <scope>test</scope>
    </dependency>
    ...
</dependencies>

UPDATE

As per comment by Alexander Wessel you can use org.junit:junit-bom as described in his answer to question Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory.

What is the difference between "expose" and "publish" in Docker?

Basically, you have three options:

  1. Neither specify EXPOSE nor -p
  2. Only specify EXPOSE
  3. Specify EXPOSE and -p

1) If you specify neither EXPOSE nor -p, the service in the container will only be accessible from inside the container itself.

2) If you EXPOSE a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.

3) If you EXPOSE and -p a port, the service in the container is accessible from anywhere, even outside Docker.

The reason why both are separated is IMHO because:

  • choosing a host port depends on the host and hence does not belong to the Dockerfile (otherwise it would be depending on the host),
  • and often it's enough if a service in a container is accessible from other containers.

The documentation explicitly states:

The EXPOSE instruction exposes ports for use within links.

It also points you to how to link containers, which basically is the inter-container communication I talked about.

PS: If you do -p, but do not EXPOSE, Docker does an implicit EXPOSE. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p includes EXPOSE. That's why I didn't list it above as a fourth case.

How do I output coloured text to a Linux terminal?

I wrote a cross-platform library color_ostream for this, with the support of ANSI color, 256 color and true color, all you have to do is directly including it and changing cout to rd_cout like this.
| std | basic color | 256 color | true color | | :----: | :----: | :----: | :----: | | std::cout | color_ostream::rd_cout | color_ostream::rd256_cout | color_ostream::rdtrue_cout | | std::wcout | color_ostream::rd_wcout | color_ostream::rd256_wcout | color_ostream::rdtrue_wcout | | std::cerr | color_ostream::rd_cerr | color_ostream::rd256_cerr | color_ostream::rdtrue_cerr | | std::wcerr | color_ostream::rd_wcerr | color_ostream::rd256_wcerr | color_ostream::rdtrue_wcerr | | std::clog | color_ostream::rd_clog | color_ostream::rd256_clog | color_ostream::rdtrue_clog | | std::wclog | color_ostream::rd_wclog | color_ostream::rd256_wclog | color_ostream::rdtrue_wclog |
Here is an simple example:

//hello.cpp
#include "color_ostream.h"

using namespace color_ostream;

int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) {
    rd_wcout.imbue(std::locale(std::locale(),"",LC_CTYPE));
    rd_wcout << L"Hello world\n";
    rd_wcout << L"Hola Mundo\n";
    rd_wcout << L"Bonjour le monde\n";

    rd256_wcout << L"\n256 color" << std::endl;
    rd256_wcout << L"Hello world\n";
    rd256_wcout << L"Hola Mundo\n";
    rd256_wcout << L"Bonjour le monde\n";

    rdtrue_wcout << L"\ntrue color" << std::endl;
    rdtrue_wcout << L"Hello world\n";
    rdtrue_wcout << L"Hola Mundo\n";
    rdtrue_wcout << L"Bonjour le monde\n";
    return 0;
}

Find html label associated with a given input

If you're willing to use querySelector (and you can, even down to IE9 and sometimes IE8!), another method becomes viable.

If your form field has an ID, and you use the label's for attribute, this becomes pretty simple in modern JavaScript:

var form = document.querySelector('.sample-form');
var formFields = form.querySelectorAll('.form-field');

[].forEach.call(formFields, function (formField) {
    var inputId = formField.id;
    var label = form.querySelector('label[for=' + inputId + ']');
    console.log(label.textContent);
});

Some have noted about multiple labels; if they all use the same value for the for attribute, just use querySelectorAll instead of querySelector and loop through to get everything you need.

Returning anonymous type in C#

You can only use dynamic keyword,

   dynamic obj = GetAnonymousType();

   Console.WriteLine(obj.Name);
   Console.WriteLine(obj.LastName);
   Console.WriteLine(obj.Age); 


   public static dynamic GetAnonymousType()
   {
       return new { Name = "John", LastName = "Smith", Age=42};
   }

But with dynamic type keyword you will loose compile time safety, IDE IntelliSense etc...

SelectSingleNode returning null for known good xml node path using XPath

Well... I had the same issue and it was a headache. Since I didn't care much about the namespace or the xml schema, I just deleted this data from my xml and it solved all my issues. May not be the best answer? Probably, but if you don't want to deal with all of this and you ONLY care about the data (and won't be using the xml for some other task) deleting the namespace may solve your problems.

XmlDocument vinDoc = new XmlDocument();
string vinInfo = "your xml string";
vinDoc.LoadXml(vinInfo);

vinDoc.InnerXml = vinDoc.InnerXml.Replace("xmlns=\"http://tempuri.org\/\", "");

How to add http:// if it doesn't exist in the URL

The best answer for this would be something like this:

function addhttp($url, $scheme="http://" )
{
  return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}

The protocol flexible, so the same function can be used with ftp, https, etc.

Annotation @Transactional. How to rollback?

For me rollbackFor was not enough, so I had to put this and it works as expected:

@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)

I hope it helps :-)

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

replace

implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

with

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

Since the version with jre is absolute , just replace and sync the project

Official Documentation here Thanks for the link @ ROMANARMY

Happy Coding :)

Is there a way to remove the separator line from a UITableView?

You can do this with the UITableView property separatorStyle. Make sure the property is set to UITableViewCellSeparatorStyleNone and you're set.

Objective-C

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

In Swift (prior to 3)

tableView.separatorStyle = .None

In Swift 3/4/5

tableView.separatorStyle = .none

iPhone/iOS JSON parsing tutorial

You will love this framework.

And you will love this tool.

For learning about JSON you might like this resource.

And you'll probably love this tutorial.

Posting array from form

You're already doing that, as a matter of fact. When the form is submitted, the data is passed through a post array ($_POST). Your process.php is receiving that array and redistributing its values as individual variables.

Converting to upper and lower case in Java

String a = "ABCD"

using this

a.toLowerCase();

all letters will convert to simple, "abcd"
using this

a.toUpperCase()

all letters will convert to Capital, "ABCD"

this conver first letter to capital:

a.substring(0,1).toUpperCase()

this conver other letter Simple

a.substring(1).toLowerCase();

we can get sum of these two

a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();

result = "Abcd"

Failed to resolve: com.google.firebase:firebase-core:16.0.1

Since May 23, 2018 update, when you're using a firebase dependency, you must include the firebase-core dependency, too.

If adding it, you still having the error, try to update the gradle plugin in your gradle-wrapper.properties to 4.5 version:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip

and resync the project.

When to use static classes in C#

I only use static classes for helper methods, but with the advent of C# 3.0, I'd rather use extension methods for those.

I rarely use static classes methods for the same reasons why I rarely use the singleton "design pattern".

Convert JSON to DataTable

There is an easier method than the other answers here, which require first deserializing into a c# class, and then turning it into a datatable.

It is possible to go directly to a datatable, with JSON.NET and code like this:

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

Arguments to main in C

For parsing command line arguments on posix systems, the standard is to use the getopt() family of library routines to handle command line arguments.

A good reference is the GNU getopt manual

How to break out of the IF statement

public void Method()
{
    if(something)
    {
    //some code
        if(something2)
        {
           // now I should break from ifs and go to te code outside ifs
           goto done;
        }
        return;
    }
    // The code i want to go if the second if is true
    done: // etc.
}

same question

long answer

How to change the display name for LabelFor in razor in mvc3?

This was an old question, but existing answers ignore the serious issue of throwing away any custom attributes when you regenerate the model. I am adding a more detailed answer to cover the current options available.

You have 3 options:

  • Add a [DisplayName("Name goes here")] attribute to the data model class. The downside is that this is thrown away whenever you regenerate the data models.
  • Add a string parameter to your Html.LabelFor. e.g. @Html.LabelFor(model => model.SomekingStatus, "My New Label", new { @class = "control-label"}) Reference: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.labelextensions.labelfor(v=vs.118).aspx The downside to this is that you must repeat the label in every view.
  • Third option. Use a meta-data class attached to the data class (details follow).

Option 3 - Add a Meta-Data Class:

Microsoft allows for decorating properties on an Entity Framework class, without modifying the existing class! This by having meta-data classes that attach to your database classes (effectively a sideways extension of your EF class). This allow attributes to be added to the associated class and not to the class itself so the changes are not lost when you regenerate the data models.

For example, if your data class is MyModel with a SomekingStatus property, you could do it like this:

First declare a partial class of the same name (and using the same namespace), which allows you to add a class attribute without being overridden:

[MetadataType(typeof(MyModelMetaData))]
public partial class MyModel
{
}

All generated data model classes are partial classes, which allow you to add extra properties and methods by simply creating more classes of the same name (this is very handy and I often use it e.g. to provide formatted string versions of other field types in the model).

Step 2: add a metatadata class referenced by your new partial class:

public class MyModelMetaData
{
    // Apply DisplayNameAttribute (or any other attributes)
    [DisplayName("My New Label")]
    public string SomekingStatus;
}

Reference: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute(v=vs.110).aspx

Notes:

  • From memory, if you start using a metadata class, it may ignore existing attributes on the actual class ([required] etc) so you may need to duplicate those in the Meta-data class.
  • This does not operate by magic and will not just work with any classes. The code that looks for UI decoration attributes is designed to look for a meta-data class first.

Calculate mean across dimension in a 2D array

Here is a non-numpy solution:

>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

How to overlay images

I just got done doing this exact thing in a project. The HTML side looked a bit like this:

<a href="[fullsize]" class="gallerypic" title="">
  <img src="[thumbnail pic]" height="90" width="140" alt="[Gallery Photo]" class="pic" />
  <span class="zoom-icon">
      <img src="/images/misc/zoom.gif" width="32" height="32" alt="Zoom">
  </span>
</a>

Then using CSS:

a.gallerypic{
  width:140px;
  text-decoration:none;
  position:relative;
  display:block;
  border:1px solid #666;
  padding:3px;
  margin-right:5px;
  float:left;
}

a.gallerypic span.zoom-icon{
  visibility:hidden;
  position:absolute;
  left:40%;
  top:35%;
  filter:alpha(opacity=50);
  -moz-opacity:0.5;
  -khtml-opacity: 0.5;
  opacity: 0.5;
}

a.gallerypic:hover span.zoom-icon{
  visibility:visible;
}

I left a lot of the sample in there on the CSS so you can see how I decided to do the style. Note I lowered the opacity so you could see through the magnifying glass.

Hope this helps.

EDIT: To clarify for your example - you could ignore the visibility:hidden; and kill the :hover execution if you wanted, this was just the way I did it.

What's the reason I can't create generic array types in Java?

Try this:

List<?>[] arrayOfLists = new List<?>[4];

How do I convert an interval into a number of hours with postgres?

select floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600)), count(*)
from od_a_week
group by floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600));

The ::int conversion follows the principle of rounding. If you want a different result such as rounding down, you can use the corresponding math function such as floor.

RESTful Authentication

To be honest with you I've seen great answers here but something that bothers me a bit is when someone will take the whole Stateless concept to a extreme where it becomes dogmatic. It reminds me of those old Smalltalk fans that only wanted to embrace pure OO and if something is not an object, then you're doing it wrong. Give me a break.

The RESTful approach is supposed to make your life easier and reduce the overhead and cost of sessions, try to follow it as it is a wise thing to do, but the minute you follow a discipline (any discipline/guideline) to the extreme where it no longer provides the benefit it was intended for, then you're doing it wrong. Some of the best languages today have both, functional programming and object orientation.

If the easiest way for you to solve your problem is to store the authentication key in a cookie and send it on HTTP header, then do it, just don't abuse it. Remember that sessions are bad when they become heavy and big, if all your session consists of is a short string containing a key, then what's the big deal?

I am open to accept corrections in comments but I just don't see the point (so far) in making our lives miserable to simply avoid keeping a big dictionary of hashes in our server.

How do I address unchecked cast warnings?

Unfortunately, there are no great options here. Remember, the goal of all of this is to preserve type safety. "Java Generics" offers a solution for dealing with non-genericized legacy libraries, and there is one in particular called the "empty loop technique" in section 8.2. Basically, make the unsafe cast, and suppress the warning. Then loop through the map like this:

@SuppressWarnings("unchecked")
Map<String, Number> map = getMap();
for (String s : map.keySet());
for (Number n : map.values());

If an unexpected type is encountered, you will get a runtime ClassCastException, but at least it will happen close to the source of the problem.

How to check if a Docker image with a specific tag exist locally?

In bash script I do this to check if image exists by tag :

IMAGE_NAME="mysql:5.6"

if docker image ls -a "$IMAGE_NAME" | grep -Fq "$IMAGE_NAME" 1>/dev/null; then
echo "could found image $IMAGE_NAME..."
fi

Example script above checks if mysql image with 5.6 tag exists. If you want just check if any mysql image exists without specific version then just pass repository name without tag as this :

IMAGE_NAME="mysql"

Nullable type as a generic parameter possible?

Multiple generic constraints can't be combined in an OR fashion (less restrictive), only in an AND fashion (more restrictive). Meaning that one method can't handle both scenarios. The generic constraints also cannot be used to make a unique signature for the method, so you'd have to use 2 separate method names.

However, you can use the generic constraints to make sure that the methods are used correctly.

In my case, I specifically wanted null to be returned, and never the default value of any possible value types. GetValueOrDefault = bad. GetValueOrNull = good.

I used the words "Null" and "Nullable" to distinguish between reference types and value types. And here is an example of a couple extension methods I wrote that compliments the FirstOrDefault method in System.Linq.Enumerable class.

    public static TSource FirstOrNull<TSource>(this IEnumerable<TSource> source)
        where TSource: class
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a class is null
        return result;
    }

    public static TSource? FirstOrNullable<TSource>(this IEnumerable<TSource?> source)
        where TSource : struct
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a nullable is null
        return result;
    }

#1071 - Specified key was too long; max key length is 1000 bytes

run this query before creating or altering table.

SET @@global.innodb_large_prefix = 1;

this will set max key length to 3072 bytes

How to check if an array value exists?

You could use the PHP in_array function

if( in_array( "bla" ,$yourarray ) )
{
    echo "has bla";
}

No module named setuptools

The PyPA recommended tool for installing and managing Python packages is pip. pip is included with Python 3.4 (PEP 453), but for older versions here's how to install it (on Windows, using Python 3.3):

Download https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

Sample usage:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

In your case it would be this (it appears that pip caches independent of Python version):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

How do I combine 2 javascript variables into a string

warning! this does not work with links.

var variable = 'variable', another = 'another';

['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');

Markdown `native` text alignment

I was trying to center an image and none of the techniques suggested in answers here worked. A regular HTML <img> with inline CSS worked for me...

<img style="display: block; margin: auto;" alt="photo" src="{{ site.baseurl }}/images/image.jpg">

This is for a Jekyll blog hosted on GitHub

Center an item with position: relative

If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto

Vertical centering is a bit tricker, but possible.

Rendering raw html with reactjs

I used this library called Parser. It worked for what I needed.

import React, { Component } from 'react';    
import Parser from 'html-react-parser';

class MyComponent extends Component {
  render() {
    <div>{Parser(this.state.message)}</div>
  }
};

Static variables in C++

A static variable declared in a header file outside of the class would be file-scoped in every .c file which includes the header. That means separate copy of a variable with same name is accessible in each of the .c files where you include the header file.

A static class variable on the other hand is class-scoped and the same static variable is available to every compilation unit that includes the header containing the class with static variable.

Can I nest a <button> element inside an <a> using HTML5?

_x000D_
_x000D_
<a href="index.html">_x000D_
  <button type="button">Submit</button>_x000D_
</a>
_x000D_
_x000D_
_x000D_ Or you can use java script in button as:

_x000D_
_x000D_
<button type="submit" onclick="myFunction()">Submit</button>_x000D_
<script>_x000D_
  function myFunction() {_x000D_
      var w = window.open(file:///E:/Aditya%20panchal/index.html);_x000D_
    }_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to add values in a variable in Unix shell scripting?

In ksh ,bash ,sh:

$ count7=0                     
$ count1=5
$ 
$ (( count7 += count1 ))
$ echo $count7
$ 5

Why do abstract classes in Java have constructors?

Because abstract classes have state (fields) and somethimes they need to be initialized somehow.

How create table only using <div> tag and Css

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key to getting empty cells and cells in general to be the right size, is Box-Sizing and Padding. Border will do the same thing as well, but creates a line in the row. Padding doesn't. And, while I haven't tried it, I think Margin will act the same way as Padding, in forcing and empty cell to be rendered properly.

Undo a Git merge that hasn't been pushed yet

With git reflog check which commit is one prior the merge (git reflog will be a better option than git log). Then you can reset it using:

git reset --hard commit_sha

There's also another way:

git reset --hard HEAD~1

It will get you back 1 commit.

Be aware that any modified and uncommitted/unstashed files will be reset to their unmodified state. To keep them either stash changes away or see --merge option below.


As @Velmont suggested below in his answer, in this direct case using:

git reset --hard ORIG_HEAD

might yield better results, as it should preserve your changes. ORIG_HEAD will point to a commit directly before merge has occurred, so you don't have to hunt for it yourself.


A further tip is to use the --merge switch instead of --hard since it doesn't reset files unnecessarily:

git reset --merge ORIG_HEAD

--merge

Resets the index and updates the files in the working tree that are different between <commit> and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added).

Show empty string when date field is 1/1/1900

When you use a CASE expression (not statement) you have to be aware of data type precedence. In this case you can't just set a DATETIME to an empty string. Try it:

SELECT CONVERT(DATETIME, '');

One workaround is to present your date as a string:

CASE WHEN CONVERT(DATE, CreatedDate) = '1900-01-01' -- to account for accidental time
  THEN ''
  ELSE CONVERT(CHAR(10), CreatedDate, 120)
    + ' ' + CONVERT(CHAR(8), CreatedDate, 108)
END 

Or you could fiddle with the presentation stuff where it belongs, at the presentation tier.

Here is an example that works exactly as you seem to want:

DECLARE @d TABLE(CreatedDate DATETIME);

INSERT @d SELECT '19000101' UNION ALL SELECT '20130321';

SELECT d = CASE WHEN CreatedDate = '19000101'
  THEN ''
  ELSE CONVERT(CHAR(10), CreatedDate, 120)
    + ' ' + CONVERT(CHAR(8), CreatedDate, 108)
END FROM @d;

Results:

d
-------------------
                    <-- empty string
2013-03-21 00:00:00

getContext is not a function

Actually we get this error also when we create canvas in javascript as below.

document.createElement('canvas');

Here point to be noted we have to provide argument name correctly as 'canvas' not anything else.

Thanks

the getSource() and getActionCommand()

I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").

I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:

public class SeleccionListener implements ActionListener, FocusListener {}

So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:

public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
        System.out.println("Aceptar pressed");
    }

In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).

public void focusGained(FocusEvent focusEvent) {
    if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
        System.out.println("Data radio button");
    }

In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)

python multithreading wait till all threads finished

I just came across the same problem where I needed to wait for all the threads which were created using the for loop.I just tried out the following piece of code.It may not be the perfect solution but I thought it would be a simple solution to test:

for t in threading.enumerate():
    try:
        t.join()
    except RuntimeError as err:
        if 'cannot join current thread' in err:
            continue
        else:
            raise