Programs & Examples On #Eventmachine

EventMachine is a fast, reactor pattern library for Ruby programs. It provides non-blocking IO APIs with transparent internal buffers and standard reactor features (such as defer, next_tick and timers). (note to future editors: Eventmachine itself does not use Fibers, and the core does not use threads for any IO, timers or core infrastructure).

PG::ConnectionBad - could not connect to server: Connection refused

I got the same problem after updating my mac on Osx Movaje.

i found this solution :

Try first the bellow command line in your terminal :

brew services restart postgresql

If nothing change :

ps aux | grep postgres

If still nothing change :

ls -ls | grep post

Last command to fix it, removed the postgres lock file by executing from root :

rm /usr/local/var/postgres/postmaster.pid

and then :

brew services restart postgresql

From berziiii : https://github.com/ga-wdi-boston/capstone-project/issues/325

Hope that will help :)

Regards !!

Should CSS always preceed Javascript?

Personally, I would not place too much emphasis on such "folk wisdom." What may have been true in the past might well not be true now. I would assume that all of the operations relating to a web-page's interpretation and rendering are fully asynchronous ("fetching" something and "acting upon it" are two entirely different things that might be being handled by different threads, etc.), and in any case entirely beyond your control or your concern.

I'd put CSS references in the "head" portion of the document, along with any references to external scripts. (Some scripts may demand to be placed in the body, and if so, oblige them.)

Beyond that ... if you observe that "this seems to be faster/slower than that, on this/that browser," treat this observation as an interesting but irrelevant curiosity and don't let it influence your design decisions. Too many things change too fast. (Anyone want to lay any bets on how many minutes it will be before the Firefox team comes out with yet another interim-release of their product? Yup, me neither.)

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Another avenue that hasn't been considered is that your postgres was installed by pgvm (Postgres Version Manager).

Uninstall with pgvm uninstall 9.0.3

Float a div above page content

Yes, the higher the z-index, the better. It will position your content element on top of every other element on the page. Say you have z-index to some elements on your page. Look for the highest and then give a higher z-index to your popup element. This way it will flow even over the other elements with z-index. If you don't have a z-index in any element on your page, you should give like z-index:2; or something higher.

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had this problem. Solution for me was to remove links to Vue.js files. Vue.js and JQuery have some conflicts in datepicker and datetimepicker functions.

caching JavaScript files

I just finished my weekend project cached-webpgr.js which uses the localStorage / web storage to cache JavaScript files. This approach is very fast. My small test showed

  • Loading jQuery from CDN: Chrome 268ms, FireFox: 200ms
  • Loading jQuery from localStorage: Chrome 47ms, FireFox 14ms

The code to achieve that is tiny, you can check it out at my Github project https://github.com/webpgr/cached-webpgr.js

Here is a full example how to use it.

The complete library:

function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};

Calling the library

requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
    requireScript('examplejs', '0.0.3', 'example.js');
});

Android: Share plain text using intent (to all messaging apps)

Images or binary data:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpg");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

or HTML:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));

Reverse / invert a dictionary mapping

To do this while preserving the type of your mapping (assuming that it is a dict or a dict subclass):

def inverse_mapping(f):
    return f.__class__(map(reversed, f.items()))

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

Long press on Google play application

  • Select App info
  • Click on Clear Cache
  • Click on Clear app data

Now again click on Google Play app, It will work now.

IntelliJ: Never use wildcard imports

  1. File\Settings... (Ctrl+Alt+S)
  2. Project Settings > Editor > Code Style > Java > Imports tab
  3. Set Class count to use import with '*' to 999
  4. Set Names count to use static import with '*' to 999

After this, your configuration should look like: enter image description here

(On IntelliJ IDEA 13.x, 14.x, 15.x, 2016.x, 2017.x)

Add text to textarea - Jquery

That should work. Better if you pass a function to val:

$('#replyBox').val(function(i, text) {
    return text + quote;
});

This way you avoid searching the element and calling val twice.

Is it possible to program Android to act as physical USB keyboard?

The only way I could see this being possible is if you:

  • modified the Android firmware to give you usb level access at a low enough level that you could operate using the necessary protocol

or

  • Made some sort of special hardware level converter that you attached to the device.

(So I suppose, depending on how much work you want to do, it could be a hardware or software problem.)

What is the best or most commonly used JMX Console / Client

Alternatively, constructing a JMX console yourself doesn't need to be hard. Just plug in Jolokia and create a web page getting the attributes that you're interested in. Admittedly, it doesn't allow you to do trend analysis, but it does allow you to construct something that is really geared towards your purpose.

I constructed something in just a few lines: http://nxt.flotsam.nl/ears-and-eyes.html

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

Chrome 11 spits out the following in its debugger:

[Error] GET http://www.mypicx.com/images/logo.jpg undefined (undefined)

It looks like that hosting service is using some funky dynamic system that is preventing these browsers from fetching it correctly. (Instead it tries to fetch the default base image, which is problematically a jpeg.) Could you just upload another copy of the image elsewhere? I would expect it to be the easiest solution by a long mile.

Edit: See what happens in Chrome when you place the image using normal <img> tags ;)

Regular expression for number with length of 4, 5 or 6

Be aware that, as written, Peter's solution will "accept" 0000. If you want to validate numbers between 1000 and 999999, then that is another problem :-)

^[1-9][0-9]{3,5}$

for example will block inserting 0 at the beginning of the string.

If you want to accept 0 padding, but only up to a lengh of 6, so that 001000 is valid, then it becomes more complex. If we use look-ahead then we can write something like

^(?=[0-9]{4,6}$)0*[1-9][0-9]{3,}$

This first checks if the string is long 4-6 (?=[0-9]{4,6}$), then skips the 0s 0*and search for a non-zero [1-9] followed by at least 3 digits [0-9]{3,}.

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Solution: You must explicitly add the parameter -CAfile your-ca-file.pem.

Note: I tried also param -CApath mentioned in another answers, but is does not works for me.

Explanation: Error unable to get local issuer certificate means, that the openssl does not know your root CA cert.


Note: If you have web server with more domains, do not forget to add also -servername your.domain.net parameter. This parameter will "Set TLS extension servername in ClientHello". Without this parameter, the response will always contain the default SSL cert (not certificate, that match to your domain).

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

install beautiful soup using pip

If you have more than one version of python installed, run the respective pip command.

For example for python3.6 run the following

pip3.6 install beautifulsoup4

To check the available command/version of pip and python on Mac run

ls /usr/local/bin

Calculating the distance between 2 points

Something like this in c# would probably do the job. Just make sure you are passing consistent units (If one point is in meters, make sure the second is also in meters)

private static double GetDistance(double x1, double y1, double x2, double y2)
{
   return Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2));
}

Called like so:

double distance = GetDistance(x1, y1, x2, y2)
if(distance <= 5)
{
   //Do stuff
}

How to add a file to the last commit in git?

Yes, there's a command git commit --amend which is used to "fix" last commit.

In your case it would be called as:

git add the_left_out_file
git commit --amend --no-edit

The --no-edit flag allow to make amendment to commit without changing commit message.

EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.

Remove Fragment Page from ViewPager in Android

You could just override the destroyItem method

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    fragmentManager.beginTransaction().remove((Fragment) object).commitNowAllowingStateLoss();
}

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

Google Maps V3 marker with label

I doubt the standard library supports this.

But you can use the google maps utility library:

http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);

var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

var marker = new MarkerWithLabel({
   position: myLatlng,
   map: map,
   draggable: true,
   raiseOnDrag: true,
   labelContent: "A",
   labelAnchor: new google.maps.Point(3, 30),
   labelClass: "labels", // the CSS class for the label
   labelInBackground: false
 });

The basics about marker can be found here: https://developers.google.com/maps/documentation/javascript/overlays#Markers

HTML entity for check mark

Something like this?

if so, type the HTML &#10004;

And &#10003; gives a lighter one:

How to get all selected values of a multiple select box?

Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:

selected = Array.prototype.filter.apply(
  select.options, [
    function(o) {
      return o.selected;
    }
  ]
);

It seems to be faster than a loop in IE, FF and Safari. I find it interesting that it's slower in Chrome and Opera.

Another approach would be using selectors:

selected = Array.prototype.map.apply(
    select.querySelectorAll('option[selected="selected"]'),
    [function (o) { return o.value; }]
);

Git copy changes from one branch to another

If you are using tortoise git.

please follow the below steps.

  1. Checkout BranchB
  2. Open project folder, go to TortoiseGit --> Pull
  3. In pull screen, Change the remote branch "BranchA" and click ok.
  4. Then right click again, go to TortoiseGit --> Push.

Now your changes moved from BranchA to BranchB

How to force open links in Chrome not download them?

I think the question was about to open a local file directly instead of downloading a local file to the download folder and open the file in the download folder, which seems not possible in Chrome, except some add-on mentioned above.

My workaround would be to right click -> Copy the link location Windows + R and paste the link there and Enter It will go to the file directly.

All shards failed

It is possible on your restart some shards were not recovered, causing the cluster to stay red.
If you hit:
http://<yourhost>:9200/_cluster/health/?level=shards you can look for red shards.

I have had issues on restart where shards end up in a non recoverable state. My solution was to simply delete that index completely. That is not an ideal solution for everyone.

It is also nice to visualize issues like this with a plugin like:
Elasticsearch Head

How do I list one filename per output line in Linux?

you can use ls -1

ls -l will also do the work

test attribute in JSTL <c:if> tag

All that the test attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"

<c:if test="true">Hello world!</c:if>

The code within the <%= %> returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if> tag looks for.

What is the path for the startup folder in windows 2008 server

SHGetKnownFolderPath:

Retrieves the full path of a known folder identified by the folder's KNOWNFOLDERID.

And, FOLDERID_CommonStartup:

Default Path %ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp

There are also managed equivalents, but you haven't told us what you're programming in.

How to go up a level in the src path of a URL in HTML?

Here is all you need to know about relative file paths:

  • Starting with / returns to the root directory and starts there

  • Starting with ../ moves one directory backward and starts there

  • Starting with ../../ moves two directories backward and starts there (and so on...)

  • To move forward, just start with the first sub directory and keep moving forward.

Click here for more details!

How to make a text box have rounded corners?

This can be done with CSS3:

<input type="text" />

input
{
  -moz-border-radius: 15px;
 border-radius: 15px;
    border:solid 1px black;
    padding:5px;
}

http://jsfiddle.net/UbSkn/1/


However, an alternative would be to put the input inside a div with a rounded background, and no border on the input

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Since you're using PHP, you will probably need to use the CURLOPT_PORT option, like so:

curl_setopt($ch, CURLOPT_PORT, 11740);

Bear in mind, you may face problems with SELinux:

Unable to make php curl request with port number

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

