Programs & Examples On #Focusrect

C# : changing listbox row color?

You will need to draw the item yourself. Change the DrawMode to OwnerDrawFixed and handle the DrawItem event.

/// <summary>
/// Handles the DrawItem event of the listBox1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.DrawItemEventArgs"/> instance containing the event data.</param>
private void listBox1_DrawItem( object sender, DrawItemEventArgs e )
{
   e.DrawBackground();
   Graphics g = e.Graphics;

    // draw the background color you want
    // mine is set to olive, change it to whatever you want
    g.FillRectangle( new SolidBrush( Color.Olive), e.Bounds );

    // draw the text of the list item, not doing this will only show
    // the background color
    // you will need to get the text of item to display
    g.DrawString( THE_LIST_ITEM_TEXT , e.Font, new SolidBrush( e.ForeColor ), new PointF( e.Bounds.X, e.Bounds.Y) );

    e.DrawFocusRectangle();
}

How do I execute a file in Cygwin?

Just call it

> a

Make sure it will be found (path).

Javascript Cookie with no expiration date

YOU JUST CAN'T. There's no exact code to use for setting a forever cookie but an old trick will do, like current time + 10 years.

Just a note that any dates beyond January 2038 will doomed you for the cookies (32-bit int) will be deleted instantly. Wish for a miracle that that will be fixed in the near future. For 64-bit int, years around 2110 will be safe. As time goes by, software and hardware will change and may never adapt to older ones (the things we have now) so prepare the now for the future.

See Year 2038 problem

Convert String into a Class Object

You can use the statement :-

Class c = s.getClass();

To get the class instance.

Comparing chars in Java

The first statement you have is probably not what you want... 'A'|'B'|'C' is actually doing bitwise operation :)

Your second statement is correct, but you will have 21 ORs.

If the 21 characters are "consecutive" the above solutions is fine.

If not you can pre-compute a hash set of valid characters and do something like

if (validCharHashSet.contains(symbol))...

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

PHP - Copy image to my server direct from URL

$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);

you must have allow_url_fopen set to on

Why is super.super.method(); not allowed in Java?

@Jon Skeet Nice explanation. IMO if some one wants to call super.super method then one must be want to ignore the behavior of immediate parent, but want to access the grand parent behavior. This can be achieved through instance Of. As below code

public class A {
    protected void printClass() {
        System.out.println("In A Class");
    }
}

public class B extends A {

    @Override
    protected void printClass() {
        if (!(this instanceof C)) {
            System.out.println("In B Class");
        }
        super.printClass();
    }
}

public class C extends B {
    @Override
    protected void printClass() {
        System.out.println("In C Class");
        super.printClass();
    }
}

Here is driver class,

public class Driver {
    public static void main(String[] args) {
        C c = new C();
        c.printClass();
    }
}

Output of this will be

In C Class
In A Class

Class B printClass behavior will be ignored in this case. I am not sure about is this a ideal or good practice to achieve super.super, but still it is working.

Multiple GitHub Accounts & SSH Config

A possibly simpler alternative to editing the ssh config file (as suggested in all other answers), is to configure an individual repository to use a different (e.g. non-default) ssh key.

Inside the repository for which you want to use a different key, run:

git config core.sshCommand 'ssh -i ~/.ssh/id_rsa_anotheraccount'

If your key is passhprase-protected and you don't want to type your password every time, you have to add it to the ssh-agent. Here's how to do it for ubuntu and here for macOS.

It should also be possible to scale this approach to multiple repositories using global git config and conditional includes (see example).

chai test array equality doesn't work as expected

For expect, .equal will compare objects rather than their data, and in your case it is two different arrays.

Use .eql in order to deeply compare values. Check out this link.
Or you could use .deep.equal in order to simulate same as .eql.
Or in your case you might want to check .members.

For asserts you can use .deepEqual, link.

How to add a hook to the application context initialization event?

Since Spring 4.2 you can use @EventListener (documentation)

@Component
class MyClassWithEventListeners {

    @EventListener({ContextRefreshedEvent.class})
    void contextRefreshedEvent() {
        System.out.println("a context refreshed event happened");
    }
}

jquery how to use multiple ajax calls one after the end of the other

Wrap each ajax call in a named function and just add them to the success callbacks of the previous call:

function callA() {
    $.ajax({
    ...
    success: function() {
      //do stuff
      callB();
    }
    });
}

function callB() {
    $.ajax({
    ...
    success: function() {
        //do stuff
        callC();
    }
    });
}

function callC() {
    $.ajax({
    ...
    });
}


callA();

css - position div to bottom of containing div

.outside {
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Needs to be

.outside {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.

OTP (token) should be automatically read from the message

I implemented something of that such. But, here is what I did when the message comes in, I retrieve only the six digit code, bundle it in an intent and send it to the activity or fragment needing it and verifies the code. The example shows you the way to get the sms already. Look at the code below for illustration on how to send using LocalBrodcastManager and if your message contains more texts E.g Greetings, standardize it to help you better. E.g "Your verification code is: 84HG73" you can create a regex pattern like this ([0-9]){2}([A-Z]){2}([0-9]){2} which means two ints, two [capital] letters and two ints. Good Luck!

After discarding all un needed info from the message

 Intent intent = new Intent("AddedItem");
 intent.putExtra("items", code);
 LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent); 

And the Fragment/Activity receiving it

@Override
public void onResume() {
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter("AddedItem"));
    super.onResume();
}

@Override
public void onPause() {
    super.onDestroy();
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
}

And the code meant to handle the payload you collected

 private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction()) {
            final String message = intent.getStringExtra("message");
            //Do whatever you want with the code here
        }
    }
};

Does that help a little bit. I did it better by using Callbacks

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.

Personally, I wouldn't bother; I'd just rename the column.

PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.

C# static class constructor

C# has a static constructor for this purpose.

static class YourClass
{
    static YourClass()
    {
        // perform initialization here
    }
}

From MSDN:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced

MSDN link

.

Changing Tint / Background color of UITabBar

Following is the perfect solution for this. This works fine with me for iOS5 and iOS4.

//---- For providing background image to tabbar
UITabBar *tabBar = [tabBarController tabBar]; 

if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
    // ios 5 code here
    [tabBar setBackgroundImage:[UIImage imageNamed:@"image.png"]];
} 
else {
    // ios 4 code here
    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
    UIImage *tabbag_image = [UIImage imageNamed:@"image.png"];
    UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
    tabbg_view.backgroundColor = tabbg_color;
    [tabBar insertSubview:tabbg_view atIndex:0];
}

What is String pool in Java?

This prints true (even though we don't use equals method: correct way to compare strings)

    String s = "a" + "bc";
    String t = "ab" + "c";
    System.out.println(s == t);

When compiler optimizes your string literals, it sees that both s and t have same value and thus you need only one string object. It's safe because String is immutable in Java.
As result, both s and t point to the same object and some little memory saved.

Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

iOS Simulator to test website on Mac

You can check and use their free trial browserstack , saucelabs or browser shots I know this is a very old question and I am answering too late and today there are many options available but may be someone get this usefull.

How can I make visible an invisible control with jquery? (hide and show not work)

It's been more than 10 years and not sure if anyone still finding this question or answer relevant.

But a quick workaround is just to wrap the asp control within a html container

<div id="myElement" style="display: inline-block">
   <asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>

Whenever the Javascript Event is triggered, if it needs to be an event by the asp control, just wrap the asp control around the div container.

<div id="testG">  
   <asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>

The jQuery Code is below:

$(document).ready(function () {
    $("#testG").click(function () {
                $("#myElement").css("display", "none");
     });
});

How to get javax.comm API?

On ubuntu

 sudo apt-get install librxtx-java then 

add RXTX jars to the project which are in

 usr/share/java

What is the regex for "Any positive integer, excluding 0"

Try this one, this one works best to suffice the requiremnt.

[1-9][0-9]*

Here is the sample output

String 0 matches regex: false
String 1 matches regex: true
String 2 matches regex: true
String 3 matches regex: true
String 4 matches regex: true
String 5 matches regex: true
String 6 matches regex: true
String 7 matches regex: true
String 8 matches regex: true
String 9 matches regex: true
String 10 matches regex: true
String 11 matches regex: true
String 12 matches regex: true
String 13 matches regex: true
String 14 matches regex: true
String 15 matches regex: true
String 16 matches regex: true
String 999 matches regex: true
String 2654 matches regex: true
String 25633 matches regex: true
String 254444 matches regex: true
String 0.1 matches regex: false
String 0.2 matches regex: false
String 0.3 matches regex: false
String -1 matches regex: false
String -2 matches regex: false
String -5 matches regex: false
String -6 matches regex: false
String -6.8 matches regex: false
String -9 matches regex: false
String -54 matches regex: false
String -29 matches regex: false
String 1000 matches regex: true
String 100000 matches regex: true

Django download a file

When you upload a file using FileField, the file will have a URL that you can use to point to the file and use HTML download attribute to download that file you can simply do this.

models.py

The model.py looks like this

class CsvFile(models.Model):
    csv_file = models.FileField(upload_to='documents')

views.py

#csv upload

class CsvUploadView(generic.CreateView):

   model = CsvFile
   fields = ['csv_file']
   template_name = 'upload.html'

#csv download

class CsvDownloadView(generic.ListView):

    model = CsvFile
    fields = ['csv_file']
    template_name = 'download.html'

Then in your templates.

#Upload template

upload.html

<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
    <button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>

#download template

download.html

  {% for document in object_list %}

     <a href="{{ document.csv_file.url }}" download  class="btn btn-dark float-right">Download</a>

  {% endfor %}

I did not use forms, just rendered model but either way, FileField is there and it will work the same.

php is null or empty?

If you use ==, php treats an empty string or array as null. To make the distinction between null and empty, either use === or is_null. So:

if($a === NULL) or if(is_null($a))

how to remove multiple columns in r dataframe?

x <-dplyr::select(dataset_df, -c('coloumn1', 'column2'))

This works for me.

React-router v4 this.props.history.push(...) not working

You need to bind handleCustomerClick:

class Customers extends Component {
  constructor() {
    super();
    this.handleCustomerClick = this.handleCustomerClick(this)
  }

How do I remove a library from the arduino environment?

In Elegoo Super Starter Kit, Part 2, Lesson 2.12, IR Receiver Module, I hit the problem that the lesson's IRremote library has a hard conflict with the built-in Arduino RobotIRremote library. I am using the Win10 IDE App, and it was non-trivial to "move the RobotIRremote" folder like the pre-Win10 instructions said. The built-in Libraries are saved at a path like: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries You won't be able to see WindowsApps unless you show hidden files, and you can't do anything in that folder structure until you are the owner. Carefully follow these directions to make that happen: https://www.youtube.com/watch?v=PmrOzBDZTzw
After hours of frustration, the process above finally resulted in success for me. Elegoo gets an F+ for modern instructions on this lesson.

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Until I get a better option, this is the most "bootstrappy" answer I can work out:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/

I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less file:

in _layout.cshtml master page

  • Move footer outside the body-content container
  • Use boostrap's navbar-fixed-bottom on the footer
  • Drop the <hr/> before the footer (as now redundant)

Relevant page HTML:

<div class="container-fluid body-content">
    @RenderBody()
</div>
<footer class="navbar-fixed-bottom">
    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
</footer>

In Site.less

  • Set HTML and BODY heights to 100%
  • Set BODY overflow to hidden
  • Set body-content div position to absolute
  • Set body-content div top to @navbar-height instead of hard-wiring value
  • Set body-content div bottom to 30px.
  • Set body-content div left and right to 0
  • Set body-content div overflow-y to auto

Site.less

html {
    height: 100%;

    body {
        height: 100%;
        overflow: hidden;

        .container-fluid.body-content {
            position: absolute;
            top: @navbar-height;
            bottom: 30px;
            right: 0;
            left: 0;
            overflow-y: auto;
        }
    }
}

The remaining problem is there seems to be no defining variable for the footer height in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.

"No Content-Security-Policy meta tag found." error in my phonegap application

You have to add a CSP meta tag in the head section of your app's index.html

As per https://github.com/apache/cordova-plugin-whitelist#content-security-policy

Content Security Policy

Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly).

On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g. <video> & WebSockets are not blocked). So, in addition to the whitelist, you should use a Content Security Policy <meta> tag on all of your pages.