The cleanest way is to copy the following classes: ShareActionProvider, ActivityChooserView, ActivityChooserModel. Add the ability to filter the intents in the ActivityChooserModel, and the appropriate support methods in the ShareActionProvider. I created the necessary classes, you can copy them into your project (https://gist.github.com/saulpower/10557956). This not only adds the ability to filter the apps you would like to share with (if you know the package name), but also to turn off history.

private final String[] INTENT_FILTER = new String[] {
    "com.twitter.android",
    "com.facebook.katana"
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.journal_entry_menu, menu);

    // Set up ShareActionProvider's default share intent
    MenuItem shareItem = menu.findItem(R.id.action_share);

    if (shareItem instanceof SupportMenuItem) {
        mShareActionProvider = new ShareActionProvider(this);
        mShareActionProvider.setShareIntent(ShareUtils.share(mJournalEntry));
        mShareActionProvider.setIntentFilter(Arrays.asList(INTENT_FILTER));
        mShareActionProvider.setShowHistory(false);
        ((SupportMenuItem) shareItem).setSupportActionProvider(mShareActionProvider);
    }

    return super.onCreateOptionsMenu(menu);
}

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

What is the difference between logical data model and conceptual data model?

This is an old question and maybe this comes way too late, but I don't see one very important aspect necessary to answering the question. That is, the TARGET audience for the data model. The Conceptual Data Model is the model generated from business analysis, from interviews with the BUSINESS about their data. It is not so much "high level" as it is the business's understanding of their data, business rules captured in the relationships between "candidate" entities. At this point, you are capturing the things of importance to the business (Employee, Customer, Contract, Account, etc.) and the relationships between them. The final Conceptual Data Model may be somewhat abstract -- for instance, treating Individuals and Organizations entering into a contract as subtypes of a "Party", Contractors and Permanent Employees as subtypes of an Employee, even Employees and Customers subtypes of "Person" -- but it is a document that a data modeler develops from discussions with the business SMEs and presents to the business for validation.

The Logical Data Model is not just "more detail" -- where useful and important, a Conceptual Data Model may well have attributes included -- it is the ARCHITECTURE document, the model that is presented to the software analysts/engineers to explain and specify the data requirements. It will resolve many-to-many relationships to association tables and will define all attributes, with examples and constraints, so that code can be written against the architecture.

The Physical model is that Logical Model generated specifically for a particular environment, such as SQL Server or Teradata or Oracle or whatever. It will have keys, indexes, partitions, or whatever is needed to implement, based on sizing, access frequency, security constraints, etc.

So, if you are being asked to develop a Conceptual Data Model, you are being asked to design the solution (or part of it) from scratch, getting your information from the business. There's more to it, but I hope that answers the question.

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

1- Never use Response.Write.

2- I put the code below after create (not in Page_Load) a LinkButton (dynamically) and solved my problem:

ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(lblbtndoc1);

How to upload image in CodeIgniter?

Below code for an uploading a single file at a time. This is correct and perfect to upload a single file. Read all commented instructions and follow the code. Definitely, it is worked.

public function upload_file() {
    ***// Upload folder location***
    $config['upload_path'] = './public/upload/';

    ***// Allowed file type***
    $config['allowed_types'] = 'jpg|jpeg|png|pdf';

    ***// Max size, i will set 2MB***
    $config['max_size'] = '2024';

    $config['max_width'] = '1024';
    $config['max_height'] = '768';

    ***// load upload library***            
    $this->load->library('upload', $config);

    ***// do_upload is the method, to send the particular image and file on that 
       // particular 
       // location that is detail in $config['upload_path']. 
       // In bracks will set name upload, here you need to set input name attribute 
       // value.***

    if($this->upload->do_upload('upload')) {
       $data = $this->upload->data();
       $post['upload'] = $data['file_name'];
    } else {
      $error = array('error' => $this->upload->display_errors());
    }
 }

Mockito matcher and array of primitives

I would rather use Matchers.<byte[]>any(). This worked for me.

Difference between socket and websocket?

You'd have to use WebSockets (or some similar protocol module e.g. as supported by the Flash plugin) because a normal browser application simply can't open a pure TCP socket.

The Socket.IO module available for node.js can help a lot, but note that it is not a pure WebSocket module in its own right.

It's actually a more generic communications module that can run on top of various other network protocols, including WebSockets, and Flash sockets.

Hence if you want to use Socket.IO on the server end you must also use their client code and objects. You can't easily make raw WebSocket connections to a socket.io server as you'd have to emulate their message protocol.

Convert character to ASCII code in JavaScript

str.charCodeAt(index)

Using charCodeAt() The following example returns 65, the Unicode value for A.

'ABC'.charCodeAt(0) // returns 65

How to add SHA-1 to android application

For linux Ubuntu Open Terminal and Write :-

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

Why use deflate instead of gzip for text files served by Apache?

You are likely not able to actually pick deflate as an option. Contrary to what you may expect mod_deflate is not using deflate but gzip. So while most of the points made are valid it likely is not relevant for most.

How to select only the records with the highest date in LINQ

It could be something like:

var qry = from t in db.Lasttraces
          group t by t.AccountId into g
          orderby t.Date
          select new { g.AccountId, Date = g.Max(e => e.Date) };

How to solve java.lang.NoClassDefFoundError?

After working on a NetBeans project for many months, I suddenly got the NoClassDefFoundError message shortly after getting a "Low Memory" alert. Doing a Clean rebuild didn't help, but closing Netbeans altogether and reopening the project there were no error reports.

How to turn on front flash light programmatically in Android?

From my experience, if your application is designed to work in both portrait and landscape orientation, you need to declare the variable cam as static. Otherwise, onDestroy(), which is called on switching orientation, destroys it but doesn't release Camera so it's not possible to reopen it again.

package com.example.flashlight;

import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

public static Camera cam = null;// has to be static, otherwise onDestroy() destroys it

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public void flashLightOn(View view) {

    try {
        if (getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA_FLASH)) {
            cam = Camera.open();
            Parameters p = cam.getParameters();
            p.setFlashMode(Parameters.FLASH_MODE_TORCH);
            cam.setParameters(p);
            cam.startPreview();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Exception flashLightOn()",
                Toast.LENGTH_SHORT).show();
    }
}

public void flashLightOff(View view) {
    try {
        if (getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA_FLASH)) {
            cam.stopPreview();
            cam.release();
            cam = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Exception flashLightOff",
                Toast.LENGTH_SHORT).show();
    }
}
}

to manifest I had to put this line

    <uses-permission android:name="android.permission.CAMERA" />

from http://developer.android.com/reference/android/hardware/Camera.html

suggested lines above wasn't working for me.

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

Following applies to IIS 7

The error is trying to tell you that one of two things is not working properly:

  • There is no default page (e.g., index.html, default.aspx) for your site. This could mean that the Default Document "feature" is entirely disabled, or just misconfigured.
  • Directory browsing isn't enabled. That is, if you're not serving a default page for your site, maybe you intend to let users navigate the directory contents of your site via http (like a remote "windows explorer").

See the following link for instructions on how to diagnose and fix the above issues.

http://support.microsoft.com/kb/942062/en-us

If neither of these issues is the problem, another thing to check is to make sure that the application pool configured for your website (under IIS Manager, select your website, and click "Basic Settings" on the far right) is configured with the same .Net framework version (in IIS Manager, under "Application Pools") as the targetFramework configured in your web.config, e.g.:

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime targetFramework="4.0" />
  </system.web>

I'm not sure why this would generate such a seemingly unrelated error message, but it did for me.

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

And so I see from other answers that there are several ways of dealing with it. But I don't believe this. It has to be reduced into one way. I love IDE but, but if I follow the IDE steps provided from different answers I know this is not the fundamental algebra. My error looked like:

* What went wrong:
Execution failed for task ':compileJava'.
> Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'.

And the way to solve it scientifically is:

vi build.gradle

To change from:

java {
    sourceCompatibility = JavaVersion.toVersion('11')
    targetCompatibility = JavaVersion.toVersion('11')
}

to become:

java {
    sourceCompatibility = JavaVersion.toVersion('8')
    targetCompatibility = JavaVersion.toVersion('8')
}

The scientific method is that method that is open for argumentation and deals on common denominators.

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

Translate all characters into their hex-entity equivalents. In this case, Null would be converted into &#4E;&#75;&#6C;&#6C;

expected constructor, destructor, or type conversion before ‘(’ token

You are missing the std namespace reference in the cc file. You should also call nom.c_str() because there is no implicit conversion from std::string to const char * expected by ifstream's constructor.

Polygone::Polygone(std::string nom) {
    std::ifstream fichier (nom.c_str(), std::ifstream::in);
    // ...
}

PHP: Show yes/no confirmation dialog

<a href="http://stackoverflow.com" 
    onclick="return confirm('Are you sure?');">My Link</a>

Creating a border like this using :before And :after Pseudo-Elements In CSS?

See the following snippet, is this what you want?

_x000D_
_x000D_
body {
    background: silver;
    padding: 0 10px;
}

#content:after {
    height: 10px;
    display: block;
    width: 100px;
    background: #808080;
    border-right: 1px white;
    content: '';
}

#footer:before {
    display: block;
    content: '';
    background: silver;
    height: 10px;
    margin-top: -20px;
    margin-left: 101px;
}

#content {
    background: white;
}


#footer {
    padding-top: 10px;
    background: #404040;
}

p {
    padding: 100px;
    text-align: center;
}

#footer p {
    color: white;
}
_x000D_
<body>
    <div id="content"><p>#content</p></div>
    <div id="footer"><p>#footer</p></div>
</body>
_x000D_
_x000D_
_x000D_

JSFiddle

using favicon with css

You don't need to - if the favicon is place in the root at favicon.ico, browsers will automatically pick it up.

If you don't see it working, clear your cache etc, it does work without the markup. You only need to use the code if you want to call it something else, or put it on a CDN for instance.

How do I read and parse an XML file in C#?

XmlDocument to read an XML from string or from file.

XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");

or

doc.LoadXml("<xml>something</xml>");

then find a node below it ie like this

XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");

or

foreach(XmlNode node in doc.DocumentElement.ChildNodes){
   string text = node.InnerText; //or loop through its children as well
}

then read the text inside that node like this

string text = node.InnerText;

or read an attribute

string attr = node.Attributes["theattributename"]?.InnerText

Always check for null on Attributes["something"] since it will be null if the attribute does not exist.

Android toolbar center title and custom font

I was facing the same issue, fixed by doing this in MainActivity

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);

And In Fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    if (view == null) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_example, container, false);
        init();
    }
    getActivity().setTitle("Choose Fragment");
    return view;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.example_menu, menu);
}

Merge/flatten an array of arrays

Recursively calling the deepFlatten function so we can spread the inner array without using any external helper method is the way to go.

const innerArr = ['a', 'b'];
const multiDimArr = [[1, 2], 3, 4, [5, 6, innerArr], 9];