On Android, support for CSP within the system webview starts with KitKat (but is available on all versions using Crosswalk WebView).

Here are some example CSP declarations for your .html pages:

<!-- Good default declaration:
    * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
    * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
    * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
        * Enable inline JS: add 'unsafe-inline' to default-src
        * Enable eval(): add 'unsafe-eval' to default-src
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *">

<!-- Allow requests to foo.com -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com">

<!-- Enable all requests, inline styles, and eval() -->
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

<!-- Allow XHRs via https only -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' https:">

<!-- Allow iframe to https://cordova.apache.org/ -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org">

Disable form auto submit on button click

<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!

$('form button').on("click",function(e){
    e.preventDefault();
});

How can I convert ticks to a date format?

It's much simpler to do this:

DateTime dt = new DateTime(633896886277130000);

Which gives

dt.ToString() ==> "9/27/2009 10:50:27 PM"

You can format this any way you want by using dt.ToString(MyFormat). Refer to this reference for format strings. "MMMM dd, yyyy" works for what you specified in the question.

Not sure where you get October 1.

Standard way to embed version into python package?

  1. Use a version.py file only with __version__ = <VERSION> param in the file. In the setup.py file import the __version__ param and put it's value in the setup.py file like this: version=__version__
  2. Another way is to use just a setup.py file with version=<CURRENT_VERSION> - the CURRENT_VERSION is hardcoded.

Since we don't want to manually change the version in the file every time we create a new tag (ready to release a new package version), we can use the following..

I highly recommend bumpversion package. I've been using it for years to bump a version.

start by adding version=<VERSION> to your setup.py file if you don't have it already.

You should use a short script like this every time you bump a version:

bumpversion (patch|minor|major) - choose only one option
git push
git push --tags

Then add one file per repo called: .bumpversion.cfg:

[bumpversion]
current_version = <CURRENT_TAG>
commit = True
tag = True
tag_name = {new_version}
[bumpversion:file:<RELATIVE_PATH_TO_SETUP_FILE>]

Note:

  • You can use __version__ parameter under version.py file like it was suggested in other posts and update the bumpversion file like this: [bumpversion:file:<RELATIVE_PATH_TO_VERSION_FILE>]
  • You must git commit or git reset everything in your repo, otherwise you'll get a dirty repo error.
  • Make sure that your virtual environment includes the package of bumpversion, without it it will not work.

How can I quantify difference between two images?

A simple solution:

Encode the image as a jpeg and look for a substantial change in filesize.

I've implemented something similar with video thumbnails, and had a lot of success and scalability.

Cannot find name 'require' after upgrading to Angular4

Will work in Angular 7+


I was facing the same issue, I was adding

"types": ["node"]

to tsconfig.json of root folder.

There was one more tsconfig.app.json under src folder and I got solved this by adding

"types": ["node"]

to tsconfig.app.json file under compilerOptions

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["node"]  ----------------------< added node to the array
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Convert string to int array using LINQ

You can shorten JSprangs solution a bit by using a method group instead:

string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ints = s1.Split(';').Select(int.Parse).ToArray();

A cycle was detected in the build path of project xxx - Build Path Problem

I faced similar problem a while ago and decided to write Eclipse plug-in that shows complete build path dependency tree of a Java project (although not in graphic mode - result is written into file). The plug-in's sources are here http://github.com/PetrGlad/dependency-tree

open resource with relative path in Java

I made a small modification on @jonathan.cone's one liner ( by adding .getFile() ) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :

String realmID = new java.util.Scanner(new java.io.File(RandomDataGenerator.class.getClassLoader().getResource("data/aa-qa-id.csv").getFile().toString())).next();

Regex pattern for checking if a string starts with a certain substring?

The following will match on any string that starts with mailto, ftp or http:

 RegEx reg = new RegEx("^(mailto|ftp|http)");

To break it down:

  • ^ matches start of line
  • (mailto|ftp|http) matches any of the items separated by a |

I would find StartsWith to be more readable in this case.

How to use XMLReader in PHP?

It all depends on how big the unit of work, but I guess you're trying to treat each <product/> nodes in succession.

For that, the simplest way would be to use XMLReader to get to each node, then use SimpleXML to access them. This way, you keep the memory usage low because you're treating one node at a time and you still leverage SimpleXML's ease of use. For instance:

$z = new XMLReader;
$z->open('data.xml');

$doc = new DOMDocument;

// move to the first <product /> node
while ($z->read() && $z->name !== 'product');

// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'product')
{
    // either one should work
    //$node = new SimpleXMLElement($z->readOuterXML());
    $node = simplexml_import_dom($doc->importNode($z->expand(), true));

    // now you can use $node without going insane about parsing
    var_dump($node->element_1);

    // go to next <product />
    $z->next('product');
}

Quick overview of pros and cons of different approaches:

XMLReader only

  • Pros: fast, uses little memory

  • Cons: excessively hard to write and debug, requires lots of userland code to do anything useful. Userland code is slow and prone to error. Plus, it leaves you with more lines of code to maintain

XMLReader + SimpleXML

  • Pros: doesn't use much memory (only the memory needed to process one node) and SimpleXML is, as the name implies, really easy to use.

  • Cons: creating a SimpleXMLElement object for each node is not very fast. You really have to benchmark it to understand whether it's a problem for you. Even a modest machine would be able to process a thousand nodes per second, though.

XMLReader + DOM

  • Pros: uses about as much memory as SimpleXML, and XMLReader::expand() is faster than creating a new SimpleXMLElement. I wish it was possible to use simplexml_import_dom() but it doesn't seem to work in that case

  • Cons: DOM is annoying to work with. It's halfway between XMLReader and SimpleXML. Not as complicated and awkward as XMLReader, but light years away from working with SimpleXML.

My advice: write a prototype with SimpleXML, see if it works for you. If performance is paramount, try DOM. Stay as far away from XMLReader as possible. Remember that the more code you write, the higher the possibility of you introducing bugs or introducing performance regressions.

Set color of TextView span in Android

Set your TextView´s text spannable and define a ForegroundColorSpan for your text.

TextView textView = (TextView)findViewById(R.id.mytextview01);    
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");          
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    
textView.setText(wordtoSpan);

Make the first character Uppercase in CSS

Make it lowercase first:

.m_title {text-transform: lowercase}

Then make it the first letter uppercase:

.m_title:first-letter {text-transform: uppercase}

"text-transform: capitalize" works for a word; but if you want to use for sentences this solution is perfect.

What's the correct way to communicate between controllers in AngularJS?

Here's the quick and dirty way.

// Add $injector as a parameter for your controller

function myAngularController($scope,$injector){

    $scope.sendorders = function(){

       // now you can use $injector to get the 
       // handle of $rootScope and broadcast to all

       $injector.get('$rootScope').$broadcast('sinkallships');

    };

}

Here is an example function to add within any of the sibling controllers:

$scope.$on('sinkallships', function() {

    alert('Sink that ship!');                       

});

and of course here's your HTML:

<button ngclick="sendorders()">Sink Enemy Ships</button>

Setting POST variable without using form

If you want to set $_POST['text'] to another value, why not use:

$_POST['text'] = $var;

on next.php?

How to add white spaces in HTML paragraph

If you really need then you can use i.e. &nbsp; entity to do that, but remember that fonts used to render your page are usually proportional, so "aligning" with spaces does not really work and looks ugly.

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

First of all you need to install xlrd & pandas packages. Then try below code.

import xlrd
import pandas as pd

xl = pd.ExcelFile("fileName.xlsx")
print(xl.parse(xl.sheet_names[0]))

How to enable multidexing with the new Android Multidex support library

Add to AndroidManifest.xml:

android:name="android.support.multidex.MultiDexApplication" 

OR

MultiDex.install(this);

in your custom Application's attachBaseContext method

or your custom Application extend MultiDexApplication

add multiDexEnabled = true in your build.gradle

defaultConfig {
    multiDexEnabled true
}

dependencies {
    compile 'com.android.support:multidex:1.0.0'
    }
}

Keeping session alive with Curl and PHP

Yup, often called a 'cookie jar' Google should provide many examples:

http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/

http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO

Copying that last one here so it does not go away...

Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell

<?php
/*
This script is an example of using curl in php to log into on one page and 
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into 
thinking its netscape and even pass a fake referer, yo look like it surfed 
from a local page.
*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo "<PRE>".htmlentities($buf2);
?>  

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

Use its value directly:

In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]: 
array([[ 0.98836259,  0.82403141],
       [ 0.337358  ,  0.02054435],
       [ 0.29271728,  0.37813099],
       [ 0.70033513,  0.69919695]])

cancelling a handler.postdelayed process

In case you do have multiple inner/anonymous runnables passed to same handler, and you want to cancel all at same event use

handler.removeCallbacksAndMessages(null);

As per documentation,

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Open PDF in new browser full window

To do it from a Base64 encoding you can use the following function:

function base64ToArrayBuffer(data) {
  const bString = window.atob(data);
  const bLength = bString.length;
  const bytes = new Uint8Array(bLength);
  for (let i = 0; i < bLength; i++) {
      bytes[i] = bString.charCodeAt(i);
  }
  return bytes;
}
function base64toPDF(base64EncodedData, fileName = 'file') {
  const bufferArray = base64ToArrayBuffer(base64EncodedData);
  const blobStore = new Blob([bufferArray], { type: 'application/pdf' });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blobStore);
      return;
  }
  const data = window.URL.createObjectURL(blobStore);
  const link = document.createElement('a');
  document.body.appendChild(link);
  link.href = data;
  link.download = `${fileName}.pdf`;
  link.click();
  window.URL.revokeObjectURL(data);
  link.remove();
}

Cannot ping AWS EC2 instance

If you setup the rules as "Custom ICMP" rule and "echo reply" with anywhere it will work like a champ. The "echo request" is the wrong rule for answering pings.

Converting a String to a List of Words?

The most simple way:

>>> import re
>>> string = 'This is a string, with words!'
>>> re.findall(r'\w+', string)
['This', 'is', 'a', 'string', 'with', 'words']

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

How to parse date string to Date?

A parse exception is a checked exception, so you must catch it with a try-catch when working with parsing Strings to Dates, as @miku suggested...

HTML form action and onsubmit issues

Try

onsubmit="return checkRegistration()"

XPath OR operator for different nodes

If you want to select only one of two nodes with union operator, you can use this solution: (//bookstore/book/title | //bookstore/city/zipcode/title)[1]

Force a screen update in Excel VBA

Text boxes in worksheets are sometimes not updated when their text or formatting is changed, and even the DoEvent command does not help.

As there is no command in Excel to refresh a worksheet in the way a user form can be refreshed, it is necessary to use a trick to force Excel to update the screen.

The following commands seem to do the trick:

- ActiveSheet.Calculate    
- ActiveWindow.SmallScroll    
- Application.WindowState = Application.WindowState

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

Simple and easy :

_x000D_
_x000D_
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
  <input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to reverse a singly linked list using only two pointers?

You can simply reverse a Linked List using only one Extra pointer. And the key to do this is by using a Recursion.

Here is the program in Java.

public class Node {
   public int data;
   public Node next;
}

public Node reverseLinkedListRecursion(Node p) {
    if (p.next == null) {
        head = p;
        q = p;
        return q;
    } else {
        reverseLinkedListRecursion(p.next);
        p.next = null;
        q.next = p;
        q = p;
        return head;
    }
}

// call this function from your main method.
 reverseLinkedListRecursion(head);

As you can see this is a simple example of a head recursion. We have mainly two different kinds of Recursion.

  1. Head Recursion:- When the Recursion is the first thing executed by a function.
  2. Tail Recursion:- When the Recursion is the last thing executed by a function.

Here the program will keep calling itself Recursively until our Pointer "p" reaches to the last node and then before returning the stack frame we will point head to the last node and the extra Pointer "q" to build the linked list in the backward direction.

Here the Stack Frames will keep on returning until the stack is empty.

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

Create a file if one doesn't exist - C

You typically have to do this in a single syscall, or else you will get a race condition.

This will open for reading and writing, creating the file if necessary.

FILE *fp = fopen("scores.dat", "ab+");

If you want to read it and then write a new version from scratch, then do it as two steps.

FILE *fp = fopen("scores.dat", "rb");
if (fp) {
    read_scores(fp);
}

// Later...

// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
    error();
write_scores(fp);

Difference between object and class in Scala

An object has exactly one instance (you can not call new MyObject). You can have multiple instances of a class.

Object serves the same (and some additional) purposes as the static methods and fields in Java.

if variable contains

You can use a regex:

if (/ST1/i.test(code))

npx command not found

Remove NodeJs and npm in your system and reinstall it by following commands

Uninlstallation

sudo apt remove nodejs
sudo apt remove npm

Fresh Installation

sudo apt install nodejs
sudo apt install npm

Configuration optional, in some cases users may face permission errors.

  1. user defined directory where npm will install packages

    mkdir ~/.npm-global

  2. configure npm

    npm config set prefix '~/.npm-global'

  3. add directory to path

    echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.profile

  4. refresh path for the current session

    source ~/.profile

  5. cross-check npm and node modules installed successfully in our system

    node -v
    npm -v

Installation of npx

sudo npm i -g npx
npx -v

Well-done we are ready to go... now you can easily use npx anywhere in your system.

Best way to simulate "group by" from bash?

The canonical solution is the one mentioned by another respondent:

sort | uniq -c

It is shorter and more concise than what can be written in Perl or awk.

You write that you don't want to use sort, because the data's size is larger than the machine's main memory size. Don't underestimate the implementation quality of the Unix sort command. Sort was used to handle very large volumes of data (think the original AT&T's billing data) on machines with 128k (that's 131,072 bytes) of memory (PDP-11). When sort encounters more data than a preset limit (often tuned close to the size of the machine's main memory) it sorts the data it has read in main memory and writes it into a temporary file. It then repeats the action with the next chunks of data. Finally, it performs a merge sort on those intermediate files. This allows sort to work on data many times larger than the machine's main memory.

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

How do I go about adding an image into a java project with eclipse?

Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:

InputStream input = classLoader.getResourceAsStream("image.jpg");

Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).

PHP parse/syntax errors; and how to solve them

I think this topic is totally overdiscussed/overcomplicated. Using an IDE is THE way to go to completely avoid any syntax errors. I would even say that working without an IDE is kind of unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you code and your entire line turns red, and a big warning notice shows you the exact type and the exact position of the syntax error, then there's absolutely no need to search for another solution.

Using a syntax-checking IDE means:

You'll (effectively) never run into syntax errors again, simply because you see them right as you type. Seriously.

Excellent IDEs with syntax check (all of them are available for Linux, Windows and Mac):

  1. NetBeans [free]
  2. PHPStorm [$199 USD]
  3. Eclipse with PHP Plugin [free]
  4. Sublime [$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)

Can I use a binary literal in C or C++?

The "type" of a binary number is the same as any decimal, hex or octal number: int (or even char, short, long long).

When you assign a constant, you can't assign it with 11011011 (curiously and unfortunately), but you can use hex. Hex is a little easier to mentally translate. Chunk in nibbles (4 bits) and translate to a character in [0-9a-f].

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

Most of time it happen because two mysql-connector-java-3.0.14-production-bin.jar file. One in lib folder of tomcat and another in classpath of the project.

Just try to remove mysql-connector-java-3.0.14-production-bin.jar from lib folder.

This way it is working for me.

What are the use cases for selecting CHAR over VARCHAR in SQL?

I stand by Jim McKeeth's comment.

Also, indexing and full table scans are faster if your table has only CHAR columns. Basically the optimizer will be able to predict how big each record is if it only has CHAR columns, while it needs to check the size value of every VARCHAR column.

Besides if you update a VARCHAR column to a size larger than its previous content you may force the database to rebuild its indexes (because you forced the database to physically move the record on disk). While with CHAR columns that'll never happen.

But you probably won't care about the performance hit unless your table is huge.

Remember Djikstra's wise words. Early performance optimization is the root of all evil.

z-index issue with twitter bootstrap dropdown menu

Just give

position: relative; 
z-index: 999;

to the navbar

how to read System environment variable in Spring applicationContext

Thanks to @Yiling. That was a hint.

<bean id="propertyConfigurer"
        class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">

    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="searchSystemEnvironment" value="true" />
    <property name="locations">
        <list>
            <value>file:#{systemEnvironment['FILE_PATH']}/first.properties</value>
            <value>file:#{systemEnvironment['FILE_PATH']}/second.properties</value>
            <value>file:#{systemEnvironment['FILE_PATH']}/third.properties</value>
        </list>
    </property>
</bean>

After this, you should have one environment variable named 'FILE_PATH'. Make sure you restart your terminal/IDE after creating that environment variable.

Multiprocessing a for loop?

You can simply use multiprocessing.Pool:

from multiprocessing import Pool

def process_image(name):
    sci=fits.open('{}.fits'.format(name))
    <process>

if __name__ == '__main__':
    pool = Pool()                         # Create a multiprocessing Pool
    pool.map(process_image, data_inputs)  # process data_inputs iterable with pool

How to use filter, map, and reduce in Python 3

Since the reduce method has been removed from the built in function from Python3, don't forget to import the functools in your code. Please look at the code snippet below.

import functools
my_list = [10,15,20,25,35]
sum_numbers = functools.reduce(lambda x ,y : x+y , my_list)
print(sum_numbers)

pandas dataframe columns scaling with sklearn

(Tested for pandas 1.0.5)
Based on @athlonshi answer (it had ValueError: could not convert string to float: 'big', on C column), full working example without warning:

import pandas as pd
from sklearn.preprocessing import MinMaxScaler
scale = preprocessing.MinMaxScaler()

df = pd.DataFrame({
           'A':[14.00,90.20,90.95,96.27,91.21],
           'B':[103.02,107.26,110.35,114.23,114.68], 
           'C':['big','small','big','small','small']
         })
print(df)
df[["A","B"]] = pd.DataFrame(scale.fit_transform(df[["A","B"]].values), columns=["A","B"], index=df.index)
print(df)

       A       B      C
0  14.00  103.02    big
1  90.20  107.26  small
2  90.95  110.35    big
3  96.27  114.23  small
4  91.21  114.68  small
          A         B      C
0  0.000000  0.000000    big
1  0.926219  0.363636  small
2  0.935335  0.628645    big
3  1.000000  0.961407  small
4  0.938495  1.000000  small

How do you find all subclasses of a given class in Java?

Scanning for classes is not easy with pure Java.

The spring framework offers a class called ClassPathScanningCandidateComponentProvider that can do what you need. The following example would find all subclasses of MyClass in the package org.example.package

ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(MyClass.class));

// scan in org.example.package
Set<BeanDefinition> components = provider.findCandidateComponents("org/example/package");
for (BeanDefinition component : components)
{
    Class cls = Class.forName(component.getBeanClassName());
    // use class cls found
}

This method has the additional benefit of using a bytecode analyzer to find the candidates which means it will not load all classes it scans.

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

How to add anchor tags dynamically to a div in Javascript?

With jquery

  $("div#id").append('<a href=#>Your LINK TITLE</a>')

With javascript

   var new_a = document.createElement('a');
   new_a.setAttribute("href", "link url here");
   new_a.innerHTML = "your link text";
   //add new link to the DOM
   document.appendChild(new_a);

How do I convert certain columns of a data frame to become factors?

Given the following sample

myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)  

then

myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)

or you could select your columns altogether and wrap it up nicely:

# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))

levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")

To obtain

> myData
      A   B Pulse
1  long 1kg    20
2 short 2kg    21
3  long 3kg    22
4 short 1kg    23
5  long 2kg    24
6 short 3kg    25

How to initialize weights in PyTorch?

Here is the better way, just pass your whole model

import torch.nn as nn
def initialize_weights(model):
    # Initializes weights according to the DCGAN paper
    for m in model.modules():
        if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.BatchNorm2d)):
            nn.init.normal_(m.weight.data, 0.0, 0.02)
        # if you also want for linear layers ,add one more elif condition 

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

You need to replace it as WHERE clockDate = { fn CURRENT_DATE() } AND userName = 'test'. Please remove extra ")" from { fn CURRENT_DATE() })

How to execute 16-bit installer on 64-bit Win7?

I am mostly posting this in case someone comes along and is not aware that VB2005 and VB2008 have update utilities that convert older VB versions to it's format. Especially since no one bothered to point that fact out.

Points taken, but maintenance of this VB6 product is unavoidable. It would also be costly in man-hours to replace the Sheridan controls with native ones. Simply developing on a 32-bit machine would be a better alternative than doing that. I would like to install everything on Win7 64-bit ideally. – CJ7

Have you tried utilizing the code upgrade functionality of VB Express 2005+?

If not, 1. Make a copy of your code - folder and all. 2. Import the project into VB express 2005. This will activate the update wizard. 3. Debug and get the app running. 4. Create a new installer utilizing MS free tool. 5. You now have a 32 bit application with a 32 bit installer.

Until you do this, you will never know how difficult or hard it will be to update and modernize the program. It is quite possible that the wizard will update the Sheridan controls to the VB 2005 controls. Again, you will not know if it does and how well it does it until you try it.

Alternatively, stick with the 32 Bit versions of Windows 7 and 8. I have Windows 7 x64 and a program that will not run. However, the program will run in Windows 7 32 bit as well as Windows 8 RC 32 bit. Under Windows 8 RC 32, I was prompted to enable 16 bit emulation which I did and the program rand quite fine afterwords.

How to connect to local instance of SQL Server 2008 Express

Please check the ServerName which you provided. It should match with the below shown Name in the UserName textbox, and that name should followed with \SQLEXPRESS:

Connect dialog

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

jQuery form input select by id

If you have more than one element with the same ID, then you have invalid HTML.

But you can acheive the same result using classes instead. That's what they're designed for.

<input class='b' ... >

You can give it an ID as well if you need to, but it should be unique.

Once you've got the class in there, you can reference it with a dot instead of the hash, like so:

var value = $('#a .b').val();

or

var value = $('#a input.b').val();

which will limit it to 'b' class elements that are inputs within the form (which seems to be close to what you're asking for).

Select parent element of known element in Selenium

Little more about XPath axes

Lets say we have below HTML structure:

<div class="third_level_ancestor">
    <nav class="second_level_ancestor">
        <div class="parent">
            <span>Child</span>
        </div>
    </nav>
</div>
  1. //span/parent::* - returns any element which is direct parent.

In this case output is <div class="parent">

  1. //span/parent::div[@class="parent"] - returns parent element only of exact node type and only if specified predicate is True.

Output: <div class="parent">

  1. //span/ancestor::* - returns all ancestors (including parent).

Output: <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor-or-self::* - returns all ancestors and current element itself.

Output: <span>Child</span>, <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor::div[2] - returns second ancestor (starting from parent) of type div.

Output: <div class="third_level_ancestor">

How to run Rake tasks from within Rake tasks?

If you want each task to run regardless of any failures, you can do something like:

task :build_all do
  [:debug, :release].each do |t| 
    ts = 0
    begin  
      Rake::Task["build"].invoke(t)
    rescue
      ts = 1
      next
    ensure
      Rake::Task["build"].reenable # If you need to reenable
    end
    return ts # Return exit code 1 if any failed, 0 if all success
  end
end

How to use WPF Background Worker

You may want to also look into using Task instead of background workers.

The easiest way to do this is in your example is Task.Run(InitializationThread);.

There are several benefits to using tasks instead of background workers. For example, the new async/await features in .net 4.5 use Task for threading. Here is some documentation about Task https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task

Add an image in a WPF button

I also had the same issue. I've fixed it by using the following code.

        <Button Width="30" Margin="0,5" HorizontalAlignment="Stretch"  Click="OnSearch" >
            <DockPanel>
                <Image Source="../Resources/Back.jpg"/>
            </DockPanel>
        </Button>

Note: Make sure the build action of the image in the property window, should be Resource.

enter image description here

How to concatenate characters in java?

this is very simple approach to concatenate or append the character

       StringBuilder desc = new StringBuilder(); 
       String Description="this is my land"; 
       desc=desc.append(Description.charAt(i));

Is it possible to change a UIButtons background color?

Another possibility (the best and most beautiful imho):

Create a UISegmentedControl with 2 segments in the required background color in Interface Builder. Set the type to 'bar'. Then, change it to having only one segment. Interface builder does not accept one segment so you have to do that programmatically.

Therefore, create an IBOutlet for this button and add this to the viewDidLoad of your view:

[segmentedButton removeSegmentAtIndex:1 animated:NO];

Now you have a beautiful glossy, colored button with the specified background color. For actions, use the 'value changed' event.

(I have found this on http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/). Thanks Chris!

Debugging iframes with Chrome developer tools

In the Developer Tools in Chrome, there is a bar along the top, called the Execution Context Selector (h/t felipe-sabino), just under the Elements, Network, Sources... tabs, that changes depending on the context of the current tab. When in the Console tab there is a dropdown in that bar that allows you to select the frame context in which the Console will operate. Select your frame in this drop down and you will find yourself in the appropriate frame context. :D

Chrome v59 Chrome version 59

Chrome v33 Chrome version 33

Chrome v32 & lower Chrome pre-version 32

Python creating a dictionary of lists

Personally, I just use JSON to convert things to strings and back. Strings I understand.

import json
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
mydict = {}
hash = json.dumps(s)
mydict[hash] = "whatever"
print mydict
#{'[["yellow", 1], ["blue", 2], ["yellow", 3], ["blue", 4], ["red", 1]]': 'whatever'}

jQuery count number of divs with a certain class?

And for the plain js answer if anyone might be interested;

var count = document.getElementsByClassName("item");

Cheers.

Reference: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

Redirecting to previous page after login? PHP

how about this :: javascript+php

echo "<script language=javascript> javascript:history.back();</script>";

it will work same as the previous button in your browser

Python 3: EOF when reading a line (Sublime Text 2 is angry)

help(input) shows what keyboard shortcuts produce EOF, namely, Unix: Ctrl-D, Windows: Ctrl-Z+Return:

input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.

You could reproduce it using an empty file:

$ touch empty
$ python3 -c "input()" < empty
Traceback (most recent call last):
  File "<string>", line 1, in <module>
EOFError: EOF when reading a line

You could use /dev/null or nul (Windows) as an empty file for reading. os.devnull shows the name that is used by your OS:

$ python3 -c "import os; print(os.devnull)"
/dev/null

Note: input() happily accepts input from a file/pipe. You don't need stdin to be connected to the terminal:

$ echo abc | python3 -c "print(input()[::-1])"
cba

Either handle EOFError in your code:

try:
    reply = input('Enter text')
except EOFError:
    break

Or configure your editor to provide a non-empty input when it runs your script e.g., by using a customized command line if it allows it: python3 "%f" < input_file

What does "static" mean in C?

If you declare a variable in a function static, its value will not be stored on the function call stack and will still be available when you call the function again.

If you declare a global variable static, its scope will be restricted to within the file in which you declared it. This is slightly safer than a regular global which can be read and modified throughout your entire program.

HttpClient 4.0.1 - how to release connection?

If you want to re-use the connection then you must consume content stream completely after every use as follows :

EntityUtils.consume(response.getEntity())

Note : you need to consume the content stream even if the status code is not 200. Not doing so will raise the following on next use :

Exception in thread "main" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated. Make sure to release the connection before allocating another one.

If it's a one time use, then simply closing the connection will release all the resources associated with it.

100% width Twitter Bootstrap 3 template

This is the complete basic structure for 100% width layout in Bootstrap v3.0.0. You shouldn't wrap your <div class="row"> with container class. Cause container class will take lots of margin and this will not provide you full screen (100% width) layout where bootstrap has removed container-fluid class from their mobile-first version v3.0.0.

So just start writing <div class="row"> without container class and you are ready to go with 100% width layout.

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap Basic 100% width Structure</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script src="http://getbootstrap.com/assets/js/html5shiv.js"></script>
  <script src="http://getbootstrap.com/assets/js/respond.min.js"></script>
<![endif]-->
<style>
    .red{
        background-color: red;
    }
    .green{
        background-color: green;
    }
</style>
</head>
<body>
    <div class="row">
        <div class="col-md-3 red">Test content</div>
        <div class="col-md-9 green">Another Content</div>
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="//code.jquery.com/jquery.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>

To see the result by yourself I have created a bootply. See the live output there. http://bootply.com/82136 And the complete basic bootstrap 3 100% width layout I have created a gist. you can use that. Get the gist from here

Reply me if you need more further assistance. Thanks.

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

How do you use global variables or constant values in Ruby?

One of the reasons why the global variable needs a prefix (called a "sigil") is because in Ruby, unlike in C, you don't have to declare your variables before assigning to them. The sigil is used as a way to be explicit about the scope of the variable.

Without a specific prefix for globals, given a statement pointNew = offset + point inside your draw method then offset refers to a local variable inside the method (and results in a NameError in this case). The same for @ used to refer to instance variables and @@ for class variables.

In other languages that use explicit declarations such as C, Java etc. the placement of the declaration is used to control the scope.

Select Pandas rows based on list index

There are many ways of solving this problem, and the ones listed above are the most commonly used ways of achieving the solution. I want to add two more ways, just in case someone is looking for an alternative.

index_list = [1,3]

df.take(pos)

#or

df.query('index in @index_list')

"Operation must use an updateable query" error in MS Access

I was accessing the database using UNC path and occasionally this exception was thrown. When I replaced the computer name with IP address, the problem was suddenly resolved.

Stuck at ".android/repositories.cfg could not be loaded."

Actually, after waiting some time it eventually goes beyond that step. Even with --verbose, you won't have any information that it computes anything, but it does.

Patience is the key :)

PS : For anyone that cancelled at that step, if you try to reinstall the android-sdk package, it will complain that Error: No such file or directory - /usr/local/share/android-sdk. You can just touch /usr/local/share/android-sdk to get rid of that error and go on with the reinstall.

android: how to align image in the horizontal center of an imageview?

<ImageView
    android:id="@+id/img"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center" />

The default XML namespace of the project must be the MSBuild XML namespace

@DavidG's answer is correct, but I would like to add that if you're building from the command line, the equivalent solution is to make sure that you're using the appropriate version of msbuild (in this particular case, it needs to be version 15).

Run msbuild /? to see which version you're using or where msbuild to check which location the environment takes the executable from and update (or point to the right location of) the tools if necessary.

Download the latest MSBuild tool from here.

Using Colormaps to set color of line in matplotlib

A combination of line styles, markers, and qualitative colors from matplotlib:

import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors   # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
    plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);

enter image description here

UPDATE: Supporting not only ListedColormap, but also LinearSegmentedColormap

import itertools
import matplotlib.pyplot as plt
Ncolors = 8
#colormap = plt.cm.Dark2# ListedColormap
colormap = plt.cm.viridis# LinearSegmentedColormap
Ncolors = min(colormap.N,Ncolors)
mapcolors = [colormap(int(x*colormap.N/Ncolors)) for x in range(Ncolors)]
N = Ncolors*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
fig,ax = plt.subplots(gridspec_kw=dict(right=0.6))
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, mapcolors)):
    ax.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=3,prop={'size': 8})

enter image description here

C# getting its own class name

I wanted to throw this up for good measure. I think the way @micahtan posted is preferred.

typeof(MyProgram).Name

Angular is automatically adding 'ng-invalid' class on 'required' fields

the accepted answer is correct.. for mobile you can also use this (ng-touched rather ng-dirty)

input.ng-invalid.ng-touched{
  border-bottom: 1px solid #e74c3c !important; 
}

Java 6 Unsupported major.minor version 51.0

The problem is because you haven't set JDK version properly.You should use jdk 7 for major number 51. Like this:

JAVA_HOME=/usr/java/jdk1.7.0_79

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

The warning is generated because you are using a full URL for the file that you are including. This is NOT the right way because this way you are going to get some HTML from the webserver. Use:

require_once('../web/a.php');

so that webserver could EXECUTE the script and deliver its output, instead of just serving up the source code (your current case which leads to the warning).

Stack Memory vs Heap Memory

It's a language abstraction - some languages have both, some one, some neither.

In the case of C++, the code is not run in either the stack or the heap. You can test what happens if you run out of heap memory by repeatingly calling new to allocate memory in a loop without calling delete to free it it. But make a system backup before doing this.

Class 'ViewController' has no initializers in swift

if you lost a "!" in your code ,like this code below, you'll also get this error.

import UIKit

class MemeDetailViewController : UIViewController {

    @IBOutlet weak var memeImage: UIImageView!

    var meme:Meme! // lost"!"

    override func viewWillAppear(animated: Bool) {

        super.viewWillAppear(animated)
        self.memeImage!.image = meme.memedImage
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
    }

}

android: stretch image in imageview to fit screen

if you use android:scaleType="fitXY" then you must specify

android:layout_width="75dp" and android:layout_height="75dp"

if use wrap_content it will not stretch to what you need

<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="@+id/listItemNoteImage"
android:src="@drawable/MyImage"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="12dp"
android:scaleType="fitXY"/>

Python Pandas : pivot table with aggfunc = count unique distinct

This is a good way of counting entries within .pivot_table:

df2.pivot_table(values='X', index=['Y','Z'], columns='X', aggfunc='count')


        X1  X2
Y   Z       
Y1  Z1   1   1
    Z2   1  NaN
Y2  Z3   1  NaN

C# How to determine if a number is a multiple of another?

I don't get that part about the string stuff, but why don't you use the modulo operator (%) to check if a number is dividable by another? If a number is dividable by another, the other is automatically a multiple of that number.

It goes like that:

   int a = 10; int b = 5;

   // is a a multiple of b 
   if ( a % b == 0 )  ....

How do I determine the dependencies of a .NET application?

Enable assembly binding logging set the registry value EnableLog in HKLM\Software\Microsoft\Fusion to 1. Note that you have to restart your application (use iisreset) for the changes to have any effect.

Tip: Remember to turn off fusion logging when you are done since there is a performance penalty to have it turned on.

Could not locate Gemfile

Is very simple. when it says 'Could not locate Gemfile' it means in the folder you are currently in or a directory you are in, there is No a file named GemFile. Therefore in your command prompt give an explicit or full path of the there folder where such file name "Gemfile" is e.g cd C:\Users\Administrator\Desktop\RubyProject\demo.

It will definitely be solved in a minute.

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

ORA-28001: The password has expired

Try to connect with the users in SQL Plus, whose password has expired. it will prompt for the new password. Enter the new password and confirm password.

It will work

SQL Plus output image

Tools to get a pictorial function call graph of code

Our DMS Software Reengineering Toolkit has static control/dataflow/points-to/call graph analysis that has been applied to huge systems (~~25 million lines) of C code, and produced such call graphs, including functions called via function pointers.

Making RGB color in Xcode

You already got the right answer, but if you dislike the UIColor interface like me, you can do this:

#import "UIColor+Helper.h"
// ...
myLabel.textColor = [UIColor colorWithRGBA:0xA06105FF];

UIColor+Helper.h:

#import <UIKit/UIKit.h>

@interface UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color;
@end

UIColor+Helper.m:

#import "UIColor+Helper.h"

@implementation UIColor (Helper)

+ (UIColor *)colorWithRGBA:(NSUInteger)color
{
    return [UIColor colorWithRed:((color >> 24) & 0xFF) / 255.0f
                           green:((color >> 16) & 0xFF) / 255.0f
                            blue:((color >> 8) & 0xFF) / 255.0f
                           alpha:((color) & 0xFF) / 255.0f];
}

@end

Add new field to every document in a MongoDB collection

if you are using mongoose try this,after mongoose connection

async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})

openCV video saving in python

I also faced same problem but it worked when I used 'MJPG' instead of 'XVID'

I used

fourcc = cv2.VideoWriter_fourcc(*'MJPG')

instead of

fourcc = cv2.VideoWriter_fourcc(*'XVID')

SELECT inside a COUNT

SELECT a AS current_a, COUNT(*) AS b,
   (SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
   from t group by a order by b desc

Getting value from a cell from a gridview on RowDataBound event

Just use a loop to check your cell in a gridview for example:

for (int i = 0; i < GridView2.Rows.Count; i++)
{
    string vr;
    vr = GridView2.Rows[i].Cells[4].Text; // here you go vr = the value of the cel
    if (vr  == "0") // you can check for anything
    {
        GridView2.Rows[i].Cells[4].Text = "Done";
        // you can format this cell 
    }
}

How to add custom method to Spring Data JPA

Considering your code snippet, please note that you can only pass Native objects to the findBy### method, lets say you want to load a list of accounts that belongs certain costumers, one solution is to do this,

@Query("Select a from Account a where a."#nameoffield"=?1")
List<Account> findByCustomer(String "#nameoffield");

Make sue the name of the table to be queried is thesame as the Entity class. For further implementations please take a look at this

SQLAlchemy: What's the difference between flush() and commit()?

commit () records these changes in the database. flush () is always called as part of the commit () (1) call. When you use a Session object to query a database, the query returns results from both the database and the reddened parts of the unrecorded transaction it is performing.

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

You can cast your timestamp to a date by suffixing it with ::date. Here, in psql, is a timestamp:

# select '2010-01-01 12:00:00'::timestamp;
      timestamp      
---------------------
 2010-01-01 12:00:00

Now we'll cast it to a date:

wconrad=# select '2010-01-01 12:00:00'::timestamp::date;
    date    
------------
 2010-01-01

On the other hand you can use date_trunc function. The difference between them is that the latter returns the same data type like timestamptz keeping your time zone intact (if you need it).

=> select date_trunc('day', now());
       date_trunc
------------------------
 2015-12-15 00:00:00+02
(1 row)

How do I get the collection of Model State Errors in ASP.NET MVC?

If you don't know what property caused the error, you can, using reflection, loop over all properties:

public static String ShowAllErrors<T>(this HtmlHelper helper) {
    StringBuilder sb = new StringBuilder();
    Type myType = typeof(T);
    PropertyInfo[] propInfo = myType.GetProperties();

    foreach (PropertyInfo prop in propInfo) {
        foreach (var e in helper.ViewData.ModelState[prop.Name].Errors) {
            TagBuilder div = new TagBuilder("div");
            div.MergeAttribute("class", "field-validation-error");
            div.SetInnerText(e.ErrorMessage);
            sb.Append(div.ToString());
        }
    }
    return sb.ToString();
}

Where T is the type of your "ViewModel".

Rounding to 2 decimal places in SQL

you may try the TO_CHAR function to convert the result

e.g.

SELECT TO_CHAR(92, '99.99') AS RES FROM DUAL

SELECT TO_CHAR(92.258, '99.99') AS RES FROM DUAL

Hope it helps

How do I check if a number is a palindrome?

Dammit, I’m mad! http://www.palindromelist.net/palindromes-d/
Single steps example: is 332 a palindromic number?

n = 332
q = n / 10 = 33
r = n - 10 * q = 2
r > 0
r != q
n = q = 33
n > r
q = n / 10 = 3
r -= q = 4294967295
r *= 10 = 4294967286
r += n = 23
r != n
r != q
n = q = 3
n > r ? No, so 332 isn't a palindromic number.

Overflow isn't a problem either. Two divisions were necessary, in code (C#) they're done with multiplications. A n-digit number: ~n/2 divisions!

const ulong c0 = 0xcccccccdUL;
static bool isPal(uint n)
{
    if (n < 10) return true;
    uint q = (uint)(c0 * n >> 35);
    uint r = n - 10 * q;
    if (r == 0) return false;
    if (r == q) return true;
    n = q;
    while (n > r)
    {
        q = (uint)(c0 * n >> 35);
        r -= q;
        r *= 10;
        r += n;
        if (r == n || r == q) return true;
        n = q;
    }
    return false;
}

There are 142948 palindromic numbers < 2^32, their sum is 137275874705916.

using System;
class Program
{
    static void Main()  // take a break
    {
        uint n, c; var sw = System.Diagnostics.Stopwatch.StartNew();
        n = ~0u; c = 0; sw.Restart(); while (n > 0) if (isPal0(n--)) c++;
        Console.WriteLine(sw.Elapsed + " " + c);                  // 76 s
        n = ~0u; c = 0; sw.Restart(); while (n > 0) if (isPal1(n--)) c++;
        Console.WriteLine(sw.Elapsed + " " + c);                  // 42 s
        n = ~0u; c = 0; sw.Restart(); while (n > 0) if (isPal2(n--)) c++;
        Console.WriteLine(sw.Elapsed + " " + c);                  // 31 s
        Console.Read();
    }

    static bool isPal0(uint u)
    {
        uint n = u, rev = 0;
        while (n > 0) { uint dig = n % 10; rev = rev * 10 + dig; n /= 10; }
        return u == rev;
    }

    static bool isPal1(uint u)
    {
        uint n = u, r = 0;
        while (n >= 10) r = n + (r - (n /= 10)) * 10;
        return u == 10 * r + n;
    }

    static bool isPal2(uint n)
    {
        if (n < 10) return true;
        uint q = n / 10, r = n - 10 * q;
        if (r == 0 || r == q) return r > 0;
        while ((n = q) > r)
        {
            q /= 10; r -= q; r *= 10; r += n;
            if (r == n || r == q) return true;
        }
        return false;
    }
}

This one seems to be faster.

using System;
class Program
{
    static void Main()
    {
        uint n, c; var sw = System.Diagnostics.Stopwatch.StartNew();
        n = ~0u; c = 0; sw.Restart(); while (n > 0) if (isPal(n--)) c++;
        Console.WriteLine(sw.Elapsed + " " + c);                 // 21 s
        Console.Read();
    }

    static bool isPal(uint n)
    {
        return n < 100 ? n < 10 || n % 11 == 0 :
              n < 1000 ? /*          */ n / 100 == n % 10 :
             n < 10000 ? n % 11 == 0 && n / 1000 == n % 10 && isP(n) :
            n < 100000 ? /*          */ n / 10000 == n % 10 && isP(n) :
           n < 1000000 ? n % 11 == 0 && n / 100000 == n % 10 && isP(n) :
          n < 10000000 ? /*          */ n / 1000000 == n % 10 && isP(n) :
         n < 100000000 ? n % 11 == 0 && n / 10000000 == n % 10 && isP(n) :
        n < 1000000000 ? /*          */ n / 100000000 == n % 10 && isP(n) :
                         n % 11 == 0 && n / 1000000000 == n % 10 && isP(n);
    }

    static bool isP(uint n)
    {
        uint q = n / 10, r = n - 10 * q;
        do { n = q; q /= 10; r -= q; r *= 10; r += n; } while (r < q);
        return r == q || r == n;
    }
}

With an almost balanced binary search spaghetti tree.

using System;
class Program
{
    static void Main()
    {
        uint n, c; var sw = System.Diagnostics.Stopwatch.StartNew();
        n = c = 0; sw.Restart(); while (n < ~0u) if (isPal(n++)) c++;
        Console.WriteLine(sw.Elapsed + " " + c);              // 17 s
        Console.Read();
    }

    static bool isPal(uint n)
    {
        return n < 1000000 ? n < 10000 ? n < 1000 ? n < 100 ?
        n < 10 || n % 11 == 0 : n / 100 == n % 10 :
        n / 1000 == n % 10 && isP(n) : n < 100000 ?
        n / 10000 == n % 10 && isP(n) :
        n / 100000 == n % 10 && isP(n) :
        n < 100000000 ? n < 10000000 ?
        n / 1000000 == n % 10 && isP(n) :
        n % 11 == 0 && n / 10000000 == n % 10 && isP(n) :
        n < 1000000000 ? n / 100000000 == n % 10 && isP(n) :
        n % 11 == 0 && n / 1000000000 == n % 10 && isP(n);
    }

    static bool isP(uint n)
    {
        uint q = n / 10, r = n - 10 * q;
        do { n = q; q /= 10; r -= q; r *= 10; r += n; } while (r < q);
        return r == q || r == n;
    }
}