const deepFlatten = (arr) => {
  const flatList = [];
  arr.forEach(item => {
    Array.isArray(item)
     ? flatList.push(...deepFlatten(item)) // recursive call
     : flatList.push(item)
  });
  return flatList;
}

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

Better way to sort array in descending order

Sure, You can customize the sort.

You need to give the Sort() a delegate to a comparison method which it will use to sort.

Using an anonymous method:

Array.Sort<int>( array,
delegate(int a, int b)
  {
    return b - a; //Normal compare is a-b
  }); 

Read more about it:

Sorting arrays
MSDN - Array.Sort Method (T[], Comparison)

How to add an Access-Control-Allow-Origin header

So what you do is... In the font files folder put an htaccess file with the following in it.

<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

also in your remote CSS file, the font-face declaration needs the full absolute URL of the font-file (not needed in local CSS files):

e.g.

@font-face {
    font-family: 'LeagueGothicRegular';
    src: url('http://www.example.com/css/fonts/League_Gothic.eot?') format('eot'),
         url('http://www.example.com/css/fonts/League_Gothic.woff') format('woff'),
         url('http://www.example.com/css/fonts/League_Gothic.ttf') format('truetype'),
         url('http://www.example.com/css/fonts/League_Gothic.svg')

}

That will fix the issue. One thing to note is that you can specify exactly which domains should be allowed to access your font. In the above htaccess I have specified that everyone can access my font with "*" however you can limit it to:

A single URL:

Header set Access-Control-Allow-Origin http://example.com

Or a comma-delimited list of URLs

Access-Control-Allow-Origin: http://site1.com,http://site2.com

(Multiple values are not supported in current implementations)

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

There are so many reasons for this error.I also got one and solved it.

It may be possible that you are adding a third party framework and not including it in the Copy Bundle Resources.That solved the problem for me.

Do this as follows. Go to Target -> BuildPhases -> CopyBundleResources -> Drag and drop your framework and run the code.

What is the iOS 5.0 user agent string?

I found a more complete listing at user agent string. BTW, this site has more than just iOS user agent strings. Also, the home page will "break down" the user agent string of your current browser for you.

Multiple Errors Installing Visual Studio 2015 Community Edition

I spent a whole week trying to solve this issue. What finally did it for me was disabling my anti-virus programs. Before I stumbled upon my solution, I went through a lot of other solutions. I thought, I'd post some of the solutions that might prove to be useful for those who are still having trouble with installing Visual Studios 2015 Community Edition.

Solution 1: Minimal Installation

Try installing with minimal extra features. Run the Visual Studios 2015 installation, then click "Custom" and on the following screen, uncheck everything and proceed with the installation.

Solution 2: Delete installation cache

Perhaps the installation failed due to corrupt files in the cache. When installation fails, remove all Visual Studio cache related items and do a full re-installation. To do this, run command prompt (Run as Administrator) and type: "cd /programdata/package cache/" then press enter. Then type "del /f /s *.msi /f /s *.cab" then press enter. Now run the Visual Studios 2015 installation again.

Solution 3: Delete temporary file data stored on your computer

Open up File Explorer and go to "C:\Users\[Your User Account Name]\AppData\Local\Microsoft". Then delete the following folders: VSCommon, VisualStudio, Blend, VsGraphics, ApplicationInsights, vshub, Team Foundation, Web Platform Installer and MsBuild. After this, run the Visual Studios 2015 Installer again.

Solution 4: Enable all four evaluations of Symbolic links

First, check to see if all four evaluations are enabled. Open up command prompt (Run as Administrator) and type "fsutil behavior query SymlinkEvaluation". All 4 evaluations should be enabled. If they aren't then type "fsutil behavior set SymlinkEvaluation L2L:1 R2R:1 L2R:1 R2L:1". Once those 4 evaluations are set, clear up temporary files and clear installation cache (see Solution 2 and Solution 3) then run the Visual Studios 2015 installation again.

Solution 5: Repair the Redistributables

Perhaps, the problem is that your VC-redistributables are faulty and are in need of repair. To do so, run "Add/Remove programs" and look for all the x86 and x64 versions of Microsoft Visual C++ [Year] Redistributable (Version). Then press Change for each of them and when the uninstallation screen pops up, press Repair. I did it for all the versions I had previously installed: 2012, 2013 and 2015. Therefore, I repaired 6 of them: 2012: x86 and x64, 2013: x86 and x64, 2015: x86 and x64.

Solution 6: Check to see if x86 and x64 sizes are the same