Unbalanced upside down.

using System;
class Program
{
    static void Main()
    {
        uint n, c; var sw = System.Diagnostics.Stopwatch.StartNew();
        n = c = 0; sw.Restart(); while (n < ~0u) if (isPal(n++)) c++;
        Console.WriteLine(sw.Elapsed + " " + c);              // 16 s
        Console.Read();
    }

    static bool isPal(uint n)
    {
        return
        n > 999999999 ? n % 11 == 0 && n / 1000000000 == n % 10 && isP(n) :
        n > 99999999 ? n / 100000000 == n % 10 && isP(n) :
        n > 9999999 ? n % 11 == 0 && n / 10000000 == n % 10 && isP(n) :
        n > 999999 ? n / 1000000 == n % 10 && isP(n) :
        n > 99999 ? n % 11 == 0 && n / 100000 == n % 10 && isP(n) :
        n > 9999 ? n / 10000 == n % 10 && isP(n) :
        n > 999 ? n % 11 == 0 && n / 1000 == n % 10 && isP(n) :
        n > 99 ? n / 100 == n % 10 :
        n < 10 || n % 11 == 0;
    }

    static bool isP(uint n)
    {
        uint q = n / 10, r = n - 10 * q;
        do { n = q; q /= 10; r -= q; r *= 10; r += n; } while (r < q);
        return r == q || r == n;
    }
}