As mentioned by others in this discussion, do a search for vcruntime140.dll and see if the x86 and x64 versions. They should NOT have the same size. If they do, see solution 5 or you can manually delete them (** Be cautious when deleting files from the Windows folder!) and re-install them (from here: https://www.microsoft.com/en-ca/download/details.aspx?id=48145).
Also do the same check for msvcp140.dll. I personally did a search for these files in "C:\Windows\SysWOW64 and C:\Windows\System32" and compared the files from the two folders. Moreover I also checked for differences of vcruntime140.dll and msvcp140.dll in "C:\Program Files\Microsoft Visual Studio 14.0" and "C:\Program Files (x86)\Microsoft Visual Studio 14.0"

Solution 7: Temporarily disable all Anti-Virus Protection and Firewalls

For me, it turned out that the problem stemmed from having ByteFence Anti-Malware and Norton Security with Backup protection. I disabled real-time protection from ByteFence Anti-Malware and I disabled Auto-Protect and Smart Firewall from Norton Security with Backup. Before I ran the installation again, I repeated Solution 2 and Solution 3 (scroll up). And Voila, installation was successful. But how did I find out that the Anti-Virus Program was the culprit? Read Solution 8.

Solution 8: Carefully monitor Visual Studios Installation Process for Intrusions

I resorted to this solution in order to find out the problem. After reading Ezh's article, I decided to download Process Monitor v3.2 and Process Explorer v16.1. I was carefully monitoring 3 programs side-by-side: Process Monitor, Process Explorer and the Visual Studios 2015 Installer, and I watched very closely all the processes that the installer was invoking. Then I noticed that when VSIXInstaller.exe process came on and attempted to install something from a remote server, it kept failing over and over again because my Anti-Virus Program would suddenly appear on screen (as a process) and decide to hog/block some important DLL files that VSIX installation needed. Temporarily disabling the anti-virus program solved my issue!

Solution 9: Complete Windows format and re-installation

If all else fails, and you are really desperate to get Visual Studios 2015 working, I suggest a complete Windows re-installation. At this point, the problem is most likely some type of interference/intrusion with a program which you do not know of.

What is the best way to uninstall gems from a rails3 project?

With newer versions of bundler you can use the clean task:

$ bundle help clean
Usage:
    bundle clean

Options:
    [--dry-run=only print out changes, do not actually clean gems]
    [--force=forces clean even if --path is not set]
    [--no-color=Disable colorization in output]
    -V, [--verbose=Enable verbose output mode]

Cleans up unused gems in your bundler directory
$ bundle clean --dry-run --force
Would have removed actionmailer (3.1.12)
Would have removed actionmailer (3.2.0.rc2)
Would have removed actionpack (3.1.12)
Would have removed actionpack (3.2.0.rc2)
Would have removed activemodel (3.1.12)
...

edit:

This is not recommended if you're using a global gemset (i.e. - all of your projects keep their gems in the same place). There're few ways to keep each project's gems separate, though:

  1. rvm gemsets (http://rvm.io/gemsets/basics)
  2. bundle install with any of the following options: --deployment or --path=<path> (http://bundler.io/v1.3/man/bundle-install.1.html)

When to use references vs. pointers

My rule of thumb is:

  • Use pointers for outgoing or in/out parameters. So it can be seen that the value is going to be changed. (You must use &)
  • Use pointers if NULL parameter is acceptable value. (Make sure it's const if it's an incoming parameter)
  • Use references for incoming parameter if it cannot be NULL and is not a primitive type (const T&).
  • Use pointers or smart pointers when returning a newly created object.
  • Use pointers or smart pointers as struct or class members instead of references.
  • Use references for aliasing (eg. int &current = someArray[i])

Regardless which one you use, don't forget to document your functions and the meaning of their parameters if they are not obvious.

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

It is because you haven't qualified Cells(1, 1) with a worksheet object, and the same holds true for Cells(10, 2). For the code to work, it should look something like this:

Dim ws As Worksheet

Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

Alternately:

With Sheets("SheetName")
    Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range also, like so:

ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

or

With Sheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Creating a div element inside a div element in javascript

Your code works well you just mistyped this line of code:

document.getElementbyId('lc').appendChild(element);

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
    var element = document.createElement("div");_x000D_
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
    document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();">  _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

Parse json string using JSON.NET

I did not test the following snippet... hopefully it will point you towards the right direction:

    var jsreader = new JsonTextReader(new StringReader(stringData));
    var json = (JObject)new JsonSerializer().Deserialize(jsreader);
    var tableRows = from p in json["items"]
                 select new
                 {
                     Name = (string)p["Name"],
                     Age = (int)p["Age"],
                     Job = (string)p["Job"]
                 };

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Text files in Windows don't have a format. There's an unofficial convention that if the file starts with the BOM codepoint in UTF-8 format that it's UTF-8, but that convention isn't universally supported. That would be the 3 byte sequence "\xef\xbf\xbe", i.e. ￾ in the Latin-1 character set.

Properties file in python (similar to Java Properties)

This is what i had written to parse file and set it as env variables which skips comments and non key value lines added switches to specify hg:d

  • -h or --help print usage summary
  • -c Specify char that identifies comment
  • -s Separator between key and value in prop file
  • and specify properties file that needs to be parsed eg : python EnvParamSet.py -c # -s = env.properties

    import pipes
    import sys , getopt
    import os.path
    
    class Parsing :
    
            def __init__(self , seprator , commentChar , propFile):
            self.seprator = seprator
            self.commentChar = commentChar
            self.propFile  = propFile
    
        def  parseProp(self):
            prop = open(self.propFile,'rU')
            for line in prop :
                if line.startswith(self.commentChar)==False and  line.find(self.seprator) != -1  :
                    keyValue = line.split(self.seprator)
                    key =  keyValue[0].strip() 
                    value = keyValue[1].strip() 
                            print("export  %s=%s" % (str (key),pipes.quote(str(value))))
    
    
    
    
    class EnvParamSet:
    
        def main (argv):
    
            seprator = '='
            comment =  '#'
    
            if len(argv)  is 0:
                print "Please Specify properties file to be parsed "
                sys.exit()
            propFile=argv[-1] 
    
    
            try :
                opts, args = getopt.getopt(argv, "hs:c:f:", ["help", "seprator=","comment=", "file="])
            except getopt.GetoptError,e:
                print str(e)
                print " possible  arguments  -s <key value sperator > -c < comment char >    <file> \n  Try -h or --help "
                sys.exit(2)
    
    
            if os.path.isfile(args[0])==False:
                print "File doesnt exist "
                sys.exit()
    
    
            for opt , arg  in opts :
                if opt in ("-h" , "--help"):
                    print " hg:d  \n -h or --help print usage summary \n -c Specify char that idetifes comment  \n -s Sperator between key and value in prop file \n  specify file  "
                    sys.exit()
                elif opt in ("-s" , "--seprator"):
                    seprator = arg 
                elif opt in ("-c"  , "--comment"):
                    comment  = arg
    
            p = Parsing( seprator, comment , propFile)
            p.parseProp()
    
        if __name__ == "__main__":
                main(sys.argv[1:])
    

Multiplying Two Columns in SQL Server

This code is used to multiply the values of one column

select exp(sum(log(column))) from table

CSS3 selector :first-of-type with class name?

This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.

However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :

:not(.myclass1) + .myclass1

Full working code example:

_x000D_
_x000D_
p:first-of-type {color:blue}_x000D_
p:not(.myclass1) + .myclass1 { color: red }_x000D_
p:not(.myclass2) + .myclass2 { color: green }
_x000D_
<div>_x000D_
  <div>This text should appear as normal</div>_x000D_
  <p>This text should be blue.</p>_x000D_
  <p class="myclass1">This text should appear red.</p>_x000D_
  <p class="myclass2">This text should appear green.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using reCAPTCHA on localhost

Google has recently changed stopped allowing localhost being allowed by default. (as touched upon by @Artur Cesar De Melo)This is under their FAQ's:

I'm getting an error "Localhost is not in the list of supported domains". This was working before, what should I do?

localhost domains are no longer supported by default. If you wish to continue supporting them for development you can add them to the list of supported domains for your site key. Go to the admin console to update your list of supported domains. We advise to use a separate key for development and production and to not allow localhost on your production site key.

1: Create a separate key for your development environment

2: Add 127.0.0.1 to the list of allowed domains

3: Save changes and allow up to 30 mins for changes to take affect

Get decimal portion of a number with JavaScript

This function splits float number into integers and returns it in array:

_x000D_
_x000D_
function splitNumber(num)
{
  num = ("0" + num).match(/([0-9]+)([^0-9]([0-9]+))?/);
  return [ ~~num[1], ~~num[3] ];
}

console.log(splitNumber(3.2));     // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789));     // [ 789, 0 ]
console.log(splitNumber("test"));  // [ 0, 0 ]
_x000D_
_x000D_
_x000D_

You can extend it to only return existing numbers and null if no number exists:

_x000D_
_x000D_
function splitNumber(num)
{
  num = ("" + num).match(/([0-9]+)([^0-9]([0-9]+))?/);
  return [num ? ~~num[1] : null, num && num[3] !== undefined ? ~~num[3] : null];
}

console.log(splitNumber(3.2));     // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789));     // [ 789, null ]
console.log(splitNumber("test"));  // [ null, null ]
_x000D_
_x000D_
_x000D_

Access a URL and read Data with R

Beside of read.csv(url("...")) you also can use read.table("http://...").

Example:

> sample <- read.table("http://www.ats.ucla.edu/stat/examples/ara/angell.txt")
> sample
                V1   V2   V3   V4 V5
1        Rochester 19.0 20.6 15.0  E
2         Syracuse 17.0 15.6 20.2  E
...
43         Atlanta  4.2 70.6 32.6  S
> 

Objective-C for Windows

Get GNUStep here

Get MINGW here

Install MINGW Install GNUStep Then Test

How to store Java Date to Mysql datetime with JPA

mysql datetime -> GregorianCalendar

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2012-12-13 14:54:30"); // mysql datetime format
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());

GregorianCalendar -> mysql datetime

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = format.format(calendar.getTime());
System.out.println(string);

Submit form without reloading page

I guess this is what you need. Try this .

<form action="" method="get">
                <input name="search" type="text">
                <input type="button" value="Search" onclick="return updateTable();">
                </form>

and your javascript code is the same

function updateTable()
    {   
        var photoViewer = document.getElementById('photoViewer');
        var photo = document.getElementById('photo1').href;
        var numOfPics = 5;
        var columns = 3; 
        var rows = Math.ceil(numOfPics/columns);
        var content="";
        var count=0;

        content = "<table class='photoViewer' id='photoViewer'>";
            for (r = 0; r < rows; r++) {
                content +="<tr>";
                for (c = 0; c < columns; c++) {
                    count++;
                    if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
                        content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
                }
                content +="</tr>";
            }
        content += "</table>";

        photoViewer.innerHTML = content; 
}

Python and pip, list all versions of a package that's available?

I came up with dead-simple bash script. Thanks to jq's author.

#!/bin/bash
set -e

PACKAGE_JSON_URL="https://pypi.org/pypi/${1}/json"

curl -L -s "$PACKAGE_JSON_URL" | jq  -r '.releases | keys | .[]' | sort -V

Update:

  • Add sorting by version number.
  • Add -L to follow redirects.

How to list all installed packages and their versions in Python?

Here's a way to do it using PYTHONPATH instead of the absolute path of your python libs dir:

for d in `echo "${PYTHONPATH}" | tr ':' '\n'`; do ls "${d}"; done

[ 10:43 Jonathan@MacBookPro-2 ~/xCode/Projects/Python for iOS/trunk/Python for iOS/Python for iOS ]$ for d in `echo "$PYTHONPATH" | tr ':' '\n'`; do ls "${d}"; done
libpython2.7.dylib pkgconfig          python2.7
BaseHTTPServer.py      _pyio.pyc              cgitb.pyo              doctest.pyo            htmlentitydefs.pyc     mimetools.pyc          plat-mac               runpy.py               stringold.pyc          traceback.pyo
BaseHTTPServer.pyc     _pyio.pyo              chunk.py               dumbdbm.py             htmlentitydefs.pyo     mimetools.pyo          platform.py            runpy.pyc              stringold.pyo          tty.py
BaseHTTPServer.pyo     _strptime.py           chunk.pyc              dumbdbm.pyc            htmllib.py             mimetypes.py           platform.pyc           runpy.pyo              stringprep.py          tty.pyc
Bastion.py             _strptime.pyc          chunk.pyo              dumbdbm.pyo            htmllib.pyc            mimetypes.pyc          platform.pyo           sched.py               stringprep.pyc         tty.pyo
Bastion.pyc            _strptime.pyo          cmd.py
....

How can I select rows with most recent timestamp for each key value?

This can de done in a relatively elegant way using SELECT DISTINCT, as follows:

SELECT DISTINCT ON (sensorID)
sensorID, timestamp, sensorField1, sensorField2 
FROM sensorTable
ORDER BY sensorID, timestamp DESC;

The above works for PostgreSQL (some more info here) but I think also other engines. In case it's not obvious, what this does is sort the table by sensor ID and timestamp (newest to oldest), and then returns the first row (i.e. latest timestamp) for each unique sensor ID.

In my use case I have ~10M readings from ~1K sensors, so trying to join the table with itself on a timestamp-based filter is very resource-intensive; the above takes a couple of seconds.

Enable IIS7 gzip

Configuration

You can enable GZIP compression entirely in your Web.config file. This is particularly useful if you're on shared hosting and can't configure IIS directly, or you want your config to carry between all environments you target.

<system.webServer>
  <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
    <dynamicTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
    </dynamicTypes>
    <staticTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
    </staticTypes>
  </httpCompression>
  <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>

Testing

To test whether compression is working or not, use the developer tools in Chrome or Firebug for Firefox and ensure the HTTP response header is set:

Content-Encoding: gzip

Note that this header won't be present if the response code is 304 (Not Modified). If that's the case, do a full refresh (hold shift or control while you press the refresh button) and check again.

Add text to Existing PDF using Python

If you're on Windows, this might work:

PDF Creator Pilot

There's also a whitepaper of a PDF creation and editing framework in Python. It's a little dated, but maybe can give you some useful info:

Using Python as PDF Editing and Processing Framework

Java: convert List<String> to a String

Code you have is right way to do it if you want to do using JDK without any external libraries. There is no simple "one-liner" that you could use in JDK.

If you can use external libs, I recommend that you look into org.apache.commons.lang.StringUtils class in Apache Commons library.

An example of usage:

List<String> list = Arrays.asList("Bill", "Bob", "Steve");
String joinedResult = StringUtils.join(list, " and ");

Split long commands in multiple lines through Windows batch file

The rule for the caret is:

A caret at the line end, appends the next line, the first character of the appended line will be escaped.

You can use the caret multiple times, but the complete line must not exceed the maximum line length of ~8192 characters (Windows XP, Windows Vista, and Windows 7).

echo Test1
echo one ^
two ^
three ^
four^
*
--- Output ---
Test1
one two three four*

echo Test2
echo one & echo two
--- Output ---
Test2
one
two

echo Test3
echo one & ^
echo two
--- Output ---
Test3
one
two

echo Test4
echo one ^
& echo two
--- Output ---
Test4
one & echo two

To suppress the escaping of the next character you can use a redirection.

The redirection has to be just before the caret. But there exist one curiosity with redirection before the caret.

If you place a token at the caret the token is removed.

echo Test5
echo one <nul ^
& echo two
--- Output ---
Test5
one
two


echo Test6
echo one <nul ThisTokenIsLost^
& echo two
--- Output ---
Test6
one
two

And it is also possible to embed line feeds into the string:

setlocal EnableDelayedExpansion
set text=This creates ^

a line feed
echo Test7: %text%
echo Test8: !text!
--- Output ---
Test7: This creates
Test8: This creates
a line feed

The empty line is important for the success. This works only with delayed expansion, else the rest of the line is ignored after the line feed.

It works, because the caret at the line end ignores the next line feed and escapes the next character, even if the next character is also a line feed (carriage returns are always ignored in this phase).

Using a remote repository with non-standard port

SSH based git access method can be specified in <repo_path>/.git/config using either a full URL or an SCP-like syntax, as specified in http://git-scm.com/docs/git-clone:

URL style:

url = ssh://[user@]host.xz[:port]/path/to/repo.git/

SCP style:

url = [user@]host.xz:path/to/repo.git/

Notice that the SCP style does not allow a direct port change, relying instead on an ssh_config host definition in your ~/.ssh/config such as:

Host my_git_host
HostName git.some.host.org
Port 24589
User not_a_root_user

Then you can test in a shell with:

ssh my_git_host

and alter your SCP-style URI in <repo_path>/.git/config as:

url = my_git_host:path/to/repo.git/

Why does the C++ STL not provide any "tree" containers?

In a way, std::map is a tree (it is required to have the same performance characteristics as a balanced binary tree) but it doesn't expose other tree functionality. The likely reasoning behind not including a real tree data structure was probably just a matter of not including everything in the stl. The stl can be looked as a framework to use in implementing your own algorithms and data structures.

In general, if there's a basic library functionality that you want, that's not in the stl, the fix is to look at BOOST.

Otherwise, there's a bunch of libraries out there, depending on the needs of your tree.

How to pass anonymous types as parameters?

If you know, that your results implements a certain interface you could use the interface as datatype:

public void LogEmployees<T>(IEnumerable<T> list)
{
    foreach (T item in list)
    {

    }
}

Can I use multiple "with"?

Yes - just do it this way:

WITH DependencedIncidents AS
(
  ....
),  
lalala AS
(
  ....
)

You don't need to repeat the WITH keyword

How do I get the color from a hexadecimal color code using .NET?

If you mean HashCode as in .GetHashCode(), I'm afraid you can't go back. Hash functions are not bi-directional, you can go 'forward' only, not back.

Follow Oded's suggestion if you need to get the color based on the hexadecimal value of the color.

Does JavaScript have a built in stringbuilder class?

The ECMAScript 6 version (aka ECMAScript 2015) of JavaScript introduced string literals.

var classType = "stringbuilder";
var q = `Does JavaScript have a built-in ${classType} class?`;

Notice that back-ticks, instead of single quotes, enclose the string.

Vim: insert the same characters across multiple lines

:%s/^/vendor_/

or am I missing something?

Making sure at least one checkbox is checked

Prevent user from deselecting last checked checkbox.
jQuery (original answer).

$('input[type="checkbox"][name="chkBx"]').on('change',function(){
    var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
        return this.value;
    }).toArray();

    if(getArrVal.length){
        //execute the code
        $('#msg').html(getArrVal.toString());

    } else {
        $(this).prop("checked",true);
        $('#msg').html("At least one value must be checked!");
        return false;

    }
});

UPDATED ANSWER 2019-05-31
Plain JS

_x000D_
_x000D_
let i,_x000D_
    el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),_x000D_
    msg = document.getElementById('msg'),_x000D_
    onChange = function(ev){_x000D_
        ev.preventDefault();_x000D_
        let _this = this,_x000D_
            arrVal = Array.prototype.slice.call(_x000D_
                document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))_x000D_
                    .map(function(cur){return cur.value});_x000D_
_x000D_
        if(arrVal.length){_x000D_
            msg.innerHTML = JSON.stringify(arrVal);_x000D_
        } else {_x000D_
            _this.checked=true;_x000D_
            msg.innerHTML = "At least one value must be checked!";_x000D_
        }_x000D_
    };_x000D_
_x000D_
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
_x000D_
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>_x000D_
<div id="msg"></div>
_x000D_
_x000D_
_x000D_

How to read file from res/raw by name

Here is example of taking XML file from raw folder:

 InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML

Then you can:

 String sxml = readTextFile(XmlFileInputStream);

when:

 public String readTextFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {

        }
        return outputStream.toString();
    }

How do I collapse a table row in Bootstrap?

You are using collapse on the div inside of your table row (tr). So when you collapse the div, the row is still there. You need to change it to where your id and class are on the tr instead of the div.

Change this:

<tr><td><div class="collapse out" id="collapseme">Should be collapsed</div></td></tr>

to this:

<tr class="collapse out" id="collapseme"><td><div>Should be collapsed</div></td></tr>

JSFiddle: http://jsfiddle.net/KnuU6/21/

EDIT: If you are unable to upgrade to 3.0.0, I found a JQuery workaround in 2.3.2:

Remove your data-toggle and data-target and add this JQuery to your button.

$(".btn").click(function() {
    if($("#collapseme").hasClass("out")) {
        $("#collapseme").addClass("in");
        $("#collapseme").removeClass("out");
    } else {
        $("#collapseme").addClass("out");
        $("#collapseme").removeClass("in");
    }
});

JSFiddle: http://jsfiddle.net/KnuU6/25/

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

A popular Linux library which has similar functionality would be ncurses.

FIX CSS <!--[if lt IE 8]> in IE

[if lt IE 8] means "if lower than IE8" - and thats why it isn't working in IE8.

wahat you want is [if lte IE 8] which means "if lower than or equal IE8".

How do I pass multiple parameters in Objective-C?

The text before each parameter is part of the method name. From your example, the name of the method is actually

-getBusStops:forTime:

Each : represents an argument. In a method call, the method name is split at the :s and arguments appear after the :s. e.g.

[getBusStops: arg1 forTime: arg2]

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.

The service:

MyApp.service('getData', 
  [
    '$http',
    function($http) {

      this.getQuote = function(ticker) {
        var _url = 'https://www.google.com/finance/info?q=' + ticker;
        return $http.get(_url); //Simply return the promise to the caller
      };
    }
  ]
);

The controller:

MyApp.controller('StockREST', 
  [
    '$scope',
    'getData', //<-- the service above
    function($scope, getData) {
      var getQuote = function(symbol) {
        getData.getQuote(symbol)
        .success(function(response, status, headers, config) {
          var _data = response.substring(4, response.length);
          var _json = JSON.parse(_data);
          $scope.stockQuoteData = _json[0];
          // ticker: $scope.stockQuoteData.t
          // last price: $scope.stockQuoteData.l
          // last updated time: $scope.stockQuoteData.ltt, such as "7:59PM EDT"
          // last updated date & time: $scope.stockQuoteData.lt, such as "Sep 29, 7:59PM EDT"
        })
        .error(function(response, status, headers, config) {
          console.log('@@@ Error: in retrieving Google Finance stock quote, ticker = ' + symbol);
        });
      };

      getQuote($scope.ticker.tick.name); //Initialize
      $scope.getQuote = getQuote; //as defined above
    }
  ]
);

The HTML:

<span>{{stockQuoteData.l}}, {{stockQuoteData.lt}}</span>

At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.

Specify system property to Maven project

If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html

If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.

How do I debug "Error: spawn ENOENT" on node.js?

Step 1: Ensure spawn is called the right way

First, review the docs for child_process.spawn( command, args, options ):

Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.

The third argument is used to specify additional options, which defaults to:

{ cwd: undefined, env: process.env }

Use env to specify environment variables that will be visible to the new process, the default is process.env.

Ensure you are not putting any command line arguments in command and the whole spawn call is valid. Proceed to next step.

Step 2: Identify the Event Emitter that emits the error event

Search on your source code for each call to spawn, or child_process.spawn, i.e.

spawn('some-command', [ '--help' ]);

and attach there an event listener for the 'error' event, so you get noticed the exact Event Emitter that is throwing it as 'Unhandled'. After debugging, that handler can be removed.

spawn('some-command', [ '--help' ])
  .on('error', function( err ){ throw err })
;

Execute and you should get the file path and line number where your 'error' listener was registered. Something like:

/file/that/registers/the/error/listener.js:29
      throw err;
            ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

If the first two lines are still

events.js:72
        throw er; // Unhandled 'error' event

do this step again until they are not. You must identify the listener that emits the error before going on next step.

Step 3: Ensure the environment variable $PATH is set

There are two possible scenarios:

  1. You rely on the default spawn behaviour, so child process environment will be the same as process.env.
  2. You are explicity passing an env object to spawn on the options argument.

In both scenarios, you must inspect the PATH key on the environment object that the spawned child process will use.

Example for scenario 1

// inspect the PATH key on process.env
console.log( process.env.PATH );
spawn('some-command', ['--help']);

Example for scenario 2

var env = getEnvKeyValuePairsSomeHow();
// inspect the PATH key on the env object
console.log( env.PATH );
spawn('some-command', ['--help'], { env: env });