Can't connect to local MySQL server through socket homebrew

I had some directories left from another mysql(8.0) installation, that were not removed.

I solved this by doing the following:

First uninstall mysql

brew uninstall [email protected]

Delete the folders/files that were not removed

rm -rf /usr/local/var/mysql
rm /usr/local/etc/my.cnf

Reinstall mysql and link it

brew install [email protected]
brew link --force [email protected]

Enable and start the service

brew services start [email protected]

T-SQL STOP or ABORT command in SQL Server

Why not simply add the following to the beginning of the script

PRINT 'INACTIVE SCRIPT'
RETURN

ResultSet exception - before start of result set

Every answer uses .next() or uses .beforeFirst() and then .next(). But why not this:

result.first();

So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet exists of one specific record.

What is WebKit and how is it related to CSS?

Update: So apparently, WebKit is a HTML/CSS web browser rendering engine for Safari/Chrome. Are there such engines for IE/Opera/Firefox and what are the differences, pros and cons of using one over the other? Can I use WebKit features in Firefox for example?

Every browser is backed by a rendering engine to draw the HTML/CSS web page.

  • IE → Trident (discontinued)
  • Edge ? EdgeHTML (clean-up fork of Trident) (Edge switched to Blink in 2019)
  • Firefox → Gecko
  • Opera → Presto (no longer uses Presto since Feb 2013, consider Opera = Chrome, therefore Blink nowadays)
  • Safari → WebKit
  • Chrome → Blink (a fork of Webkit).

See Comparison of web browser engines for a list of comparisons in different areas.

The ultimate question... is WebKit supported by IE?

Not natively.

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

For webpack 1 or 2 with Bootstrap 4 you need

new webpack.ProvidePlugin({
   $: 'jquery',
   jQuery: 'jquery',
   Tether: 'tether'
})

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

Even I got the same issue and my mistake was that I didn't download python MSI file. You will get it here: https://www.python.org/downloads/

Once you download the msi, run the setup and that will solve the problem. After that you can go to File->Settings->Project Settings->Project Interpreter->Python Interpreters

and select the python.exe file. (This file will be available at c:\Python34) Select the python.exe file. That's it.

How to import a csv file into MySQL workbench?

In the navigator under SCHEMAS, right click your schema/database and select "Table Data Import Wizard"

Works for mac too.

How do I create documentation with Pydoc?

As RocketDonkey suggested, your module itself needs to have some docstrings.

For example, in myModule/__init__.py:

"""
The mod module
"""

You'd also want to generate documentation for each file in myModule/*.py using

pydoc myModule.thefilename

to make sure the generated files match the ones that are referenced from the main module documentation file.

Take a screenshot via a Python script on Linux

for ubuntu this work for me, you can take a screenshot of select window with this:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gdk
from gi.repository import GdkPixbuf
import numpy as np
from Xlib.display import Display

#define the window name
window_name = 'Spotify'

#define xid of your select 'window'
def locate_window(stack,window):
    disp = Display()
    NET_WM_NAME = disp.intern_atom('_NET_WM_NAME')
    WM_NAME = disp.intern_atom('WM_NAME') 
    name= []
    for i, w in enumerate(stack):
        win_id =w.get_xid()
        window_obj = disp.create_resource_object('window', win_id)
        for atom in (NET_WM_NAME, WM_NAME):
            window_name=window_obj.get_full_property(atom, 0)
            name.append(window_name.value)
    for l in range(len(stack)):
        if(name[2*l]==window):
            return stack[l]

window = Gdk.get_default_root_window()
screen = window.get_screen()
stack = screen.get_window_stack()
myselectwindow = locate_window(stack,window_name)
img_pixbuf = Gdk.pixbuf_get_from_window(myselectwindow,*myselectwindow.get_geometry()) 

to transform pixbuf into array

def pixbuf_to_array(p):
    w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channels(), p.get_rowstride())
    assert p.get_colorspace() == GdkPixbuf.Colorspace.RGB
    assert p.get_bits_per_sample() == 8
    if  p.get_has_alpha():
        assert c == 4
    else:
        assert c == 3
    assert r >= w * c
    a=np.frombuffer(p.get_pixels(),dtype=np.uint8)
    if a.shape[0] == w*c*h:
        return a.reshape( (h, w, c) )
    else:
        b=np.zeros((h,w*c),'uint8')
        for j in range(h):
            b[j,:]=a[r*j:r*j+w*c]
        return b.reshape( (h, w, c) )

beauty_print = pixbuf_to_array(img_pixbuf)

how to use getSharedPreferences in android

After reading around alot, only this worked: In class to set Shared preferences:

 SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
                    SharedPreferences.Editor edit = userDetails.edit();
                    edit.clear();
                    edit.putString("test1", "1");
                    edit.putString("test2", "2");
                    edit.commit();

In AlarmReciever:

SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
    String test1 = userDetails.getString("test1", "");
    String test2 = userDetails.getString("test2", "");

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

How to call JavaScript function instead of href in HTML

I use a little CSS on a span to make it look like a link like so:

CSS:

.link {
    color:blue;
    text-decoration:underline;
    cursor:pointer;
}

HTML:

<span class="link" onclick="javascript:showWindow('url');">Click Me</span>

JAVASCRIPT:

function showWindow(url) {
    window.open(url, "_blank", "directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes");
}

minimize app to system tray

This is the method I use in my applications, it's fairly simple and self explanatory but I'm happy to give more details in answer to your comments.

    public Form1()
    {
        InitializeComponent();

        // When window state changed, trigger state update.
        this.Resize += SetMinimizeState;

        // When tray icon clicked, trigger window state change.       
        systemTrayIcon.Click += ToggleMinimizeState;
    }      

    // Toggle state between Normal and Minimized.
    private void ToggleMinimizeState(object sender, EventArgs e)
    {    
        bool isMinimized = this.WindowState == FormWindowState.Minimized;
        this.WindowState = (isMinimized) ? FormWindowState.Normal : FormWindowState.Minimized;
    }

    // Show/Hide window and tray icon to match window state.
    private void SetMinimizeState(object sender, EventArgs e)
    {    
        bool isMinimized = this.WindowState == FormWindowState.Minimized;

        this.ShowInTaskbar = !isMinimized;           
        systemTrayIcon.Visible = isMinimized;
        if (isMinimized) systemTrayIcon.ShowBalloonTip(500, "Application", "Application minimized to tray.", ToolTipIcon.Info);
    }