The absence of PATH (i.e., it's undefined) will cause spawn to emit the ENOENT error, as it will not be possible to locate any command unless it's an absolute path to the executable file.

When PATH is correctly set, proceed to next step. It should be a directory, or a list of directories. Last case is the usual.

Step 4: Ensure command exists on a directory of those defined in PATH

Spawn may emit the ENOENT error if the filename command (i.e, 'some-command') does not exist in at least one of the directories defined on PATH.

Locate the exact place of command. On most linux distributions, this can be done from a terminal with the which command. It will tell you the absolute path to the executable file (like above), or tell if it's not found.

Example usage of which and its output when a command is found

> which some-command
some-command is /usr/bin/some-command

Example usage of which and its output when a command is not found

> which some-command
bash: type: some-command: not found

miss-installed programs are the most common cause for a not found command. Refer to each command documentation if needed and install it.

When command is a simple script file ensure it's accessible from a directory on the PATH. If it's not, either move it to one or make a link to it.

Once you determine PATH is correctly set and command is accessible from it, you should be able to spawn your child process without spawn ENOENT being thrown.

Git with SSH on Windows

I've found my ssh.exe in "C:/Program Files/Git/usr/bin" directory

How to write a caption under an image?

To be more semantically correct and answer the OPs orginal question about aligning them side by side I would use this:

HTML

<div class="items">
<figure>
    <img src="hello.png" width="100px" height="100px">
    <figcaption>Caption 1</figcaption>
</figure>
<figure>
    <img src="hi.png" width="100px" height="100px"> 
    <figcaption>Caption 2</figcaption>
</figure></div>

CSS

.items{
text-align:center;
margin:50px auto;}


.items figure{
margin:0px 20px;
display:inline-block;
text-decoration:none;
color:black;}

https://jsfiddle.net/c7borg/jLzc6h72/3/

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

How to beautifully update a JPA entity in Spring Data?

I have encountered this issue!
Luckily, I determine 2 ways and understand some things but the rest is not clear.
Hope someone discuss or support if you know.

  1. Use RepositoryExtendJPA.save(entity).
    Example:
    List<Person> person = this.PersonRepository.findById(0) person.setName("Neo"); This.PersonReository.save(person);
    this block code updated new name for record which has id = 0;
  2. Use @Transactional from javax or spring framework.
    Let put @Transactional upon your class or specified function, both are ok.
    I read at somewhere that this annotation do a "commit" action at the end your function flow. So, every things you modified at entity would be updated to database.

Direct casting vs 'as' operator?

All given answers are good, if i might add something: To directly use string's methods and properties (e.g. ToLower) you can't write:

(string)o.ToLower(); // won't compile

you can only write:

((string)o).ToLower();

but you could write instead:

(o as string).ToLower();

The as option is more readable (at least to my opinion).

Run a script in Dockerfile

In addition to the answers above:

If you created/edited your .sh script file in Windows, make sure it was saved with line ending in Unix format. By default many editors in Windows will convert Unix line endings to Windows format and Linux will not recognize shebang (#!/bin/sh) at the beginning of the file. So Linux will produce the error message like if there is no shebang.

Tips:

  • If you use Notepad++, you need to click "Edit/EOL Conversion/UNIX (LF)"
  • If you use Visual Studio, I would suggest installing "End Of Line" plugin. Then you can make line endings visible by pressing Ctrl-R, Ctrl-W. And to set Linux style endings you can press Ctrl-R, Ctrl-L. For Windows style, press Ctrl-R, Ctrl-C.

Sorting Directory.GetFiles()

The MSDN Documentation states that there is no guarantee of any order on the return values. You have to use the Sort() method.

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

How to find out which package version is loaded in R?

Old question, but not among the answers is my favorite command to get a quick and short overview of all loaded packages:

(.packages())

To see which version is installed of all loaded packages, just use the above command to subset installed.packages().

installed.packages()[(.packages()),3]

By changing the column number (3 for package version) you can get any other information stored in installed.packages() in an easy-to-read matrix. Below is an example for version number and dependency:

installed.packages()[(.packages()),c(3,5)]

Finding duplicate integers in an array and display how many times they occurred

Since you can't use LINQ, you can do this with collections and loops instead:

static void Main(string[] args)
{              
    int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
    var dict = new Dictionary<int, int>();

    foreach(var value in array)
    {
        if (dict.ContainsKey(value))
            dict[value]++;
        else
            dict[value] = 1;
    }

    foreach(var pair in dict)
        Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
    Console.ReadKey();
}

How to Execute SQL Server Stored Procedure in SQL Developer?

    EXECUTE [or EXEC] procedure_name
  @parameter_1_Name = 'parameter_1_Value', 
    @parameter_2_name = 'parameter_2_value',
    @parameter_z_name = 'parameter_z_value'

How to POST raw whole JSON in the body of a Retrofit request?

JSONObject showing error please use

JsonObject paramObject = new JsonObject(); paramObject.addProperty("loginId", vMobile_Email);

Custom Card Shape Flutter SDK

You can also customize the card theme globally with ThemeData.cardTheme:

MaterialApp(
  title: 'savvy',
  theme: ThemeData(
    cardTheme: CardTheme(
      shape: RoundedRectangleBorder(
        borderRadius: const BorderRadius.all(
          Radius.circular(8.0),
        ),
      ),
    ),
    // ...

Maximum call stack size exceeded on npm install

This problem is solved by clearing npm cache and then install re-install npm packages, so to solve this

Run clean the cache

npm cache clean --force

Then This stage is very important

npm rebuild

Finally re-install node modules

npm install

Good Luck

How to change the size of the font of a JLabel to take the maximum size

JLabel label = new JLabel("Hello World");
label.setFont(new Font("Calibri", Font.BOLD, 20));

How to call C++ function from C?

You will have to write a wrapper for C in C++ if you want to do this. C++ is backwards compatible, but C is not forwards compatible.

Creating Accordion Table with Bootstrap

In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:

.collapse-row.collapsed + tr {
     display: none;
}

'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.

Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/

Is it possible to specify the schema when connecting to postgres with JDBC?

DataSourcesetCurrentSchema

When instantiating a DataSource implementation, look for a method to set the current/default schema.

For example, on the PGSimpleDataSource class call setCurrentSchema.

org.postgresql.ds.PGSimpleDataSource dataSource = new org.postgresql.ds.PGSimpleDataSource ( );
dataSource.setServerName ( "localhost" );
dataSource.setDatabaseName ( "your_db_here_" );
dataSource.setPortNumber ( 5432 );
dataSource.setUser ( "postgres" );
dataSource.setPassword ( "your_password_here" );
dataSource.setCurrentSchema ( "your_schema_name_here_" );  // <----------

If you leave the schema unspecified, Postgres defaults to a schema named public within the database. See the manual, section 5.9.2 The Public Schema. To quote hat manual:

In the previous sections we created tables without specifying any schema names. By default such tables (and other objects) are automatically put into a schema named “public”. Every new database contains such a schema.

How do I rename both a Git local and remote branch name?

If you have named a branch incorrectly AND pushed this to the remote repository follow these steps to rename that branch (based on this article):

  1. Rename your local branch:

    • If you are on the branch you want to rename:
      git branch -m new-name

    • If you are on a different branch:
      git branch -m old-name new-name

  2. Delete the old-name remote branch and push the new-name local branch:
    git push origin :old-name new-name

  3. Reset the upstream branch for the new-name local branch:
    Switch to the branch and then:
    git push origin -u new-name

Why is there no SortedList in Java?

JavaFX SortedList

Though it took a while, Java 8 does have a sorted List. http://docs.oracle.com/javase/8/javafx/api/javafx/collections/transformation/SortedList.html

As you can see in the javadocs, it is part of the JavaFX collections, intended to provide a sorted view on an ObservableList.

Update: Note that with Java 11, the JavaFX toolkit has moved outside the JDK and is now a separate library. JavaFX 11 is available as a downloadable SDK or from MavenCentral. See https://openjfx.io

How can you run a Java program without main method?

public class X { static {
  System.out.println("Main not required to print this");
  System.exit(0);
}}

Run from the cmdline with java X.

What causes a SIGSEGV

Here is an example of SIGSEGV.

root@pierr-desktop:/opt/playGround# cat test.c
int main()
{
     int * p ;
     * p = 0x1234;
     return 0 ;
}
root@pierr-desktop:/opt/playGround# g++ -o test test.c  
root@pierr-desktop:/opt/playGround# ./test 
Segmentation fault

And here is the detail.

How to handle it?

  1. Avoid it as much as possible in the first place.

    Program defensively: use assert(), check for NULL pointer , check for buffer overflow.

    Use static analysis tools to examine your code.

    compile your code with -Werror -Wall.

    Has somebody review your code.

  2. When that actually happened.

    Examine you code carefully.

    Check what you have changed since the last time you code run successfully without crash.

    Hopefully, gdb will give you a call stack so that you know where the crash happened.


EDIT : sorry for a rush. It should be *p = 0x1234; instead of p = 0x1234;

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

How/When does Execute Shell mark a build as failure in Jenkins?

In my opinion, turning off the -e option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.

If you have a line in your script where failure is expected, like a grep or a find, then just add || true to the end of that line. That ensures that line will always return success.

If you need to use that exit code, you can either hoist the command into your if statement:

grep foo bar; if [ $? == 0 ]; then ...    -->   if grep foo bar; then ...

Or you can capture the return code in your || clause:

grep foo bar || ret=$?

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

calling java methods in javascript code

Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

How do I change the value of a global variable inside of a function

var a = 10;

myFunction(a);

function myFunction(a){
   window['a'] = 20; // or window.a
}

alert("Value of 'a' outside the function " + a); //outputs 20

With window['variableName'] or window.variableName you can modify the value of a global variable inside a function.

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

Get ASCII value at input word

simply do

int a = ch

(also this has nothing to do with android)

Flexbox not working in Internet Explorer 11

See "Can I Use" for the full list of IE11 Flexbox bugs and more

There are numerous Flexbox bugs in IE11 and other browsers - see flexbox on Can I Use -> Known Issues, where the following are listed under IE11:

  • IE 11 requires a unit to be added to the third argument, the flex-basis property
  • In IE10 and IE11, containers with display: flex and flex-direction: column will not properly calculate their flexed childrens' sizes if the container has min-height but no explicit height property
  • IE 11 does not vertically align items correctly when min-height is used

Also see Philip Walton's Flexbugs list of issues and workarounds.

Is there a float input type in HTML5?

Via: http://blog.isotoma.com/2012/03/html5-input-typenumber-and-decimalsfloats-in-chrome/

But what if you want all the numbers to be valid, integers and decimals alike? In this case, set step to “any”

<input type="number" step="any" />

Works for me in Chrome, not tested in other browsers.

multiple where condition codeigniter

Yes, multiple calls to where() is a perfectly valid way to achieve this.

$this->db->where('username',$username);
$this->db->where('status',$status);

http://www.codeigniter.com/user_guide/database/query_builder.html

Unable to resolve host "<insert URL here>" No address associated with hostname

If you see this intermittently on wifi or LAN, but your mobile internet connection seems ok, it is most likely your ISP's cheap gateway router is experiencing high traffic load.

You should trap these errors and display a reminder to the user to close any other apps using the network.

Test by running a couple of HD youtube videos on your desktop to reproduce, or just go to a busy Starbucks.

Java logical operator short-circuiting

The && and || operators "short-circuit", meaning they don't evaluate the right-hand side if it isn't necessary.

The & and | operators, when used as logical operators, always evaluate both sides.

There is only one case of short-circuiting for each operator, and they are:

  • false && ... - it is not necessary to know what the right-hand side is because the result can only be false regardless of the value there
  • true || ... - it is not necessary to know what the right-hand side is because the result can only be true regardless of the value there

Let's compare the behaviour in a simple example:

public boolean longerThan(String input, int length) {
    return input != null && input.length() > length;
}

public boolean longerThan(String input, int length) {
    return input != null & input.length() > length;
}

The 2nd version uses the non-short-circuiting operator & and will throw a NullPointerException if input is null, but the 1st version will return false without an exception.

Android WebView, how to handle redirects in app instead of opening a browser

Create a class that implements webviewclient and add the following code that allows ovveriding the url string as shown below. You can see these [example][1]

public class myWebClient extends WebViewClient {

    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         view.loadUrl(url); 
         return true;
     }
}

On your constructor, create a webview object as shown below.

   web = new WebView(this); web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); 

Then add the following code to perform loading of urls inside your app

       WebSettings settings=web.getSettings(); 
    settings.setJavaScriptEnabled(true); 
    
    web.loadUrl("http://www.facebook.com");
    web.setWebViewClient(new myWebClient()); 
   
 web.setWebChromeClient(new WebChromeClient() {
      // 
      //
    }

Is it a good practice to use try-except-else in Python?

Is it a good practice to use try-except-else in python?

The answer to this is that it is context dependent. If you do this:

d = dict()
try:
    item = d['item']
except KeyError:
    item = 'default'

It demonstrates that you don't know Python very well. This functionality is encapsulated in the dict.get method:

item = d.get('item', 'default')

The try/except block is a much more visually cluttered and verbose way of writing what can be efficiently executing in a single line with an atomic method. There are other cases where this is true.

However, that does not mean that we should avoid all exception handling. In some cases it is preferred to avoid race conditions. Don't check if a file exists, just attempt to open it, and catch the appropriate IOError. For the sake of simplicity and readability, try to encapsulate this or factor it out as apropos.

Read the Zen of Python, understanding that there are principles that are in tension, and be wary of dogma that relies too heavily on any one of the statements in it.

Counting the number of files in a directory using Java

This might not be appropriate for your application, but you could always try a native call (using jni or jna), or exec a platform-specific command and read the output before falling back to list().length. On *nix, you could exec ls -1a | wc -l (note - that's dash-one-a for the first command, and dash-lowercase-L for the second). Not sure what would be right on windows - perhaps just a dir and look for the summary.

Before bothering with something like this I'd strongly recommend you create a directory with a very large number of files and just see if list().length really does take too long. As this blogger suggests, you may not want to sweat this.

I'd probably go with Varkhan's answer myself.

angular2 submit form by pressing enter without submit button

add this inside your input tag

<input type="text" (keyup.enter)="yourMethod()" />

Fixed point vs Floating point number

Take the number 123.456789

  • As an integer, this number would be 123
  • As a fixed point (2), this number would be 123.46 (Assuming you rounded it up)
  • As a floating point, this number would be 123.456789

Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer..

Find a value in DataTable

A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.

Looking at your requirement your filterexpression will have to be somewhat general to make this work.

myDataTable.Select("columnName1 like '%" + value + "%'");

MySQL: #126 - Incorrect key file for table

I know that this is an old topic but none of the solution mentioned worked for me. I have done something else that worked:

You need to:

  1. stop the MySQL service:
  2. Open mysql\data
  3. Remove both ib_logfile0 and ib_logfile1.
  4. Restart the service

var functionName = function() {} vs function functionName() {}

The first one is an Anonymous Function Expression:

var functionOne = function() {
  // some code
};

While the second one is a Function Declaration:

function functionTwo () {
  // some code
}

The main clear difference between both is the function name since Anonymous Functions have no name to call.

Named Functions Vs. Anonymous Functions

The anonymous function is quick and easy to type, and many libraries and tools tend to encourage this idiomatic style of code. However, anonymous functions have some drawbacks:

  • Readability: anonymous functions omit a name which could cause less readable code.

  • Debugging: anonymous functions have no name in stack traces, which can make debugging more difficult.

  • Self-Reference: what if the function needs to refer to itself, for recursion for example.

Naming Function Expression:

Providing a name for your function expression quite effectively addresses all these drawbacks, and has no tangible downsides. The best practice is to always name your function expressions:

setTimeout(function timeHandler() { // <-- look, a name here!
  console.log("I've waited 1 second");
}, 1000);

Naming IIFEs (Immediate Invoked Function Expression):

(function IIFE(str) { // <-- look, always name IIFEs!
  console.log(str); // "Hello!"
})('Hello!');

For functions assigned to a variable, naming the function, in this case, is not very common and may cause confusion, in this case, the arrow function may be a better choice.

Android - SMS Broadcast receiver

Also note that the Hangouts application will currently block my BroadcastReceiver from receiving SMS messages. I had to disable SMS functionality in the Hangouts application (Settings->SMS->Turn on SMS), before my SMS BroadcastReceived started getting fired.

Edit: It appears as though some applications will abortBroadcast() on the intent which will prevent other applications from receiving the intent. The solution is to increase the android:priority attribute in the intent-filter tag:

<receiver android:name="com.company.application.SMSBroadcastReceiver" >
  <intent-filter android:priority="500">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
  </intent-filter>
</receiver>

See more details here: Enabling SMS support in Hangouts 2.0 breaks the BroadcastReceiver of SMS_RECEIVED in my app

Symfony - generate url with parameter in controller

It's pretty simple :

public function myAction()
{
    $url = $this->generateUrl('blog_show', array('slug' => 'my-blog-post'));
}

Inside an action, $this->generateUrl is an alias that will use the router to get the wanted route, also you could do this that is the same :

$this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));

Ternary operator (?:) in Bash

The let command supports most of the basic operators one would need:

let a=b==5?c:d;

Naturally, this works only for assigning variables; it cannot execute other commands.

Regex to match only letters

You would use

/[a-z]/gi

[]--checks for any characters between given inputs

a-z---covers the entire alphabet

g-----globally throughout the whole string

i-----getting upper and lowercase

How to avoid annoying error "declared and not used"

I ran into this issue when I wanted to temporarily disable the sending of an email while working on another part of the code.

Commenting the use of the service triggered a lot of cascade errors, so instead of commenting I used a condition

if false {
    // Technically, svc still be used so no yelling
    _, err = svc.SendRawEmail(input) 
    Check(err)
}

How to call jQuery function onclick?

try this:

$('form').submit(function(){
    // this function will be raised when submit button is clicked.
    // perform submit operations here
});

Issue with virtualenv - cannot activate

For windows, type "C:\Users\Sid\venv\FirstProject\Scripts\activate" in the terminal without quotes. Simply give the location of your Scripts folder in your project. So, the command will be location_of_the_Scripts_Folder\activate.enter image description here

Changing nav-bar color after scrolling?

window.addEventListener('scroll', function (e) {
        var nav = document.getElementById('nav');
        if (document.documentElement.scrollTop || document.body.scrollTop > window.innerHeight) {
                nav.classList.add('nav-colored');
                nav.classList.remove('nav-transparent');
            } else {
                nav.classList.add('nav-transparent');
                nav.classList.remove('nav-colored');
            }
    });

best approach to use event listener. especially for Firefox browser, check this doc Scroll-linked effects and Firefox is no longer support document.body.scrollTop and alternative to use document.documentElement.scrollTop. This is completes the answer from Yahya Essam

How to use MySQL DECIMAL?

There are correct solutions in the comments, but to summarize them into a single answer:

You have to use DECIMAL(6,4).

Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.

How do I print bold text in Python?

Assuming that you really mean "print" on a real printing terminal:

>>> text = 'foo bar\r\noof\trab\r\n'
>>> ''.join(s if i & 1 else (s + '\b' * len(s)) * 2 + s
...         for i, s in enumerate(re.split(r'(\s+)', text)))
'foo\x08\x08\x08foo\x08\x08\x08foo bar\x08\x08\x08bar\x08\x08\x08bar\r\noof\x08\
x08\x08oof\x08\x08\x08oof\trab\x08\x08\x08rab\x08\x08\x08rab\r\n'

Just send that to your stdout.

How to set image name in Dockerfile?

How to build an image with custom name without using yml file:

docker build -t image_name .

How to run a container with custom name:

docker run -d --name container_name image_name

iOS Launching Settings -> Restrictions URL Scheme

As of iOS10 you can use

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root")!) 

to open general settings.

also you can add known urls(you can see them in the most upvoted answer) to it to open specific settings. For example the below one opens touchID and passcode.

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root=TOUCHID_PASSCODE")!)

Add or change a value of JSON key with jquery or javascript

Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:

data.busNum = 12345;
...

How to underline a UILabel in swift?

Swift 5 & 4.2 one liner:

label.attributedText = NSAttributedString(string: "Text", attributes:
    [.underlineStyle: NSUnderlineStyle.single.rawValue])

Swift 4 one liner:

label.attributedText = NSAttributedString(string: "Text", attributes:
    [.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])

Swift 3 one liner:

label.attributedText = NSAttributedString(string: "Text", attributes:
      [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])

How to position text over an image in css

as of 2017 this is more responsive and worked for me. This is for putting text inside vs over, like a badge. instead of the number 8, I had a variable to pull data from a database.

this code started with Kailas's answer up above

https://jsfiddle.net/jim54729/memmu2wb/3/

My HTML

<div class="containerBox">
  <img class="img-responsive"    src="https://s20.postimg.org/huun8e6fh/Gold_Ring.png">
  <div class='text-box'>
   <p class='dataNumber'> 8 </p>
  </div>
</div>

and my css:

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  height: 120px;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}

How to create empty constructor for data class in Kotlin Android

If you give a default value to each primary constructor parameter:

data class Item(var id: String = "",
            var title: String = "",
            var condition: String = "",
            var price: String = "",
            var categoryId: String = "",
            var make: String = "",
            var model: String = "",
            var year: String = "",
            var bodyStyle: String = "",
            var detail: String = "",
            var latitude: Double = 0.0,
            var longitude: Double = 0.0,
            var listImages: List<String> = emptyList(),
            var idSeller: String = "")

and from the class where the instances you can call it without arguments or with the arguments that you have that moment

var newItem = Item()

var newItem2 = Item(title = "exampleTitle",
            condition = "exampleCondition",
            price = "examplePrice",
            categoryId = "exampleCategoryId")

Including non-Python files with setup.py

I just wanted to follow up on something I found working with Python 2.7 on Centos 6. Adding the package_data or data_files as mentioned above did not work for me. I added a MANIFEST.IN with the files I wanted which put the non-python files into the tarball, but did not install them on the target machine via RPM.

In the end, I was able to get the files into my solution using the "options" in the setup/setuptools. The option files let you modify various sections of the spec file from setup.py. As follows.

from setuptools import setup


setup(
    name='theProjectName',
    version='1',
    packages=['thePackage'],
    url='',
    license='',
    author='me',
    author_email='[email protected]',
    description='',
    options={'bdist_rpm': {'install_script': 'filewithinstallcommands'}},
)

file - MANIFEST.in:

include license.txt

file - filewithinstallcommands:

mkdir -p $RPM_BUILD_ROOT/pathtoinstall/
#this line installs your python files
python setup.py install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES
#install license.txt into /pathtoinstall folder
install -m 700 license.txt $RPM_BUILD_ROOT/pathtoinstall/
echo /pathtoinstall/license.txt >> INSTALLED_FILES

What is move semantics?

If you are really interested in a good, in-depth explanation of move semantics, I'd highly recommend reading the original paper on them, "A Proposal to Add Move Semantics Support to the C++ Language."

It's very accessible and easy to read and it makes an excellent case for the benefits that they offer. There are other more recent and up to date papers about move semantics available on the WG21 website, but this one is probably the most straightforward since it approaches things from a top-level view and doesn't get very much into the gritty language details.

How to Export-CSV of Active Directory Objects?

the first command is correct but change from convert to export to csv, as below,

Get-ADUser -Filter * -Properties * `
    | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
    | Sort-Object -Property Name `
    | Export-Csv -path  C:\Users\*\Desktop\file1.csv

HttpServletRequest to complete URL

I use this method:

public static String getURL(HttpServletRequest req) {

    String scheme = req.getScheme();             // http
    String serverName = req.getServerName();     // hostname.com
    int serverPort = req.getServerPort();        // 80
    String contextPath = req.getContextPath();   // /mywebapp
    String servletPath = req.getServletPath();   // /servlet/MyServlet
    String pathInfo = req.getPathInfo();         // /a/b;c=123
    String queryString = req.getQueryString();          // d=789

    // Reconstruct original requesting URL
    StringBuilder url = new StringBuilder();
    url.append(scheme).append("://").append(serverName);

    if (serverPort != 80 && serverPort != 443) {
        url.append(":").append(serverPort);
    }

    url.append(contextPath).append(servletPath);

    if (pathInfo != null) {
        url.append(pathInfo);
    }
    if (queryString != null) {
        url.append("?").append(queryString);
    }
    return url.toString();
}

jQuery selector for the label of a checkbox

This should do it:

$("label[for=comedyclubs]")

If you have non alphanumeric characters in your id then you must surround the attr value with quotes:

$("label[for='comedy-clubs']")

How to turn a string formula into a "real" formula

UPDATE This used to work (in 2007, I believe), but does not in Excel 2013.

EXCEL 2013:

This isn't quite the same, but if it's possible to put 0.4 in one cell (B1, say), and the text value A1 in another cell (C1, say), in cell D1, you can use =B1*INDIRECT(C1), which results in the calculation of 0.4 * A1's value.

So, if A1 = 10, you'd get 0.4*10 = 4 in cell D1. I'll update again if I can find a better 2013 solution, and sorry the Microsoft destroyed the original functionality of INDIRECT!

EXCEL 2007 version:

For a non-VBA solution, use the INDIRECT formula. It takes a string as an argument and converts it to a cell reference.

For example, =0.4*INDIRECT("A1") will return the value of 0.4 * the value that's in cell A1 of that worksheet.

If cell A1 was, say, 10, then =0.4*INDIRECT("A1") would return 4.

Convert floating point number to a certain precision, and then copy to string

Using round:

>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

I suggest you use TO_CHAR() when converting to string. In order to do that, you need to build a date first.

SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
    (SELECT EXTRACT( DAY FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
        FROM DUAL
        )) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )), 09) AS MONTH, EXTRACT(YEAR FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )) AS YEAR
    FROM DUAL
    );