Calling Oracle stored procedure from C#?

It's basically the same mechanism as for a non query command with:

  • command.CommandText = the name of the stored procedure
  • command.CommandType = CommandType.StoredProcedure
  • As many calls to command.Parameters.Add as the number of parameters the sp requires
  • command.ExecuteNonQuery

There are plenty of examples out there, the first one returned by Google is this one

There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection

Is there a way to crack the password on an Excel VBA Project?

The protection is a simple text comparison in Excel. Load Excel in your favourite debugger (Ollydbg being my tool of choice), find the code that does the comparison and fix it to always return true, this should let you access the macros.

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

You need the Microsoft.AspNet.WebApi.Core package.

You can see it in the .csproj file:

<Reference Include="System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.0.0\lib\net45\System.Web.Http.dll</HintPath>
</Reference>

Get current time as formatted string in Go?

https://golang.org/src/time/format.go specified For parsing time 15 is used for Hours, 04 is used for minutes, 05 for seconds.

For parsing Date 11, Jan, January is for months, 02, Mon, Monday for Day of the month, 2006 for year and of course MST for zone

But you can use this layout as well, which I find very simple. "Mon Jan 2 15:04:05 MST 2006"

    const layout = "Mon Jan 2 15:04:05 MST 2006"
    userTimeString := "Fri Dec 6 13:05:05 CET 2019"

    t, _ := time.Parse(layout, userTimeString)
    fmt.Println("Server: ", t.Format(time.RFC850))
    //Server:  Friday, 06-Dec-19 13:05:05 CET

    mumbai, _ := time.LoadLocation("Asia/Kolkata")
    mumbaiTime := t.In(mumbai)
    fmt.Println("Mumbai: ", mumbaiTime.Format(time.RFC850))
    //Mumbai:  Friday, 06-Dec-19 18:35:05 IST

DEMO

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

What is the difference between an IntentService and a Service?

Intent service is child of Service

IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.

Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication

Half circle with CSS (border, outline only)

I use a percentage method to achieve

        border: 3px solid rgb(1, 1, 1);
        border-top-left-radius: 100% 200%;
        border-top-right-radius: 100% 200%;

How do I detect whether a Python variable is a function?

The solutions using hasattr(obj, '__call__') and callable(.) mentioned in some of the answers have a main drawback: both also return True for classes and instances of classes with a __call__() method. Eg.

>>> import collections
>>> Test = collections.namedtuple('Test', [])
>>> callable(Test)
True
>>> hasattr(Test, '__call__')
True

One proper way of checking if an object is a user-defined function (and nothing but a that) is to use isfunction(.):

>>> import inspect
>>> inspect.isfunction(Test)
False
>>> def t(): pass
>>> inspect.isfunction(t)
True

If you need to check for other types, have a look at inspect — Inspect live objects.

How do I format a number to a dollar amount in PHP

In PHP and C++ you can use the printf() function

printf("$%01.2f", $money);

Have a variable in images path in Sass?

Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/

Basically, you can set your image path in config.rb and you use the image-url() helper

android studio 0.4.2: Gradle project sync failed error

I'm not using Android Studio, but had same problem. I had to update the latest java jdk and set the JAVA_HOME to that jdk.

Volatile vs. Interlocked vs. lock

Interlocked functions do not lock. They are atomic, meaning that they can complete without the possibility of a context switch during increment. So there is no chance of deadlock or wait.

I would say that you should always prefer it to a lock and increment.

Volatile is useful if you need writes in one thread to be read in another, and if you want the optimizer to not reorder operations on a variable (because things are happening in another thread that the optimizer doesn't know about). It's an orthogonal choice to how you increment.

This is a really good article if you want to read more about lock-free code, and the right way to approach writing it

http://www.ddj.com/hpc-high-performance-computing/210604448

How to retry after exception?

increment your loop variable only when the try clause succeeds

Maven: add a folder or jar file into current classpath

This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?

In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.

See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html

Easy pretty printing of floats in python?

I just ran into this problem while trying to use pprint to output a list of tuples of floats. Nested comprehensions might be a bad idea, but here's what I did:

tups = [
        (12.0, 9.75, 23.54),
        (12.5, 2.6, 13.85),
        (14.77, 3.56, 23.23),
        (12.0, 5.5, 23.5)
       ]
pprint([['{0:0.02f}'.format(num) for num in tup] for tup in tups])

I used generator expressions at first, but pprint just repred the generator...

Javascript change color of text and background to input value

Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.

First considerations are about mixing HTML, Javascript and CSS:

Why is using onClick() in HTML a bad practice?

Unobtrusive Javascript

Inline Styles vs Classes

I will be removing inline content and splitting these into their appropriate files.

Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.

Your function changeBackground sets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up in the DOM twice.

CSS

#TheForm {
    margin-left: 396px;
}
#submitColor {
    margin-left: 48px;
    margin-top: 5px;
}

HTML

<form id="TheForm">
    <input id="color" type="text" />
    <br/>
    <input id="submitColor" value="Submit" type="button" />
</form>
<span id="coltext">This text should have the same color as you put in the text box</span>

Javascript

function changeBackground() {
    var color = document.getElementById("color").value; // cached

    // The working function for changing background color.
    document.bgColor = color;

    // The code I'd like to use for changing the text simultaneously - however it does not work.
    document.getElementById("coltext").style.color = color;
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Source: w3schools

Color Values

CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).

Hex values are written as 3 double digit numbers, starting with a # sign.

Update: as pointed out by @Ian

Hex can be either 3 or 6 characters long

Source: W3C

Numerical color values

The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.

Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.

For regex testing, I will use this pattern

/^#(?:[0-9a-f]{3}){1,2}$/i

but if you were regex matching and wanted to break the numbers into groups then you would require a different pattern

function changeBackground() {
    var color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i;

    if (rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Hex Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

Here is a further modification that will allow colours by name along with by hex.

function changeBackground() {
    var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"],
        color = document.getElementById("color").value.trim(),
        rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i,
        formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase();

    if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) {
        document.getElementById("coltext").style.color = color;
    } else {
        alert("Invalid CSS Color");
    }
}

document.getElementById("submitColor").addEventListener("click", changeBackground, false);

On jsfiddle

What is the default username and password in Tomcat?

Platform NetBeans 7.3, Apache Tomcat 7.0.34 re: Tomcat Manager

I spent 3 days tracking this down because I thought I had a bad install.

On Windows and Linux, NetBeans uses a separate file location for CATALINA_BASE:

http://wiki.netbeans.org/FaqInstallationDefaultTomcatPassword

So you can modify the tomcat_user.xml under CATALINA_HOME: until your face turns blue, to no effect.

It appears that the IDE only requires, manager-script,admin roles under CATALINA_BASE:.

When I tried to add a user to the manager-gui role (to the correct tomcat_user.xml file), required for access to the Tomcat Manager, Tomcat stopped presenting the login dialog and went directly to the 401 access denied splash page.

It appears that the NetBeans package uses a locked-down version of TomCat.

I hope this saves everyone some time.

Setting PATH environment variable in OSX permanently

You have to add it to /etc/paths.

Reference (which works for me) : Here

R - " missing value where TRUE/FALSE needed "

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"

How do I horizontally center a span element inside a div

Applying inline-block to the element that is to be centered and applying text-align:center to the parent block did the trick for me.

Works even on <span> tags.

document.createElement("script") synchronously

This works for modern 'evergreen' browsers that support async/await and fetch.

This example is simplified, without error handling, to show the basic principals at work.

// This is a modern JS dependency fetcher - a "webpack" for the browser
const addDependentScripts = async function( scriptsToAdd ) {

  // Create an empty script element
  const s=document.createElement('script')

  // Fetch each script in turn, waiting until the source has arrived
  // before continuing to fetch the next.
  for ( var i = 0; i < scriptsToAdd.length; i++ ) {
    let r = await fetch( scriptsToAdd[i] )

    // Here we append the incoming javascript text to our script element.
    s.text += await r.text()
  }

  // Finally, add our new script element to the page. It's
  // during this operation that the new bundle of JS code 'goes live'.
  document.querySelector('body').appendChild(s)
}

// call our browser "webpack" bundler
addDependentScripts( [
  'https://code.jquery.com/jquery-3.5.1.slim.min.js',
  'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js'
] )

Spring REST Service: how to configure to remove null objects in json response

For all you non-xml config folks:

ObjectMapper objMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
HttpMessageConverter msgConverter = new MappingJackson2HttpMessageConverter(objMapper);
restTemplate.setMessageConverters(Collections.singletonList(msgConverter));

How to find out the MySQL root password

Unless the package manager requests you to type the root password during installation, the default root password is the empty string. To connect to freshly installed server, type:

shell> mysql -u root --password=
mysql>

To change the password, get back the unix shell and type:

shell> mysqladmin -u root --password= password root

The new password is 'root'. Now connect to the server:

shell> mysql -u root --password=
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Oops, the password has changed. Use the new one, root:

shell> mysql -u root --password=root
...
blah, blah, blah : mysql welcome banner
...
mysql> 

Bingo! New do something interesting

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

Maurycy

multiple packages in context:component-scan, spring config

The following approach is correct:

<context:component-scan base-package="x.y.z.service, x.y.z.controller" /> 

Note that the error complains about x.y.z.dao.daoservice.LoginDAO, which is not in the packages mentioned above, perhaps you forgot to add it:

<context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" /> 

Make one div visible and another invisible

Making it invisible with visibility still makes it use up space. Rather try set the display to none to make it invisible, and then set the display to block to make it visible.

Executing multiple SQL queries in one statement with PHP

Pass 65536 to mysql_connect as 5th parameter.

Example:

$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */) 
    or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);

    INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);

    DELETE FROM table3 WHERE field6 = 6;

    UPDATE table4 SET field7 = 7 WHERE field8 = 8;

    INSERT INTO table5
       SELECT t6.field11, t6.field12, t7.field13
       FROM table6 t6
       INNER JOIN table7 t7 ON t7.field9 = t6.field10;

    -- etc
");

When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid.

For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*. It is okay to use mysql_affected_rows to return how many rows inserted.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);
    SELECT * FROM table2;
");

Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    SELECT * FROM table2;
    INSERT INTO table1 (field1,field2) VALUES(1,2);
");

How to HTML encode/escape a string? Is there a built-in?

An addition to Christopher Bradford's answer to use the HTML escaping anywhere, since most people don't use CGI nowadays, you can also use Rack:

require 'rack/utils'
Rack::Utils.escape_html('Usage: foo "bar" <baz>')