System.Net.WebException: The remote name could not be resolved:

Open the hosts file located at : **C:\windows\system32\drivers\etc**.

Hosts file is for what?

Add the following at end of this file :

YourServerIP YourDNS

Example:

198.168.1.1 maps.google.com

Adding close button in div to close the box

it's easy with the id of the div container : (I didn't put the close button inside the <a> because that's does work properly on all browser.

<div id="myDiv">
<button class="close" onclick="document.getElementById('myDiv').style.display='none'" >Close</button>
<a class="fragment" href="http://google.com">
    <div>
    <img src ="http://placehold.it/116x116" alt="some description"/> 
    <h3>the title will go here</h3>
        <h4> www.myurlwill.com </h4>
    <p class="text">
        this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc 
    </p>
</div>
</a>
</div>

String comparison - Android

This one work for me:

 if (email.equals("[email protected]") && pass.equals("123ss") ){
        Toast.makeText(this,"Logged in",Toast.LENGTH_LONG).show();
    }
    else{

        Toast.makeText(this,"Logged out",Toast.LENGTH_LONG).show();
    }

How can I find the dimensions of a matrix in Python?

If you are using NumPy arrays, shape can be used. For example

  >>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
  >>> a
  array([[[ 1,  2,  3],
         [ 1,  2,  3]],

         [[12,  3,  4],
         [ 2,  1,  3]]])
 >>> a.shape
 (2, 2, 3)