HTTP GET request in JavaScript?

Ajax

You'd be best off using a library such as Prototype or jQuery.

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

How do I exclude all instances of a transitive dependency when using Gradle?

Ah, the following works and does what I want:

configurations {
  runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"
}

It seems that an Exclude Rule only has two attributes - group and module. However, the above syntax doesn't prevent you from specifying any arbitrary property as a predicate. When trying to exclude from an individual dependency you cannot specify arbitrary properties. For example, this fails:

dependencies {
  compile ('org.springframework.data:spring-data-hadoop-core:2.0.0.M4-hadoop22') {
    exclude group: "org.slf4j", name: "slf4j-log4j12"
  }
}

with

No such property: name for class: org.gradle.api.internal.artifacts.DefaultExcludeRule

So even though you can specify a dependency with a group: and name: you can't specify an exclusion with a name:!?!

Perhaps a separate question, but what exactly is a module then? I can understand the Maven notion of groupId:artifactId:version, which I understand translates to group:name:version in Gradle. But then, how do I know what module (in gradle-speak) a particular Maven artifact belongs to?

md-table - How to update the column width

I found a combination of jymdman's and Rahul Patil's answers is working best for me:

.mat-column-userId {
  flex: 0 0 75px;
}

Also, if you have one "leading" column which you want to always occupy a certain amount of space across different devices, I found the following quite handy to adopt to the available container width in a more responsive kind (this forces the remaining columns to use the remaining space evenly):

.mat-column-userName {
  flex: 0 0 60%;
}

Can scripts be inserted with innerHTML?

For anyone still trying to do this, no, you can't inject a script using innerHTML, but it is possible to load a string into a script tag using a Blob and URL.createObjectURL.

I've created an example that lets you run a string as a script and get the 'exports' of the script returned through a promise:

function loadScript(scriptContent, moduleId) {
    // create the script tag
    var scriptElement = document.createElement('SCRIPT');

    // create a promise which will resolve to the script's 'exports'
    // (i.e., the value returned by the script)
    var promise = new Promise(function(resolve) {
        scriptElement.onload = function() {
            var exports = window["__loadScript_exports_" + moduleId];
            delete window["__loadScript_exports_" + moduleId];
            resolve(exports);
        }
    });

    // wrap the script contents to expose exports through a special property
    // the promise will access the exports this way
    var wrappedScriptContent =
        "(function() { window['__loadScript_exports_" + moduleId + "'] = " + 
        scriptContent + "})()";

    // create a blob from the wrapped script content
    var scriptBlob = new Blob([wrappedScriptContent], {type: 'text/javascript'});

    // set the id attribute
    scriptElement.id = "__loadScript_module_" + moduleId;

    // set the src attribute to the blob's object url 
    // (this is the part that makes it work)
    scriptElement.src = URL.createObjectURL(scriptBlob);

    // append the script element
    document.body.appendChild(scriptElement);

    // return the promise, which will resolve to the script's exports
    return promise;
}

...

function doTheThing() {
    // no evals
    loadScript('5 + 5').then(function(exports) {
         // should log 10
        console.log(exports)
    });
}

I've simplified this from my actual implementation, so no promises that there aren't any bugs in it. But the principle works.

If you don't care about getting any value back after the script runs, it's even easier; just leave out the Promise and onload bits. You don't even need to wrap the script or create the global window.__load_script_exports_ property.

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

Setting the filter to an OpenFileDialog to allow the typical image formats?

To filter images files, use this code sample.

//Create a new instance of openFileDialog
OpenFileDialog res = new OpenFileDialog();

//Filter
res.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.gif;*.tif;...";

//When the user select the file
if (res.ShowDialog() == DialogResult.OK)
{
   //Get the file's path
   var filePath = res.FileName;
   //Do something
   ....
}

How do I check if an element is hidden in jQuery?

You can use the hidden selector:

// Matches all elements that are hidden
$('element:hidden')

And the visible selector:

// Matches all elements that are visible
$('element:visible')

AngularJS : ng-model binding not updating when changed with jQuery

Just use:

$('#selectedDueDate').val(dateText).trigger('input');

instead of:

$('#selectedDueDate').val(dateText);

How to custom switch button?

Its a simple xml design. It looks like iOS switch, check this below image

enter image description here

You need to create custom_thumb.xml and custom_track.xml

This is my switch,I need a very big switch so added layout_width/layout_height parameter

 <androidx.appcompat.widget.SwitchCompat
        android:id="@+id/swOnOff"
        android:layout_width="@dimen/_200sdp"
        android:layout_marginStart="@dimen/_50sdp"
        android:layout_marginEnd="@dimen/_50sdp"
        android:layout_marginTop="@dimen/_30sdp"
        android:layout_gravity="center"
        app:showText="true"
        android:textSize="@dimen/_20ssp"
        android:fontFamily="@font/opensans_bold"
        app:track="@drawable/custom_track"
        android:thumb="@drawable/custom_thumb"
        android:layout_height="@dimen/_120sdp"/>

Now create custom_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false">
        <shape android:shape="oval">
            <solid android:color="#ffffff"/>
            <size android:width="@dimen/_100sdp"
                android:height="@dimen/_100sdp"/>
            <stroke android:width="1dp"
                android:color="#8c8c8c"/>
        </shape>
    </item>
    <item android:state_checked="true">
        <shape android:shape="oval">
            <solid android:color="#ffffff"/>
            <size android:width="@dimen/_100sdp"
                android:height="@dimen/_100sdp"/>
            <stroke android:width="1dp"
                android:color="#34c759"/>
        </shape>
    </item>
</selector>

Now create custom_track.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false">
        <shape android:shape="rectangle">
            <corners android:radius="@dimen/_100sdp" />
            <solid android:color="#ffffff" />
            <stroke android:color="#8c8c8c" android:width="1dp"/>
            <size android:height="20dp" />
        </shape>
    </item>
    <item android:state_checked="true">
        <shape android:shape="rectangle">
            <corners android:radius="@dimen/_100sdp" />
            <solid android:color="#34c759" />
            <stroke android:color="#8c8c8c" android:width="1dp"/>
            <size android:height="20dp" />
        </shape>
    </item>
</selector>

std::queue iteration

If you need to iterate a queue ... queue isn't the container you need.
Why did you pick a queue?
Why don't you take a container that you can iterate over?


1.if you pick a queue then you say you want to wrap a container into a 'queue' interface: - front - back - push - pop - ...

if you also want to iterate, a queue has an incorrect interface. A queue is an adaptor that provides a restricted subset of the original container

2.The definition of a queue is a FIFO and by definition a FIFO is not iterable

Pass table as parameter into sql server UDF

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

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


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

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

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

What is the difference between an Instance and an Object?

Regarding the difference between an object and an instance, I do not think there is any consensus.

It looks to me like people change it pretty much interchangeably, in papers, blog posts, books or conversations.

As for me, the way I see it is, an object is a generic and alive entity in the memory, specified by the language it is used in. Just like the Object class in Java. We do not much care its type, or anything else associated with it, whether it is managed by a container or not.

An instance is an object but associated with a type, as in this method accepts Foo instances, or you can not put Animal instances in an instance of a List of Vehicles.

objects for example have locks associated with them, not instances, whereas instances have methods. objects are garbage collected, not instances.

But as I said, this is only how I see it, and I do not think there is any organisation we can refer to for a standard definition between them and everyone will pretty much have their slightly different understanding / definitions (of course within limits).

Can we execute a java program without a main() method?

Now - no


Prior to Java 7:

Yes, sequence is as follows:

  • jvm loads class
  • executes static blocks
  • looks for main method and invokes it

So, if there's code in a static block, it will be executed. But there's no point in doing that.

How to test that:

public final class Test {
    static {
        System.out.println("FOO");
    }
}

Then if you try to run the class (either form command line with java Test or with an IDE), the result is:

FOO
java.lang.NoSuchMethodError: main

How do I translate an ISO 8601 datetime string into a Python datetime object?

Both ways:

Epoch to ISO time:

isoTime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(epochTime))

ISO time to Epoch:

epochTime = time.mktime(time.strptime(isoTime, '%Y-%m-%dT%H:%M:%SZ'))

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use this in your my.ini under

[mysqldump]
    user=root
    password=anything

How to escape a while loop in C#

Use break; to escape the first loop:

if (s.Contains("mp4:production/CATCHUP/"))
{
   RemoveEXELog();
   Process p = new Process();
   p.StartInfo.WorkingDirectory = "dump";
   p.StartInfo.FileName = "test.exe"; 
   p.StartInfo.Arguments = s; 
   p.Start();
   break;
}

If you want to also escape the second loop, you might need to use a flag and check in the out loop's guard:

        boolean breakFlag = false;
        while (!breakFlag)
        {
            Thread.Sleep(5000);
            if (!System.IO.File.Exists("Command.bat")) continue;
            using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("mp4:production/CATCHUP/"))
                    {

                        RemoveEXELog();

                        Process p = new Process();
                        p.StartInfo.WorkingDirectory = "dump";
                        p.StartInfo.FileName = "test.exe"; 
                        p.StartInfo.Arguments = s; 
                        p.Start();

                        breakFlag = true;
                        break;
                    }
                }
            }

Or, if you want to just exit the function completely from within the nested loop, put in a return; instead of a break;.

But these aren't really considered best practices. You should find some way to add the necessary Boolean logic into your while guards.

Oracle client and networking components were not found

After you install Oracle Client components on the remote server, restart SQL Server Agent from the PC Management Console or directly from Sql Server Management Studio. This will allow the service to load correctly the path to the Oracle components. Otherwise your package will work on design time but fail on run time.

Localhost : 404 not found

I had the same problem and here is how it worked for me :

1) Open XAMPP control panel.

2)On the right top corner go to config > Service and Port setting and change the port (I did 81 from 80).

3)Open config in Apache just right(next) to Apache admin Option and click on that and select first one (httpd.conf) it will open in the notepad.

4) There you find port listen 80 and replace it with 81 in all place and save the file.

5) Now restart Apache and MYSql

6) Now type following in Browser : http://localhost:81/phpmyadmin/

I hope this works.

In Windows cmd, how do I prompt for user input and use the result in another command?

I am not sure if this is the case for all versions of Windows, however on the XP machine I have, I need to use the following:

set /p Var1="Prompt String"

Without the prompt string in quotes, I get various results depending on the text.

python selenium click on button

I had the same problem using Phantomjs as browser, so I solved in the following way:

driver.find_element_by_css_selector('div.button.c_button.s_button').click()

Essentially I have added the name of the DIV tag into the quote.

Grant execute permission for a user on all stored procedures in database?

Without over-complicating the problem, to grant the EXECUTE on chosen database:

USE [DB]
GRANT EXEC TO [User_Name];