Fixed page header overlaps in-page anchors

You can do this with jQuery:

var offset = $('.target').offset();
var scrollto = offset.top - 50; // fixed_top_bar_height = 50px
$('html, body').animate({scrollTop:scrollto}, 0);

How to send a POST request from node.js Express?

As described here for a post request :

var http = require('http');

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

callback = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();

Pandas Merge - How to avoid duplicating columns

This is a bit of going around the problem, but I have written a function that basically deals with the extra columns:

def merge_fix_cols(df_company,df_product,uniqueID):
    
    df_merged = pd.merge(df_company,
                         df_product,
                         how='left',left_on=uniqueID,right_on=uniqueID)    
    for col in df_merged:
        if col.endswith('_x'):
            df_merged.rename(columns = lambda col:col.rstrip('_x'),inplace=True)
        elif col.endswith('_y'):
            to_drop = [col for col in df_merged if col.endswith('_y')]
            df_merged.drop(to_drop,axis=1,inplace=True)
        else:
            pass
    return df_merged

Seems to work well with my merges!

How to call a method after a delay in Android

There are a lot of ways to do this but the best is to use handler like below

long millisecDelay=3000

Handler().postDelayed({
  // do your work here
 },millisecDelay)

Set NOW() as Default Value for datetime datatype?

ALTER TABLE table_name
  CHANGE COLUMN date_column_name date_column_name DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Finally, This worked for me!

Jquery change background color

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

The .queue() function waits for running animations to run out and then fires whatever's in the supplied function.

ConfigurationManager.AppSettings - How to modify and save?

I think the problem is that in the debug visual studio don't use the normal exeName.

it use indtead "NameApplication".host.exe

so the name of the config file is "NameApplication".host.exe.config and not "NameApplication".exe.config

and after the application close - it return to the back app.config

so if you check the wrong file or you check on the wrong time you will see that nothing changed.

How to delete last character from a string using jQuery?

You can also try this in plain javascript

"1234".slice(0,-1)

the negative second parameter is an offset from the last character, so you can use -2 to remove last 2 characters etc

How to get the selected item of a combo box to a string variable in c#

SelectedText = this.combobox.SelectionBoxItem.ToString();

Recursively look for files with a specific extension

find $directory -type f -name "*.in"

is a bit shorter than that whole thing (and safer - deals with whitespace in filenames and directory names).

Your script is probably failing for entries that don't have a . in their name, making $extension empty.

Decreasing height of bootstrap 3.0 navbar

If you guys are generating your stylesheets with LESS/SASS and are importing Bootstrap there, I've found that overriding the @navbar-height variable lets your set the height of the navbar, which is originally defined in the variables.less file.

enter image description here

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

As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

./configure --prefix ...

The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

I have to keep a separate virtual machine with everything installed for my recompilation purposes.

How to make two plots side-by-side using Python?

You can use - matplotlib.gridspec.GridSpec

Check - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html

The below code displays a heatmap on right and an Image on left.

#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2) 
fig = plt.figure(figsize=(25,3))

#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)

#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])

#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")

plt.imshow(image)
plt.show()

Output image

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

On my execution of openssl pkcs12 -export -out cacert.pkcs12 -in testca/cacert.pem, I received the following message:

unable to load private key 140707250050712:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: ANY PRIVATE KEY`

Got this solved by providing the key file along with the command. The switch is -inkey inkeyfile.pem

How to get input type using jquery?

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
          $(".show-pwd").click(function(){
          alert();
            var x = $("#myInput");
            if (x[0].type === "password") {
              x[0].type = "text";
            } else {
              x[0].type = "password";
            }
          });
        });
    </script>
</head>

<body>
    <p>Click the radio button to toggle between password visibility:</p>Password:
    <input type="password" value="FakePSW" id="myInput">
    <br>
    <br>
    <input type="checkbox" class="show-pwd">Show Password</body>

</html>

Finding last occurrence of substring in string, replacing that

Naïve approach:

a = "A long string with a . in the middle ending with ."
fchar = '.'
rchar = '. -'
a[::-1].replace(fchar, rchar[::-1], 1)[::-1]

Out[2]: 'A long string with a . in the middle ending with . -'

Aditya Sihag's answer with a single rfind:

pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]

How to set username and password for SmtpClient object in .NET?

Since not all of my clients use authenticated SMTP accounts, I resorted to using the SMTP account only if app key values are supplied in web.config file.

Here is the VB code:

sSMTPUser = ConfigurationManager.AppSettings("SMTPUser")
sSMTPPassword = ConfigurationManager.AppSettings("SMTPPassword")

If sSMTPUser.Trim.Length > 0 AndAlso sSMTPPassword.Trim.Length > 0 Then
    NetClient.Credentials = New System.Net.NetworkCredential(sSMTPUser, sSMTPPassword)

    sUsingCredentialMesg = "(Using Authenticated Account) " 'used for logging purposes
End If

NetClient.Send(Message)

fork() child and parent processes

It is printing twice because you are calling printf twice, once in the execution of your program and once in the fork. Try taking your fork() out of the printf call.

Weird PHP error: 'Can't use function return value in write context'

The problem is in the () you have to go []

if (isset($_POST('sms_code') == TRUE)

by

if (isset($_POST['sms_code'] == TRUE)

How to setup FTP on xampp

XAMPP comes preloaded with the FileZilla FTP server. Here is how to setup the service, and create an account.

  1. Enable the FileZilla FTP Service through the XAMPP Control Panel to make it startup automatically (check the checkbox next to filezilla to install the service). Then manually start the service.

  2. Create an ftp account through the FileZilla Server Interface (its the essentially the filezilla control panel). There is a link to it Start Menu in XAMPP folder. Then go to Users->Add User->Stuff->Done.

  3. Try connecting to the server (localhost, port 21).

COALESCE with Hive SQL

Hive supports bigint literal since 0.8 version. So, additional "L" is enough:

COALESCE(column, 0L)

What is the correct JSON content type?

As some research,

Most commonly MIME type is

application/json

Let's see a example to differentiate with json and javascript.

  • application/json

It is used when it is not known how this data will be used. When the information is to be just extracted from the server in JSON format, it may be through a link or from any file, in that case, it is used.

For example-

<?php 
  
header('Content-type:application/json');     
   
$directory =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

    
// Showing the json data 

echo json_encode($directory);     


   ?>

Output is,

[{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}]

  • application/javascript

it is used when the use of the data is predefined. It is used by applications in which there are calls by the client-side ajax applications. It is used when the data is of type JSON-P or JSONP. 

For example

<?php 

header('Content-type:application/javascript'); 

$dir =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

echo "Function_call(".json_encode($dir).");"; 

  

?> 

Output is,

Function_call([{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}])

And for other MIME Types see full detail here,

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types

Python Set Comprehension

primes = {x for x in range(2, 101) if all(x%y for y in range(2, min(x, 11)))}

I simplified the test a bit - if all(x%y instead of if not any(not x%y

I also limited y's range; there is no point in testing for divisors > sqrt(x). So max(x) == 100 implies max(y) == 10. For x <= 10, y must also be < x.

pairs = {(x, x+2) for x in primes if x+2 in primes}

Instead of generating pairs of primes and testing them, get one and see if the corresponding higher prime exists.

"webxml attribute is required" error in Maven

It does look like you have web.xml in the right location, but even so, this error is often caused by the directory structure not matching what Maven expects to see. For example, if you start out with an Eclipse webapp that you are trying to build with Maven.

If that is the issue, a quick fix is to create a
src/main/java and a
src/main/webapp directory (and other directories if you need them) and just move your files.

Here is an overview of the maven directory layout: http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

The split() method in Java does not work on a dot (.)

java.lang.String.split splits on regular expressions, and . in a regular expression means "any character".

Try temp.split("\\.").

C++ Returning reference to local variable

A local variable is memory on the stack, that memory is not automatically invalidated when you go out of scope. From a Function deeper nested (higher on the stack in memory), its perfectly safe to access this memory.

Once the Function returns and ends though, things get dangerous. Usually the memory is not deleted or overwritten when you return, meaning the memory at that adresss is still containing your data - the pointer seems valid.

Until another function builds up the stack and overwrites it. This is why this can work for a while - and then suddenly cease to function after one particularly deeply nested set of functions, or a function with really huge sized or many local objects, reaches that stack-memory again.

It even can happen that you reach the same program part again, and overwrite your old local function variable with the new function variable. All this is very dangerous and should be heavily discouraged. Do not use pointers to local objects!

How do I include image files in Django templates?

If you give the address of online image in your django project it will work. that is working for me. You should take a shot.